spring mvc最大的好处就在于它可以基于一整套的注解,完成业务功能!
需要配置的地方有:
1,web.xml,包括 url 拦截器,中文过滤器,监听器请看如下代码:
<?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></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spitter</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>//spring 的servlet 负责映射请求的
<load-on-startup>1</load-on-startup>//项目启动的时候就加载
</servlet>
<servlet-mapping>
<servlet-name>spitter</servlet-name>
<url-pattern>/</url-pattern>//过滤/
</servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>//中文过滤器
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>//设置字符集
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>//过滤的请求
</filter-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml//加载spring配置的文件
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>//监听spring 的listener
</listener>
</web-app>
这是web.xml 的配置,此处的配置与struts+spring 的配置基本相同只是org.springframework.web.servlet.DispatcherServlet 这个类不同及加了org.springframework.web.filter.CharacterEncodingFilter的中文过滤器
如果说没有其他配置的情况下
那么该项目启动时会在web-inf 下查找 spitter-servlet.xml 的文件具体的命名规则是[servlet-name]-servlet.xml;切记这个文件不用在applicationContext.xml导入这个文件spring会自动导入它
接下来是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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
">
<!-- <import resource="applicationContext-security.xml"/>-->
<mvc:annotation-driven/> // 这个是spring mvc 基于注解能进行的关键
<context:annotation-config /> // 这个是支持spring 关于bean的注解
<!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 -->
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<context:component-scan base-package="com"></context:component-scan>
<!-- Aspect声明 -->
<aop:aspectj-autoproxy />
<!-- 注解事务 -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="false" />
<property name="locations">
<list>
<!-- 标准配置 -->
<!--<value>classpath*:/application.properties</value> -->
<value>classpath:/confing.properties</value>
</list>
</property>
</bean>
//链接池
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass">
<value>${dirverClass}</value>
</property>
<property name="jdbcUrl">
<value>${url}</value>
</property>
<property name="user">
<value>${user}</value>
</property>
<property name="password">
<value>${password}</value>
</property>
</bean>
//整合hibernate3 的sessionfactory,也是能基于注解的
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
//能被注解的目录
<property name="packagesToScan">
<list>
<value>com.*</value>
</list>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
<property name="cacheQueries" value="true"/>
<property name="fetchSize" value="100"/>
<property name="maxResults" value="1000"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
</beans>
这个示例性的项目DAO层是基于hibernate的所以说会有一部分时关于spring 及 hibernate的
以实现完全的注解方式,注意 一定要将
<mvc:annotation-driven/>写在这个文件里因为,当服务器启动时会将所有的bean先加载,加入bean的线程池中,放在spitter-servlet.xml 会造成延迟从而导致无法映射url
以下是config.xml 这个文件里包含相关的配置参数
dirverClass=com.mysql.jdbc.Driver
user=root
password=
url=jdbc\:mysql\://localhost\:3306/test?useUnicode\=true&characterEncoding\=UTF-8
minPoolSize=5
maxPoolSize=10
initialPoolSize=5
maxIdleTime=25000
acquireIncrement=1
acquireRetryAttempts=30
acquireRetryDelay=1000
testConnectionOnCheckin=true
idleConnectionTestPeriod=18000
checkoutTimeout=50000
hibernate.hbm2ddl.auto=update //这里是update 以保证当服务器启动时会默认检查 bean,以生成新表,或更改字段,开发完成后建议修改
hibernate.show_sql=true
hibernate.cache.use_query_cache=false
接下来就是orm部分了看代码(get set 方法省略)
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import org.hibernate.annotations.GenericGenerator;
@Entity//标记该类为一个orm的实体类
@Table(name="tn_user")//所对应的table
public class User implements Serializable{
@GenericGenerator(name = "generator", strategy = "uuid")
@Id
@GeneratedValue(generator = "generator")
@Column(name = "id", unique = true, nullable = false, length = 32)
private String id;//设定自增长序列,注解非空
@Size(min=6,max=10,message="账号必须在6-10之间")
@Column(name="account",length=32) //name 为列名,length为长度,类型自动对应
private String account;
@Size(min=6,max=10,message="密码必须在6-10之间")// JSR 验证设定最大与最小长度
@Column(name="password",length=32)
private String password;
@Size(max=8,min=2,message="真实姓名长度必须在2-8之间")
@Column(name="trueName",length=32)
private String trueName;
@Column(name="telNum",length=11)
private String telNum;
@Column(name="authChar",length=8)
private String authChar;
@Column(name="homeId",length=32)
private String homeId;
该类为Object对表的对象 验证此处不再赘述,百度上很多,在服务器启动的时候,会检索数据库如果没有tn_user 表 会自动创建,如果有这个表了但是没有其中的一列,那么会自动添加该列,且原有数据不变,注意该类一定要在com下因为在sesionfactory时候设置,否则不会有效果
dao层接口:
package com.dao;
import java.util.List;
import com.bean.User;
public interface UserDao {
void addUser(User user)throws Exception;
User getUser(String id)throws Exception;
User getUserByAccout(String account)throws Exception;
void updateUser(User user)throws Exception;
List<User> listUserByHomeId(String homeId)throws Exception;
}
dao 层接口实现
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.bean.User;
import com.dao.UserDao;
@Repository//专门用来注册dao 层
public class UserDaoImpl implements UserDao {
@Autowired //注入hibernateTemplate 默认情况Type,该变量必须有get 和set 方法
private HibernateTemplate template;
public void addUser(User user) throws Exception {
template.save(user);
}
public User getUser(String id) throws Exception {
return template.get(User.class, id);
}
public User getUserByAccout(String account) throws Exception {
String hql="from User as u where u.account='"+account+"'";
List<User> users=template.find(hql);
return users!=null&&!users.isEmpty()?users.get(0):new User();
}
/**
*系统生成.
* @return the template
*/
public HibernateTemplate getTemplate() {
return template;
}
/**
*系统生成.
* @param template the template to set
*/
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
public void updateUser(User user) throws Exception {
template.update(user);
}
public List<User> listUserByHomeId(String homeId) throws Exception {
String hql="from User as u where u.homeId='"+homeId+"'";
List<User> users = template.find(hql);
return users!=null?users:new ArrayList<User>();
}
}
该类中用了 @Autowired 标签 该标签的功能是按照类型注入
@Repository 用于注册dao的bean 但是这不是强制性的,更多的情况下只是为了区分dao层与别的层
service
接口
import java.util.List;
import com.bean.User;
public interface UserService {
void saveUser(User user)throws Exception;
User getUser(String id)throws Exception;
User login(String passWord,String account)throws Exception;
void update(User user)throws Exception;
List<User> listUserByHost(User Host) throws Exception;
}
接口实现类
package com.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bean.User;
import com.dao.UserDao;
import com.service.UserService;
@Service //service 用于标记业务层
public class UserServiceImpl implements UserService {
@Autowired // 注入userdao
private UserDao userDao;
public void saveUser(User user) throws Exception {
userDao.addUser(user);
}
public User getUser(String id) throws Exception {
return userDao.getUser(id);
}
public User login(String passWord, String account) throws Exception {
User user = userDao.getUserByAccout(account);
if(passWord.equals(user.getPassword())){
return user;
}
return null;
}
/**
*系统生成.
* @return the userDao
*/
public UserDao getUserDao() {
return userDao;
}
/**
*系统生成.
* @param userDao the userDao to set
*/
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void update(User user) throws Exception {
userDao.updateUser(user);
}
public List<User> listUserByHost(User Host) throws Exception {
return userDao.listUserByHomeId(Host.getHomeId());
}
}
@Service 用于注册业务层的bean,当然跟@Repository 一样不是强制性的只是区分
接下来就是Controller 的看代码
package com.controller;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.bean.Home;
import com.bean.User;
import com.service.HomeService;
import com.service.UserService;
@Controller //标记这是一个控制器,这个是强制性的
@RequestMapping(value="/user") //映射url,这个类的所有被@RequestMapping注释的方法都会映射/user 为开头的url 相当与struts2 的namespace
public class UserManagent {
@Autowired //注入
private UserService userService;
@Autowired
private HomeService homeService;
@RequestMapping(value="/login",method=RequestMethod.POST) //映射 /user/login 的请求,method 标记以何种方式提交
public String login(String passWord,String account,HttpSession session)throws Exception{
User user=userService.login(passWord, account);
if(user!=null){
session.setAttribute("user",user);
return "redirect:Welcome";//成功之后 redirect 到/user/welcome
}
return "index";// 要不然就返回index.jsp
}
@RequestMapping(value="/home",method=RequestMethod.GET)
public String home()throws Exception{
return "index";
}
//增加用户的第一步,先把一个user 放进 model里以完成user的自动装配,model不能在url之间传递
@RequestMapping(value="/createUser")
public String createUser(Model model,String authChar)throws Exception{
User user = new User();
user.setAuthChar(authChar);
model.addAttribute("user",user);
return "view/createUser";
}
//存储用户
@RequestMapping(value="/saveUser",method=RequestMethod.POST)
//@Valid 表示user需要被验证,验证的规则是 jsr 上文已经写了几个简单的验证标记
//@BindingResult 必须在被验证的对象之后,以反映出前一个参数的验证结果
//在spring 的mvc中,request,session等对象以参数方式传入,不象action2,是通过servletActionContext对象获取的
public String saveUser(@Valid User user,BindingResult bindingResult,Model model,HttpSession session)throws Exception{
if(bindingResult.hasErrors()){ //是否有错误信息
model.addAttribute("bindingResult",bindingResult);//此处可以没有,我写了一个jsp标签专门用于显示错误信息,springMvc也有自带标签
return "view/createUser";
}
if(user.getAuthChar().equals("update")){
User host = (User) session.getAttribute("user");
user.setHomeId(host.getHomeId());
}else{
session.setAttribute("user", user);
}
userService.saveUser(user);
return "redirect: Welcome";
}
@RequestMapping(value="/Welcome",method=RequestMethod.GET)
public String welcomeUser(HttpSession session,Model model)throws Exception{
if (session.getAttribute("user") == null) {
return "redirect: home";
}
User user = (User) session.getAttribute("user");
int isCreateHome = homeService.isAllowCreateHome(user.getId());
model.addAttribute("isCreateHome",isCreateHome);
Home home = homeService.getHome(user.getHomeId());
model.addAttribute("home",home);
model.addAttribute("users", userService.listUserByHost(user));
return "Wecome";
}
/**
*系统生成.
* @return the userService
*/
public UserService getUserService() {
return userService;
}
/**
*系统生成.
* @param userService the userService to set
*/
public void setUserService(UserService userService) {
this.userService = userService;
}
/**
*系统生成.
* @return the homeService
*/
public HomeService getHomeService() {
return homeService;
}
/**
*系统生成.
* @param homeService the homeService to set
*/
public void setHomeService(HomeService homeService) {
this.homeService = homeService;
}
// 以上 的部分就是控制器的部分,需要注意的是RequestMethod.GET是默认的方法,
//get,和post 可以用不同的方法控制,注意区分
//关于from 增加一个bean需要在model添加,才能进行自动的装配,这与strut2自动装配的方式是不同的
//对于视图显示的部分最好是用jsp的标签,因为,它足够全面,速度快,可以自己开发标签
//struts2 开发标签不对外开放
//视图显示部分在源码中查看,该源码中还包含有简单的aop
//需要安装mysql数据库并且有test database,才能自动建表,或修改
//源码地址 http://pan.baidu.com/s/1hqgds8k