篇一进行了对spingmvc的基础配置 http://www.cnblogs.com/liuyanhao/p/4798989.html
注意: 使用注解就必须在配置文件中加入<context:component-scan base-package=“包名”/>表示在该包中使用注解
@Resource(name="dataSource")
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
类似的,也可以怎样:
@Resource
private DataSource dataSource;
@Resource装配顺序
1. 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;
@Controller
@Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象。分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了@RequestMapping 注解。@Controller 只是定义了一个控制器类,而使用@RequestMapping 注解的方法才是真正处理请求的处理器。
@RequestMapping
当@RequestMapping 标记在Controller 类上的时候,里面使用@RequestMapping 标记的方法的请求地址都是相对于类上的@RequestMapping 而言的;当Controller 类上没有标记@RequestMapping 注解时,方法上的@RequestMapping 都是绝对路径。这种绝对路径和相对路径所组合成的最终路径都是相对于根路径“/ ”而言的。
@RequestMapping
RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
RequestMapping注解有六个属性,下面我们把她分成三类进行说明。
value: 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);
method: 指定请求的method类型, GET、POST、PUT、DELETE等;
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
params: 指定request中必须包含某些参数值是,才让该方法处理。
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。
-------分割线---------
这里再讲解下JdbcTemplate类
JdbcTemplate将完成JDBC核心处理流程,比如SQL语句的创建、执行,而把SQL语句的生成以及查询结果的提取工作留给我们的应用代码。
摘自Spring Framework开发参考手册:
查询(SELECT)
一个简单的例子用于展示如何获取一个表中的所有行数。
int rowCount = this.jdbcTemplate.queryForInt("select count(0) from t_accrual");
一个简单的例子展示如何进行参数绑定。
int countOfActorsNamedJoe = this.jdbcTemplate.queryForInt( "select count(0) from t_actors where first_name = ?", new Object[]{"Joe"});
查询一个 String 。
String surname = (String) this.jdbcTemplate.queryForObject( "select surname from t_actor where id = ?", new Object[]{new Long(1212)}, String.class);
查询并将结果记录为一个简单的数据模型。
Actor actor = (Actor) this.jdbcTemplate.queryForObject( "select first_name, surname from t_actor where id = ?", new Object[]{new Long(1212)}, new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { Actor actor = new Actor(); actor.setFirstName(rs.getString("first_name")); actor.setSurname(rs.getString("surname")); return actor; } });
查询并组装多个数据模型。
Collection actors = this.jdbcTemplate.query( "select first_name, surname from t_actor", new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { Actor actor = new Actor(); actor.setFirstName(rs.getString("first_name")); actor.setSurname(rs.getString("surname")); return actor; } });
更新(INSERT/UPDATE/DELETE)
this.jdbcTemplate.update( "insert into t_actor (first_name, surname) values (?, ?)", new Object[] {"Leonor", "Watling"});
this.jdbcTemplate.update( "update t_actor set weapon = ? where id = ?", new Object[] {"Banjo", new Long(5276)});
this.jdbcTemplate.update( "delete from actor where id = ?", new Object[] {new Long.valueOf(actorId)});
若仍有些知识点模糊,不要紧,让我们开始边练边学
首先,让我们梳理下整体步骤:
1)新引入jar包:commons-dbcp.jar,commons-pool.jar,mysql-connector-java.jar
2)修改applicationContext.xml,spring-servlet.xml,web.xml
3)新增service层,dao层,db-config.properties(数据源配置文件)
开始配置!
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>mvc_loginregist</display-name> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app>
db-config.propertise
db.url= jdbc:mysql://127.0.0.1/springmvc db.username=root db.password=199624 db.dirverClassName= com.mysql.jdbc.Driver
该配置文件提供数据库的属性
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- 属性文件读入 --> <bean id="db-config" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:db-config.properties</value> </list> </property> </bean> <!-- 数据源定义,使用jdbc数据源 --> <!-- 实际的JDBC连接属性从一个属性文件(properties file)解析而来,在这个属性文件里,关键字与提供的${占位符}互相对应, --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName"> <value>${db.dirverClassName}</value> </property> <property name="url"> <value>${db.url}</value> </property> <property name="username"> <value>${db.username}</value> </property> <property name="password"> <value>${db.password}</value> </property> </bean> <!-- 配置JdbcTemplate --> <bean id="template" class="org.springframework.jdbc.core.JdbcTemplate" abstract="false" lazy-init="false" autowire="default" p:dataSource-ref="dataSource" /> <!--配置View,引入p标签--> <bean id="view" class="com.htgy.view.View" p:loginSuccess="loginSuccess" p:login="login" p:regist="regist" p:registSuccess="registSuccess" p:registFail="registFail" /> </beans>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <!-- 支持JSTL标签库 --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 启用spring mvc 注解 --> <context:annotation-config /> <!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能,base-package为需要扫描的包(含所有子包)--> <context:component-scan base-package="com.htgy"/> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> </beans>
UserForm.java
package com.htgy.form; /* * 表单类 */ public class UserForm { private String account; private String password; private String passFirst; private String passSecond; private String username; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassFirst() { return passFirst; } public void setPassFirst(String passFirst) { this.passFirst = passFirst; } public String getPassSecond() { return passSecond; } public void setPassSecond(String passSecond) { this.passSecond = passSecond; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; }
User.java
package com.htgy.user; /* * 用户 */ public class User { private String account; private String username; private String password; public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
view.java
package com.htgy.view; /* * 视图类 */ //@Component @Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。 public class View { private String loginSuccess; private String registSuccess; private String registFail; private String login; private String regist; public String getLoginSuccess() { return loginSuccess; } public void setLoginSuccess(String loginSuccess) { this.loginSuccess = loginSuccess; } public String getRegistSuccess() { return registSuccess; } public void setRegistSuccess(String registSuccess) { this.registSuccess = registSuccess; } public String getRegistFail() { return registFail; } public void setRegistFail(String registFail) { this.registFail = registFail; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getRegist() { return regist; } public void setRegist(String regist) { this.regist = regist; } }
UserDAO.java
package com.htgy.userdao; /* * UserDAO接口 */ import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.List; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Component; import org.springframework.web.servlet.ModelAndView; import com.htgy.user.User; @SuppressWarnings("all") public interface UserDAO{ //一个template访问一个数据库,也可以继承JdbcDaoSupport实现 public JdbcTemplate template = null; // 此方法把USEMBO表对应的字段查询出来依次放入userPO中 // public Collection<UserPO> doquery(); // public User doquery(final String account,final String password); //按账号查询 public User queryAccount(String account); //按用户名查询 public User queryUsername(String username); //增加 public void insert(String account,String password,String username); // class UserRowMapper implements RowMapper; // public List findAllByRowMapperResultReader(String accont); }
UserDAOImpl.java
package com.htgy.userdao.impl; /* * UserDAOImpl实现 */ import java.sql.ResultSet; import java.sql.SQLException; import javax.annotation.Resource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import com.htgy.userdao.UserDAO; import com.htgy.user.User; @Repository("dao") public class UserDAOImpl implements UserDAO{ //一个template访问一个数据库,也可以继承JdbcDaoSupport实现 @Resource private JdbcTemplate template; // 此方法把USEMBO表对应的字段查询出来依次放入userPO中 // public Collection<UserPO> doquery() { // String sql = "SELECT T.USERID,T.USERNAME,T.USERAGE FROM USERMBO T"; // return super.getJdbcTemplate().query(sql, new RowMapper() { // public Object mapRow(ResultSet rs, int num) throws SQLException { // UserPO user = new UserPO(); // user.setUserId(rs.getInt("USERID")); // user.setUserName(rs.getString("USERNAME")); // user.setUserAge(rs.getInt("USERAGE")); // return user; // } // }); // public User doquery(final String account,final String password){ // User user = (User) this.template.queryForObject( // "SELECT account, password FROM user WHERE account=?", // new Object[]{account}, // new RowMapper() { // public Object mapRow(ResultSet rs, int rowNum) throws SQLException { // User user = new User(); // user.setAccount(rs.getString(account)); // user.setPassword(rs.getString(password)); // return user; // } // }); // return user; // } //按账号查询,若账号不存在则报错 @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public User queryAccount(String account){ User user = (User) this.template.queryForObject( "SELECT account, password FROM user WHERE account=?", new Object[]{account}, new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setAccount(rs.getString("account")); user.setPassword(rs.getString("password")); return user; } }); return user; } //按用户名查询,不存在则报错 @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public User queryUsername(String username){ User user = (User) this.template.queryForObject( "SELECT account, password FROM user WHERE username=?", new Object[]{username}, new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setAccount(rs.getString("account")); user.setPassword(rs.getString("password")); return user; } }); return user; } //增加用户 @Override public void insert(String account,String password,String username){ this.template.update( "INSERT INTO user (account, password,username) values (?, ?, ?)", new Object[] {account,password,username}); }
// class UserRowMapper implements RowMapper { // public Object mapRow(ResultSet rs, int index) throws SQLException { // User user = new User(); // user.setAccount(rs.getString("account")); // user.setPassword(rs.getString("password")); // return user; // } // } // // public List findAllByRowMapperResultReader(String accont) { // String sql = "SELECT * FROM USER"; // return this.template.queryForObject(sql,new UserRowMapper()); // } }
ServiceInterface.java
package com.htgy.service; /* * Service接口 @Service服务层组件,用于标注业务层组件,表示定义一个bean. * 自动根据bean的类名实例化一个首写字母为小写的bean,例如Chinese实例化为chinese,如果需要自己改名字则:@Service("你自己改的bean名")。
*/ import java.util.HashMap; public interface Serviceinterface { public boolean queryAccount(String account); public boolean queryUsername(String username); public void insert(String account,String password,String username); public boolean doquery(String account,String password); public HashMap<String, Object> dealNull(); public HashMap<String, Object> loginSuccess(); public HashMap<String, Object> error(); public HashMap<String, Object> intact(); public HashMap<String, Object> correct(); public HashMap<String, Object> consistent(); public HashMap<String, Object> accountExist(); public HashMap<String, Object> usernameExist(); }
ServiceImpl.java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.htgy.service.Serviceinterface; import com.htgy.user.User; import com.htgy.userdao.impl.UserDAOImpl; @Service("sI") //@Service服务层组件,用于标注业务层组件,表示定义一个bean. //自动根据bean的类名实例化一个首写字母为小写的bean,例如Chinese实例化为chinese,如果需要自己改名字则:@Service("你自己改的bean名")。
//此处将ServiceImpl初始化为名称为"sI"的bean public class ServiceImpl implements Serviceinterface{ @Resource private UserDAOImpl dao; //账号或密码不能为空 public HashMap<String, Object> dealNull(){ HashMap<String, Object> map = new HashMap<String,Object>(); List<String> msgList = new ArrayList<String>(); msgList.add("账号或密码不能为空"); map.put("msg", msgList); return map; } //登录成功 public HashMap<String, Object> loginSuccess(){ HashMap<String, Object> map = new HashMap<String,Object>(); List<String> msgList = new ArrayList<String>(); msgList.add("恭喜您,登录成功"); map.put("msg", msgList); return map; } //账号或密码错误 public HashMap<String, Object> error(){ HashMap<String, Object> map = new HashMap<String,Object>(); List<String> msgList = new ArrayList<String>(); msgList.add("账号或密码错误"); map.put("msg", msgList); return map; } //信息不完整 public HashMap<String, Object> intact(){ HashMap<String, Object> map = new HashMap<String,Object>(); List<String> msgList = new ArrayList<String>(); msgList.add("请将信息填写完整"); map.put("msg", msgList); return map; } //信息不正确 public HashMap<String, Object> correct(){ HashMap<String, Object> map = new HashMap<String,Object>(); List<String> msgList = new ArrayList<String>(); msgList.add("请正确填写信息"); map.put("msg", msgList); return map; } //密码不一致 public HashMap<String, Object> consistent(){ HashMap<String, Object> map = new HashMap<String,Object>(); List<String> msgList = new ArrayList<String>(); msgList.add("两次输入的密码不一致"); map.put("msg", msgList); return map; } //账号存在 public HashMap<String, Object> accountExist(){ HashMap<String, Object> map = new HashMap<String,Object>(); List<String> msgList = new ArrayList<String>(); msgList.add("账号已存在"); map.put("msg", msgList); return map; } //用户名存在 public HashMap<String, Object> usernameExist(){ HashMap<String, Object> map = new HashMap<String,Object>(); List<String> msgList = new ArrayList<String>(); msgList.add("用户名已存在"); map.put("msg", msgList); return map; } //按账号查询 public boolean queryAccount(String account){ try{ dao.queryAccount(account); return true; }catch(Exception e){ return false; } } //按用户名查询 public boolean queryUsername(String username){ try{ dao.queryUsername(username); return true; }catch(Exception e){ return false; } } //查询 public boolean doquery(String account,String password){ try{ User user=dao.queryAccount(account); if(user.getAccount().equals(account)&&user.getPassword().equals(password)){ return true; } else{ return false; } }catch(Exception e){ return false; } } //查找 public void insert(String account,String password,String username){ dao.insert(account,password,username); } }
LRController.java
package com.htgy.actions; /* * Controller类 */ import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.htgy.form.UserForm; import com.htgy.service.impl.ServiceImpl; import com.htgy.view.View; @Controller //@Controller用于标注控制层组件(如struts中的action) public class LRController { @Resource private ServiceImpl sI; @Resource private View view; //跳转到注册页面 @RequestMapping("/toRegist") // 请求URL地址映射 public ModelAndView toRegist(){ return new ModelAndView("regist"); // 手动实例化ModelAndView完成跳转页面,效果等同于下面返回字符串的方法 //return new ModelAndView(new RedirectView("../index.jsp")); 采用重定向方式跳转页面 //return new ModelAndView("redirect:../index.jsp"); 另一种简单的方法 } //跳转到登录页面 @RequestMapping({"/","/toLogin"}) // "/"表示访问首页的请求 public String toLogin(){ return "login"; } //登录 @RequestMapping("/doLogin") protected ModelAndView doLogin(UserForm userForm){ // request和response不必非要出现在方法中,如果用不上的话可以去掉 // 支持参数为表单对象 String account = userForm.getAccount(); String password = userForm.getPassword(); if(account.equals("")&&password.equals("")){ return new ModelAndView(view.getLogin(),sI.dealNull()); } else if(sI.doquery(account,password)){ return new ModelAndView(view.getLoginSuccess(),sI.loginSuccess()); } else{ return new ModelAndView(view.getLogin(),sI.error()); } } //注册 @RequestMapping("/doRegist") protected ModelAndView doRegist(UserForm userform){ String account = userform.getAccount(); String passFirst = userform.getPassFirst(); String passSecond = userform.getPassSecond(); String username = userform.getUsername(); //判断 if(account.equals("")||passFirst.equals("") ||passSecond.equals("")||username.equals("")){ return new ModelAndView(view.getRegist(),sI.intact()); } else if(account.length()<4||passFirst.length()<4 ||passSecond.length()<4){ return new ModelAndView(view.getRegist(),sI.correct()); } else if(!passFirst.equals(passSecond)){ return new ModelAndView(view.getRegist(),sI.consistent()); } else if(sI.queryAccount(account)){ return new ModelAndView(view.getRegist(),sI.accountExist()); } else if(sI.queryUsername(username)){ return new ModelAndView(view.getRegist(),sI.usernameExist()); } else{ sI.insert(account,passFirst,username); return new ModelAndView(view.getRegistSuccess()); } } }
剩下的就只需配置Jsp页面了,在篇一中已经配置
1)注解 @Controller 的基本目标是担任所注解的类的原型的角色,指明它的职责。 Dispatcher将会在这样被注解的类中扫描映射的方法,探测注解 @RequestMapping
@Controller 只是定义了一个控制器类,而使用@RequestMapping 注解的方法才是真正处理请求的处理器.使用@Controller后就无需继SimpleFormController
2)@Service用于标注业务层组件
@Controller用于标注控制层组件(如struts中的action)
@Repository用于标注数据访问组件,即DAO组件
@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
------本篇为笔者原创,未经允许不得转载--------