首页 > 代码库 > SpringMVC案例3----spring3.0项目拦截器、ajax、文件上传应用
SpringMVC案例3----spring3.0项目拦截器、ajax、文件上传应用
依然是项目结构图和所需jar包图:
显示配置文件hib-config.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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/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 "> <context:component-scan base-package="com.sxt"></context:component-scan> <!-- 支持aop注解 --> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value=http://www.mamicode.com/"com.mysql.jdbc.Driver">>
再是springmvc-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:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <!-- 対web包中的全部的类进行扫描,以完毕bean的创建和自己主动依赖输入功能 --> <context:component-scan base-package="com.sxt"></context:component-scan> <!-- 启动springmvc的注解功能,完毕请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="cacheSeconds" value=http://www.mamicode.com/"0">>
web.xml<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/hib-config.xml,/WEB-INF/springmvc-servlet.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>dao层的userDaopackage com.sxt.dao; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; import com.sxt.po.User; @Repository("userDao") public class UserDao { @Autowired private HibernateTemplate hibernateTemplate ; public void add(User u){ System.out.println("userDao.add()"); hibernateTemplate.save(u) ; } }
模型层的user类package com.sxt.po; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class User { private int id ; private String name ; private String pwd ; public User(){} public User(String name,String pwd){ this.name = name ; this.pwd = pwd ; } @Id @GeneratedValue(strategy=GenerationType.AUTO) public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }
service层的userService类package com.sxt.service; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sxt.dao.UserDao; import com.sxt.po.User; @Service("userService") public class UserService { @Autowired private UserDao userDao ; public void add(String name){ System.out.println("UserService.add()"); User u = new User() ; u.setName(name) ; userDao.add(u) ; } }controller层的userController类package com.sxt.action; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import com.sxt.service.UserService; @org.springframework.stereotype.Controller("userController") @RequestMapping("/user.do") @SessionAttributes({"uname"}) public class UserController{ @Autowired private UserService userService ; @RequestMapping(params="method=reg") public String reg(String uname){ System.out.println("UserController.reg()"); userService.add(uname) ; return "index" ; } @RequestMapping(params="method=reg2") public String reg2(@RequestParam("uname")String name,ModelMap map){ System.out.println("UserController.reg2()"); userService.add(name) ; map.put("b", "bbb") ; return "index" ; } @RequestMapping(params="method=reg3") public String reg3(String uname,ModelMap map){ System.out.println("UserController.reg3()"); userService.add(uname) ; System.out.println(uname); map.put("uname", uname) ; return "index" ; } @RequestMapping(params="method=reg4") public String reg4(String uname,ModelMap map){ System.out.println("UserController.reg4()"); // return "forward:user.do?method=reg3" ; //转发,不写默认就是转发 return "redirect:http://www.baidu.com" ;//重定向 } @RequestMapping(params="method=reg5") public String reg5(String uname){ System.out.println("UserController.reg4()"); return "redirect:http://www.baidu.com" ;//重定向 } }
MyAjaxController类package com.sxt.action; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.sxt.po.User; @Controller @RequestMapping("myajax.do") public class MyAjaxController { @RequestMapping(params="method=test2",method=RequestMethod.GET) public @ResponseBody List<User> test1(String uname) throws Exception{ String uname2 = new String(uname.getBytes("iso8859-1"),"utf-8") ; System.out.println(uname2); System.out.println("MyAjaxController.test1()"); List<User> list = new ArrayList<User>() ; list.add(new User("吴海旭","123")) ; list.add(new User("韩敬琼","456")) ; System.out.println(list.size()); return list ; } }
FileUoLoadController类package com.sxt.action; import java.io.File; import java.util.Date; import javax.servlet.ServletContext; import org.apache.log4j.chainsaw.Main; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.context.ServletContextAware; import org.springframework.web.multipart.commons.CommonsMultipartFile; @Controller("fileUpLoadController") public class FileUpLoadController implements ServletContextAware{ private ServletContext servletContext ; @Override public void setServletContext(ServletContext servletContext) { // TODO Auto-generated method stub this.servletContext = servletContext ; } @RequestMapping(value=http://www.mamicode.com/"/upload.do",method=RequestMethod.POST)>
拦截器层的MyInterceptor类package com.sxt.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class MyInterceptor implements HandlerInterceptor{ @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { // TODO Auto-generated method stub System.out.println("最后运行,一般用于释放资源!!!"); } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // TODO Auto-generated method stub System.out.println("action运行之后,生成视图之前!。"); } @Override public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { // TODO Auto-generated method stub System.out.println("action之前运行"); return true; } }
MyInterceptor2类package com.sxt.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class MyInterceptor2 extends HandlerInterceptorAdapter{ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // TODO Auto-generated method stub System.out.println("MyInterceptor2.preHandle()"); return true; } }
用于測试ajax的a.jsp文件<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'a.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script> function createAjaxObj(){ var req ; if(window.XMLHttpRequest){ req = new XMLHttpRequest() ; }else{ req = new ActiveXObject("Msxml2.XMLHTTP") ; } return req ; } function sendAjaxReq(){ var req = createAjaxObj() ; req.open("get","myajax.do?method=test2&uname=张三") ; req.setRequestHeader("accept","application/json") ; req.onreadystatechange = function(){ var msg = req.responseText ; eval("var result=" + msg) ; document.getElementById("div1").innerHTML = result[0].name ; } req.send(null) ; } </script> </head> <body> <a href="javascript:void(0);" onclick="sendAjaxReq();">測试</a> <div id="div1"></div> </body> </html>
index.jsp<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href=http://www.mamicode.com/"">>
index2.jsp<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href=http://www.mamicode.com/"">>
upload_error.jsp<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href=http://www.mamicode.com/"">>
upload_ok.jsp<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href=http://www.mamicode.com/"">></h1> </body> </html>
upload.jsp<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href=http://www.mamicode.com/"">>
至此整个springmvc重要的东西測试完成!
SpringMVC案例3----spring3.0项目拦截器、ajax、文件上传应用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。