1 所需jar包
项目结构如下:
2 web.xml配置文件的内容如下:
<?xmlversion="1.0"encoding="UTF-8"?> <web-appversion="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> </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的内容如下:
<?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/context http://www.springframework.org/schema/context/spring-context-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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "> <context:component-scanbase-package="com.rl.controller"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <propertyname="prefix"value="/WEB-INF/jsp/"/> <propertyname="suffix"value=".jsp"/> </bean> <!--文件上传的视图解析器 <beanid="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--文件上传的最大值,以字节为单位 <propertyname="maxUploadSize"value="1024000"></property> </bean> <mvc:interceptors> <mvc:interceptor> <!-- path:指定要拦截的范围。语法:/(根目录)test/**,所有拦截/** <mvc:mappingpath="/**"/> <beanclass="com.rl.interceptor.MyInterceptor"/> </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 { /** * * @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") //当前Controller的namespace,防止不同Controller中方法名重复的问题 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:在参数的列表中来直接定义要接收的参数,参数名(形象)一定要 * * * * @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("姓名:" + age + " 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:接收实体对象,直接在参数列表中定义要接收的实体类就可以了,每次访问的时候springmvc会自动创建相关参数的实体对象,对象中 * * * @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"; } /** * * * @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>(); // map.put("person", p); return new ModelAndView("index", map); } /** * * * @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")); // map.put("person", p); return "index"; } /** * * * @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")); // model.addAttribute("person", p); return "index"; } /** * desc:method=RequestMethod.POST该方法只能使用method指定的请求方式来指定 */ @RequestMapping(value = "/getParamByObjWithMethod.do", method = RequestMethod.POST) public String getParamByObjWithMethod(Person person) { System.out.println(person); return "success"; } /** * desc:在参数列表中直接来定义HttpServletResponse,并且方法的返回值要定义void为ajax提供调用 * * @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"; } /** * * * * @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") //当前Controller的namespace,防止不同Controller中方法名重复的问题 public class UploadController { @RequestMapping("/uploadPic.do") public String uploadPic(Person person, HttpServletRequest request) throws Exception { // MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request; // 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("----------------------------------"); } /** * * * */ 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..."); } /** * * * * */ 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; publicclass Integer String Integer String Date /** * */ public returnid; } /** * */ publicvoid this.id } /** * */ public returnname; } /** * */ publicvoid this.name } /** * */ public returnage; } /** * */ publicvoid this.age } /** * */ public returnaddress; } /** * */ publicvoid this.address } /** * */ public returnbirthday; } /** * */ publicvoid this.birthday } } |
9 User的内容如下
package com.rl.model; publicclass Integer String /** * */ public returnid; } /** * */ publicvoid this.id } /** * */ public returnname; } /** * */ publicvoid this.name } @Override public return"User } } |
10 ajax.jsp的内容如下:
<%@page <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPEHTML <html> <head> <basehref="<%=basePath%>"> <title>My <metahttp-equiv="pragma"content="no-cache"> <metahttp-equiv="cache-control"content="no-cache"> <metahttp-equiv="expires"content="0"> <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"> <metahttp-equiv="description"content="This <scripttype="text/javascript"src="js/jquery.js"></script> <scripttype="text/javascript"> $(function(){ $("#mybutton").click(function(){ console.log("test"); varmytext $.ajax({ url:"test/ajax1.do", type:"post", dataType:"text", data:{ name:mytext }, success:function(responseText){ alert(responseText); }, error:function(){ alert("system } }); }); }); </script> </head> <body> <inputtype="text"id="mytext"/> <inputid="mybutton"type="button"value="click"/> </body> </html> |
11 form.jsp的内容如下:
<%@page <!DOCTYPEHTML <html> <head> <title>My </head> <body> <formaction="upload/uploadPic.do"method="post"enctype="multipart/form-data"> id:<inputname="id"type="text"/><br> name:<inputname="name"type="text"/><br> age:<inputname="age"type="text"/><br> address:<inputname="address"type="text"/><br> birthday:<inputname="birthday"type="text"/><br> pic:<inputtype="file"name="pic"/><br> <inputvalue="submit"type="submit"/> </form> </body> </html> |
12 index.jsp的内容如下:
<%@page <%@taglib <!DOCTYPEHTML <html> <head> <title>My </head> <body> <h1>${person.id}</h1> <h1>${person.name}</h1> <h1>${person.age}</h1> <h1>${person.address}</h1> <h1><fmt:formatDatevalue="${person.birthday <h1>${test </body> </html> |
13 success.jsp的内容如下:
<%@page <!DOCTYPEHTML <html> <head> <title>My </head> <body> success<br> </body> </html> |