1
所需jar包
项目结构如下:
2
web.xml配置文件的内容如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app 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 <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <!-- struts用/*,springmvc不能用/*方式,配置的url-pattern如:*.xxx <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app> |
3
springmvc-servlet.xml的内容如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans <context:component-scan <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property <property </bean> <!-- <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- <property </bean> <mvc:interceptors> <mvc:interceptor> <!-- path:指定要拦截的范围。语法:/(根目录)test/**, <mvc:mapping <bean </mvc:interceptor> </mvc:interceptors> </beans> |
4
Test1Controller.java的内容如下:
package com.rl.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/test1") //当前Controller的namespace,防止不同的Controller中方名重复的问题 public class Test1Controller { /** * 浏览器中的访问地址是:http://localhost:8080/springmvc2/test1/toAjax.do * @return */ @RequestMapping("/toAjax.do") public String toAjax() { return "ajax"; } } |
5
TestController的内容如下:
package com.rl.controller; import java.io.IOException; import java.io.PrintWriter; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.rl.model.Person; import com.rl.model.User; @Controller @RequestMapping("test") // public class TestController { public TestController() { System.out.println("Controller被创建...."); } /** * desc:返回值类型是String,含义是ModelAndView中的viewname * * @RequestMapping:请求方法的映射,内容最好和方法名称一致 * @author 涂作权 * @return */ @RequestMapping("/hello.do") public String hello() { return "index"; } /** * desc:HttpServletRequest可以直接定义在方法的参数列表中来使用 * * @param request * @author 涂作权 * @return */ @RequestMapping("/getParam.do") public String getParam(HttpServletRequest request) { String name = request.getParameter("name"); System.out.println(name); return "index"; } /** * desc:在参数的列表中来直接定义要接收的参数,参数名(形象)一定要 * 和请求中传递的参数名(实参)一致,数据类型会自动的转换,如果数据 * 类型转换出错会报400错误??? * * @param name * @param id * @param age * @param address * @param birthday * @author 涂作权 * @return */ @RequestMapping("/getParam1.do") public String getParam1(String name, Integer id, Integer age, String address, Date birthday) { System.out.println("姓名:" + name + " + age + " 地址: " + address + " return "index"; } /** * desc:多选的接收在参数列表中定义数组来接收,参数名(形参) * 如果以字符串来接收的话会接收到一个以逗号分隔的一个字符串 * * @author 涂作权 * @param favor * @return */ @RequestMapping("/getParam2.do") public String getParam2(String[] favor) { System.out.println(favor); for (String fa : favor) { System.out.println(fa); } return "index"; } /** * desc:接收实体对象,直接在参数列表中定义要接收的实体类就可以了, * 的属性值是通过请求传递过来并且注入到对象中 * * @author 涂作权 * @param person * @param user * @param name * @return */ @RequestMapping("/getParamByObj.do") public String getParamByObj(Person person, User user, String name) { System.out.println(person); System.out.println(user); return "index"; } /** * 不建议使用 desc:返回值类型定义成ModelAndView,把数据和视图注入到ModelAndView中返回即可 * * @return * @author 涂作权 * @throws Exception */ @RequestMapping("/returnData.do") public ModelAndView returnData() throws Exception { Person p = new Person(); p.setId(1); p.setName("zhangsan"); p.setAge(22); p.setAddress("beijing"); p.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("2013-08-05")); Map<String, Object> map = new HashMap<String, Object>(); // 相当于request.setAttribute("person", p); map.put("person", p); return new ModelAndView("index", map); } /** * 不建议使用 desc:返回值是String类型:viewName,参数是map,是ModelAndView中 * * @author 涂作权 * @param map * @return * @throws Exception */ @RequestMapping("/returnData1.do") public String returnData1(Map<String, Object> map) throws Exception { Person p = new Person(); p.setId(1); p.setName("zhangsan"); p.setAge(22); p.setAddress("beijing"); p.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("2013-08-05")); // 相当于request.setAttribute("person", p); map.put("person", p); return "index"; } /** * 在参数列表中定义Model来给页面返回数据 * * @author 涂作权 * @param model * @return * @throws Exception */ @RequestMapping("/returnData2.do") public String returnData2(Model model) throws Exception { Person p = new Person(); p.setId(1); p.setName("zhangsan"); p.setAge(22); p.setAddress("beijing"); p.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("2013-08-05")); // 相当于request.setAttribute("person", p); model.addAttribute("person", p); return "index"; } /** * desc:method=RequestMethod.POST */ @RequestMapping(value = "/getParamByObjWithMethod.do", method = RequestMethod.POST) public String getParamByObjWithMethod(Person person) { System.out.println(person); return "success"; } /** * desc:在参数列表中直接来定义HttpServletResponse, * * @author 涂作权 * @param name * @param response */ @RequestMapping("/ajax.do") public void ajax(String name, HttpServletResponse response) { String result = "hello" + name; try { response.getWriter().write(result); } catch (IOException e) { e.printStackTrace(); } } /** * desc:直接在参数列表中来定义PrintWriter * * @param name * @param out */ @RequestMapping("/ajax1.do") public void ajax1(String name, PrintWriter out){ String result = "hello " + name; out.write(result); } @RequestMapping("/toAjax.do") public String toAjax(){ return "ajax"; } /** * 在同一个Controller中重定向语法 * * * @return */ @RequestMapping("/redirectToAjax.do") public String redirectToAjax(){ return "redirect:toAjax.do"; } /** * controller之间的重定向redirect:后面要有"/",代表从项目的根目录开始 * * @return * @author 涂作权 */ @RequestMapping("/redirectToAjax1.do") public String redirectToAjax1(){ return "redirect:/test1/toAjax.do"; } /** * 单纯的转发 * * @author 涂作权 * @return */ @RequestMapping("/toForm.do") public String toForm(){ return "form"; } /** * 用于转换数据类型 * @param binder */ @InitBinder public void initBinder(ServletRequestDataBinder binder){ binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true)); } } |
6 UploadController的内容如下:
package com.rl.controller; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.rl.model.Person; @Controller @RequestMapping("/upload") // public class UploadController { @RequestMapping("/uploadPic.do") public String uploadPic(Person person, HttpServletRequest request) throws Exception { // 把request转换成MultipartHttpServletRequest MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request; // 获得文件,这里的pic是表单中的file字段对应的属性名称 MultipartFile mf = mr.getFile("pic"); // 获得文件的字节数组 byte[] fbyte = mf.getBytes(); // 获得当前时间的最小精度 String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS") .format(new Date()); // 追加三位随机数 Random random = new Random(); for (int i = 0; i < 3; i++) { fileName = fileName + random.nextInt(10); } // 获得原始文件名 String oriFileName = mf.getOriginalFilename(); // 获得后缀名 String suffix = oriFileName.substring(oriFileName.lastIndexOf(".")); // 拿到服务器的根目录 String realPath = request.getSession().getServletContext() .getRealPath("/"); // 创建文件输出流 OutputStream out = new FileOutputStream(new File(realPath + "/upload/" + fileName + suffix)); out.write(fbyte); out.flush(); out.close(); return "success"; } @InitBinder public void initBinder(ServletRequestDataBinder binder) { binder.registerCustomEditor(Date.class, new CustomDateEditor( new SimpleDateFormat("yyyy-MM-dd"), true)); } } |
7
MyInterceptor的内容如下:
package com.rl.interceptor; import java.util.Map; 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{ /** * 执行时机:在视图解析器解析完毕之后,页面一旦报错异常会抛到该方法中, * try{}catch后面的finally,用于系统监控 */ public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception ex) throws Exception { System.out.println("afterCompletion..................."); System.out.println("----------------------------------"); ex.printStackTrace(); System.out.println("----------------------------------"); } /** * 执行时机:Controller执行完毕,视图解析器解析之前来执行 * 注意:此案例中如果是测试异步,这里的mv是null,此处会报错。 * 解决办法是注释掉springmvc-servlet.xml中的拦截器的配置内容 */ public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView mv) throws Exception { Map<String, Object> map = mv.getModel(); map.put("test", "append something..."); System.out.println("postHandle..."); } /** * 返回值数据类型是布尔类型:true放行, * 执行时机:Controller执行之前 * * 最常用的应用场景就是权限的拦截 */ public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object obj) throws Exception { System.out.println("preHandle..."); System.out.println(obj.getClass().getName()); return true; } } |
8
Person的内容如下:
package com.rl.model; import java.util.Date; public Integer id; String name; Integer age; String address; Date birthday; /** * @return the */ public Integer getId() { return } /** * @param id */ public this.id } /** * @return the */ public String getName() { return } /** * @param name */ public this.name } /** * @return the */ public Integer getAge() { return } /** * @param age */ public this.age } /** * @return the */ public String getAddress() { return } /** * @param address */ public this.address } /** * @return the */ public Date getBirthday() { return } /** * @param birthday */ public this.birthday } } |
9 User的内容如下
package com.rl.model; public Integer id; String name; /** * @return the */ public Integer getId() { return } /** * @param id */ public this.id } /** * @return the */ public String getName() { return } /** * @param name */ public this.name } @Override public String toString() { return } } |
10 ajax.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> <head> <base <title>My <meta <meta <meta <meta <meta <script <script $(function(){ $("#mybutton").click(function(){ console.log("test"); var $.ajax({ url:"test/ajax1.do", type:"post", dataType:"text", data:{ name:mytext }, success:function(responseText){ alert(responseText); }, error:function(){ alert("system error"); } }); }); }); </script> </head> <body> <input <input </body> </html> |
11 form.jsp的内容如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE <html> <head> <title>My </head> <body> <form id:<input name:<input age:<input address:<input birthday:<input pic:<input <input </form> </body> </html> |
12 index.jsp的内容如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ <!DOCTYPE <html> <head> <title>My </head> <body> <h1>${person.id}</h1> <h1>${person.name}</h1> <h1>${person.age}</h1> <h1>${person.address}</h1> <h1><fmt:formatDate <h1>${test </body> </html> |
13 success.jsp的内容如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE <html> <head> <title>My </head> <body> success<br> </body> </html> |