1.导入jar包
1.1 spring面向切面jar包
com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
1.2 springJDBCjar包
c3p0-0.9.2.1.jar
mchange-commons-java-0.2.3.4.jar
spring-jdbc-4.2.2.RELEASE.jar
1.3 mybatis与spring整合jar包
mybatis-3.2.2.jar
mybatis-spring-1.2.1.jar
1.4 mysql数据库jar包
mysql-connector-java-5.0.8-bin.jar
1.5 springAOP及springMVCjar包
commons-logging-1.1.3.jar
spring-aop-4.2.2.RELEASE.jar
spring-beans-4.2.2.RELEASE.jar
spring-context-4.2.2.RELEASE.jar
spring-core-4.2.2.RELEASE.jar
spring-expression-4.2.2.RELEASE.jar
spring-tx-4.2.2.RELEASE.jar
spring-web-4.2.2.RELEASE.jar
spring-webmvc-4.2.2.RELEASE.jar
1.6 js标签库jar包
jstl.jar
standard.jar
1.7 文件上传jar包
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
1.8 springMVC与ajax交互jar包
jackson-annotations-2.2.1.jar
jackson-core-2.2.1.jar
jackson-databind-2.2.1.jar
2.配置spring的xml文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:tx="http://www.springframework.org/schema/tx" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context.xsd 11 http://www.springframework.org/schema/tx 12 http://www.springframework.org/schema/tx/spring-tx.xsd 13 http://www.springframework.org/schema/aop 14 http://www.springframework.org/schema/aop/spring-aop.xsd"> 15 16 <!-- 包扫描 *业务层 --> 17 <context:component-scan base-package="com.eduask.liusheng.service"/> 18 19 <!-- 引入属性文件 *数据源属性及连接池属性 --> 20 <context:property-placeholder location="classpath:db.properties"/> 21 22 <!-- 配置数据源 --> 23 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 24 <property name="driverClass" value="${jdbc.driver}"></property> 25 <property name="jdbcUrl" value="${jdbc.url}"></property> 26 <property name="user" value="${jdbc.username}"></property> 27 <property name="password" value="${jdbc.password}"></property> 28 </bean> 29 30 <!-- 配置SQLSessionFactory --> 31 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 32 <!-- 注入数据库连接池 --> 33 <property name="dataSource" ref="dataSource"/> 34 <!-- 扫描实体类包,使用别名 --> 35 <property name="typeAliasesPackage" value="com.eduask.liusheng.bean"/> 36 <!-- 扫描映射文件 --> 37 <property name="mapperLocations" value="classpath:com/eduask/liusheng/mapper/*.xml"/> 38 </bean> 39 40 <!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 --> 41 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 42 <!-- 注入sqlSessionFactory --> 43 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> 44 <!-- 给出需要扫描Dao接口包,自动生成对应实体,不用手动实现 --> 45 <property name="basePackage" value="com.eduask.liusheng.dao"/> 46 </bean> 47 48 <!-- 配置事务管理器 --> 49 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 50 <property name="dataSource" ref="dataSource"></property> 51 </bean> 52 53 <!-- 配置事务通知 *如果是注解方式,需要配置事务管理注解驱动--> 54 <tx:advice id="advice" transaction-manager="transactionManager"> 55 <tx:attributes> 56 <tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT" read-only="false"/> 57 <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" read-only="false"/> 58 <tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" read-only="false"/> 59 <tx:method name="select*" read-only="true"/> 60 <tx:method name="*" read-only="true"/> 61 </tx:attributes> 62 </tx:advice> 63 64 <!-- 配置切点 --> 65 <aop:config> 66 <!-- 配置切点 --> 67 <aop:pointcut expression="execution(* com.eduask.liusheng.service.*.*(..))" id="pointcut"/> 68 <!-- 关联切点与通知 --> 69 <aop:advisor advice-ref="advice" pointcut-ref="pointcut"/> 70 </aop:config> 71 72 </beans>
1 jdbc.driver=com.mysql.jdbc.Driver 2 jdbc.url=jdbc:mysql://localhost:3306/employeemanager 3 jdbc.username=root 4 jdbc.password=root 5 #连接池属性在这里配置
3.配置springMVC的xml文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context.xsd 10 http://www.springframework.org/schema/mvc 11 http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 12 13 <!-- 配置包扫描 *控制器层 注意:扫描包为com.eduask.liusheng时,会使Service事物管理失效,需要加限制条件context:exclude-filter--> 14 <context:component-scan base-package="com.eduask.liusheng.controller"/> 15 16 <!-- 配置视图解析器 *受保护的网页放在/WEB-INF下,不能被直接访问,只能请求转发到该页面 --> 17 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 18 <property name="prefix" value="/WEB-INF/view/"></property> 19 <property name="suffix" value=".jsp"></property> 20 </bean> 21 22 <!-- 访问静态资源 js jpg html css 等静态资源 --> 23 <mvc:default-servlet-handler/> 24 25 <!-- 配置登陆拦截器 --> 26 <mvc:interceptors> 27 <mvc:interceptor> 28 <mvc:mapping path="/**"/> 29 <bean class="com.eduask.liusheng.inerceptor.LoginInterceptor"></bean> 30 </mvc:interceptor> 31 </mvc:interceptors> 32 33 <!-- 配置全局时间转化类 没有时间转化可省略以下 --> 34 <!-- 第一步: 创建自定义日期转换规则 class:为时间转化类的全类名 --> 35 <bean id="dateConvert" class="com.eduask.liusheng.util.DateConvert"/> 36 <!-- 第二步: 创建convertion-Service ,并注入dateConvert--> 37 <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 38 <property name="converters"> 39 <set> 40 <ref bean="dateConvert"/> 41 </set> 42 </property> 43 </bean> 44 <!-- 第三步:注册处理器映射器/处理器适配器 ,添加conversion-service属性--> 45 <mvc:annotation-driven conversion-service="conversionService"/> 46 47 <!-- 配置文件上传的映射 *id必须为multipartResolver --> 48 <bean id="multipartResolver" 49 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 50 <!-- 配置上传的大小 --> 51 <property name="maxUploadSize" value="104857600"></property> 52 <!-- 配置缓存 --> 53 <property name="maxInMemorySize" value="4096" /> 54 <!-- 配置上传的编码 --> 55 <property name="defaultEncoding" value="utf-8"></property> 56 </bean> 57 58 </beans>
1 import java.text.ParseException; 2 import java.text.SimpleDateFormat; 3 import java.util.Date; 4 5 import org.springframework.core.convert.converter.Converter; 6 7 public class DateConvert implements Converter<String, Date> { 8 9 @Override 10 public Date convert(String stringDate){ 11 //时间转化类(时间格式) 12 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); 13 try { 14 return simpleDateFormat.parse(stringDate); 15 } catch (ParseException e) { 16 e.printStackTrace(); 17 } 18 return null; 19 } 20 21 }
1 import java.io.File; 2 import java.io.FileOutputStream; 3 4 import javax.servlet.http.HttpServletRequest; 5 6 import org.springframework.stereotype.Controller; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 import org.springframework.web.bind.annotation.RequestParam; 9 import org.springframework.web.multipart.MultipartFile; 10 import org.springframework.web.multipart.MultipartHttpServletRequest; 11 import org.springframework.web.multipart.commons.CommonsMultipartFile; 12 13 @Controller 14 public class UploadController { 15 @RequestMapping("/upload1.do") 16 public String upload(HttpServletRequest req) throws Exception{ 17 long startTime=System.currentTimeMillis(); 18 MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)req; 19 MultipartFile multiFile=multiRequest.getFile("myfile1"); 20 String path=req.getSession().getServletContext().getRealPath("/upload"); 21 File file=new File(path+"\"+multiFile.getOriginalFilename()); 22 FileOutputStream fos=new FileOutputStream(file); 23 fos.write(multiFile.getBytes()); 24 fos.flush(); 25 fos.close(); 26 long endTime=System.currentTimeMillis(); 27 System.out.println("upload1运行时间:"+String.valueOf(endTime-startTime)+"ms"); 28 return "a"; 29 } 30 31 @RequestMapping("/upload2.do") 32 public String upload1(@RequestParam("myfile2") CommonsMultipartFile file,HttpServletRequest req) throws Exception{ 33 long startTime=System.currentTimeMillis(); 34 String path=req.getSession().getServletContext().getRealPath("/upload"); 35 File uploadfile=new File(path+"\"+file.getOriginalFilename()); 36 file.transferTo(uploadfile); 37 long endTime=System.currentTimeMillis(); 38 System.out.println("upload2运行时间:"+String.valueOf(endTime-startTime)+"ms"); 39 return "a"; 40 } 41 42 @RequestMapping("/upload3.do") 43 public String upload3(HttpServletRequest req) throws Exception{ 44 long startTime=System.currentTimeMillis(); 45 MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)req; 46 MultipartFile multiFile=multiRequest.getFile("myfile3"); 47 String path=req.getSession().getServletContext().getRealPath("/upload"); 48 File file=new File(path+"\"+multiFile.getOriginalFilename()); 49 multiFile.transferTo(file); 50 long endTime=System.currentTimeMillis(); 51 System.out.println("upload3运行时间:"+String.valueOf(endTime-startTime)+"ms"); 52 return "a"; 53 } 54 55 }
1 import java.io.PrintWriter; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.ResponseBody; 6 7 @Controller 8 public class AjaxController { 9 10 @RequestMapping("/fun1.do") 11 public void fun1(PrintWriter out,User user){ 12 System.out.println(user); 13 out.print("你好"); 14 } 15 16 @RequestMapping("/fun2.do") 17 @ResponseBody 18 public User fun2(User user){ 19 return user; 20 } 21 22 }
1 import javax.servlet.http.HttpServletRequest; 2 import javax.servlet.http.HttpServletResponse; 3 4 import org.springframework.web.servlet.HandlerInterceptor; 5 import org.springframework.web.servlet.ModelAndView; 6 7 8 public class LoginInterceptor implements HandlerInterceptor { 9 10 /** 11 * preHandle方法是进行处理器拦截用的,顾名思义,该方法将在Controller处理之前进行调用, 12 * SpringMVC中的Interceptor拦截器是链式的,可以同时存在多个Interceptor, 13 * 然后SpringMVC会根据声明的前后顺序一个接一个的执行, 14 * 而且所有的Interceptor中的preHandle方法都会在Controller方法调用之前调用。 15 * SpringMVC的这种Interceptor链式结构也是可以进行中断的, 16 * 这种中断方式是令preHandle的返回值为false,当preHandle的返回值为false的时候整个请求就结束了。 17 */ 18 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 19 Object o) throws Exception { 20 System.out.println("----------preHandle------------"); 21 String path=request.getServletPath(); 22 System.out.println("path:"+path); 23 if("/login.do".equals(path)){ 24 return true; 25 } 26 if("/logout.do".equals(path)){ 27 request.getSession().removeAttribute("user"); 28 } 29 String str=(String) request.getSession().getAttribute("user"); 30 if (str!=null) { 31 return true; 32 }else{ 33 response.sendRedirect("login.jsp"); 34 return false; 35 } 36 } 37 38 /** 39 * 这个方法只会在当前这个Interceptor的preHandle方法返回值为true的时候才会执行。 40 * postHandle是进行处理器拦截用的,它的执行时间是在处理器进行处理之后, 41 * 也就是在Controller的方法调用之后执行,但是它会在DispatcherServlet进行视图的渲染之前执行, 42 * 也就是说在这个方法中你可以对ModelAndView进行操作。 43 * 这个方法的链式结构跟正常访问的方向是相反的,也就是说先声明的Interceptor拦截器该方法反而会后调用, 44 * 这跟Struts2里面的拦截器的执行过程有点像, 45 * 只是Struts2里面的intercept方法中要手动的调用ActionInvocation的invoke方法, 46 * Struts2中调用ActionInvocation的invoke方法就是调用下一个Interceptor 47 * 或者是调用action,然后要在Interceptor之前调用的内容都写在调用invoke之前, 48 * 要在Interceptor之后调用的内容都写在调用invoke方法之后。 49 */ 50 public void postHandle(HttpServletRequest request, HttpServletResponse response, 51 Object o, ModelAndView ex) throws Exception { 52 System.out.println("----------postHandle------------"); 53 } 54 55 /** 56 * 该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行。 57 * 该方法将在整个请求完成之后,也就是DispatcherServlet渲染了视图执行, 58 * 这个方法的主要作用是用于清理资源的,当然这个方法也只能在当前这个Interceptor的preHandle方法的返回值为true时才会执行。 59 */ 60 public void afterCompletion(HttpServletRequest request, 61 HttpServletResponse response, Object o, Exception ex) 62 throws Exception { 63 System.out.println("----------afterCompletion------------"); 64 } 65 66 }
4.配置web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 3 <display-name>EmployeeManager</display-name> 4 <welcome-file-list> 5 <welcome-file>index.html</welcome-file> 6 <welcome-file>index.htm</welcome-file> 7 <welcome-file>index.jsp</welcome-file> 8 <welcome-file>default.html</welcome-file> 9 <welcome-file>default.htm</welcome-file> 10 <welcome-file>default.jsp</welcome-file> 11 </welcome-file-list> 12 13 <!-- 配置前端控制器 和 springMVC-servlet 的配置文件引入--> 14 <servlet> 15 <servlet-name>springMVC</servlet-name> 16 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 17 <init-param> 18 <param-name>contextConfigLocation</param-name> 19 <param-value>classpath:springMVC-servlet.xml</param-value> 20 </init-param> 21 <load-on-startup>1</load-on-startup> 22 </servlet> 23 <servlet-mapping> 24 <servlet-name>springMVC</servlet-name> 25 <url-pattern>/*</url-pattern> 26 </servlet-mapping> 27 28 <!-- 设置servlet所有编码的过滤器 --> 29 <filter> 30 <filter-name>CharacterEncodingFilter</filter-name> 31 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 32 <init-param> 33 <param-name>encoding</param-name> 34 <param-value>utf-8</param-value> 35 </init-param> 36 <init-param> 37 <param-name>forceEncoding</param-name> 38 <param-value>true</param-value> 39 </init-param> 40 </filter> 41 <filter-mapping> 42 <filter-name>CharacterEncodingFilter</filter-name> 43 <url-pattern>/*</url-pattern> 44 </filter-mapping> 45 46 <!-- 配置监听器 --> 47 <listener> 48 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 49 </listener> 50 51 <!-- Spring配置文件的引入 --> 52 <context-param> 53 <param-name>contextConfigLocation</param-name> 54 <param-value>classpath:applicationContext.xml</param-value> 55 </context-param> 56 57 </web-app>
注意:配置error page时,如果不跳转到error页面,可能是浏览器选项中,高级-显示友好页面信息未取消勾选