SpringMVC知识点小结

是基于Spring3.1的。从Spring3.0之后,SpringMVC开始广泛使用基于注解的控制器,而不是继承AbstractController 类或者实现Controller接口了。虽然Struts2现在很流行,但是,个人觉得SpringMVC十分优雅,不比Struts2差。至少我在公司中,从来没用用过SpringMVC,而且貌似在国内的公司用SpringMVC做WEB层的不多吧。不过对Spring感兴趣的话,可以自己有空研究一下。

 

这下的是自己的一点总结,是一些常用的SpringMVC知识点。

 

Java代码   收藏代码
  1. -------------------------------------------------启动SpringMVC-------------------------------------------------  
  2.   
  3. 1.要导入的JAR文件  
  4.   
  5. 必须的  
  6. org.springframework.aop-3.1.0.RELEASE.jar  
  7. org.springframework.asm-3.1.0.RELEASE.jar  
  8. org.springframework.beans-3.1.0.RELEASE.jar  
  9. org.springframework.context-3.1.0.RELEASE.jar  
  10. org.springframework.core-3.1.0.RELEASE.jar  
  11. org.springframework.expression-3.1.0.RELEASE.jar  
  12.   
  13. 数据访问  
  14. org.springframework.jdbc-3.1.0.RELEASE.jar  
  15. org.springframework.orm-3.1.0.RELEASE.jar  
  16. org.springframework.transaction-3.1.0.RELEASE.jar  
  17.   
  18. 测试  
  19. org.springframework.test-3.1.0.RELEASE.jar  
  20. com.springsource.org.junit-4.7.0.jar  
  21.   
  22. WEB  
  23. org.springframework.web-3.1.0.RELEASE.jar  
  24. org.springframework.web.servlet-3.1.0.RELEASE.jar  
  25.   
  26. JSTL标签  
  27. com.springsource.javax.servlet.jsp.jstl-1.1.2.jar  
  28. com.springsource.org.apache.taglibs.standard-1.1.2.jar  
  29.   
  30. AOP  
  31. com.springsource.org.aopalliance-1.0.0.jar  
  32. com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar  
  33.   
  34. 日志  
  35. com.springsource.org.apache.commons.logging-1.1.1.jar  
  36. com.springsource.org.apache.log4j-1.2.15.jar  
  37.   
  38. 文件上传  
  39. com.springsource.org.apache.commons.fileupload-1.2.0.jar  
  40. com.springsource.org.apache.commons.io-1.4.0.jar  
  41.   
  42. 2.启动SpringMVC  
  43. web.xml  
  44.   
  45. <context-param>  
  46.     <param-name>contextConfigLocation</param-name>  
  47.     <param-value>classpath:beans.xml</param-value>  
  48. </context-param>  
  49.   
  50. <listener>  
  51.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  52. </listener>  
  53.   
  54. <servlet>  
  55.     <servlet-name>spring</servlet-name>  
  56.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  57.     <load-on-startup>1</load-on-startup>  
  58. </servlet>  
  59. <servlet-mapping>  
  60.     <servlet-name>spring</servlet-name>  
  61.     <url-pattern>*.html</url-pattern>  
  62. </servlet-mapping>  
  63.   
  64. 3.spring-servlet.xml  
  65.   
  66. <!-- 配置要扫描的控制器 -->  
  67. <context:annotation-config/>  
  68. <context:component-scan base-package="org.springfuncs.web.controller"/>  
  69.   
  70.   
  71. <!-- 配置视图解析器 -->  
  72. <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  73.     <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>  
  74.     <property name="prefix" value="/WEB-INF/jsp/"/>  
  75.     <property name="suffix" value=".jsp"/>  
  76. </bean>  
  77.   
  78. -------------------------------------------------@Controller详解-------------------------------------------------  
  79.   
  80.   
  81. 在一个POJO的上面打上@Controller注解,就表示此类是一个MVC控制器  
  82. 例如:  
  83. @Controller  
  84. public class UserController {  
  85.   
  86. }  
  87.   
  88. -------------------------------------------------@RequestMapping详解-------------------------------------------------  
  89.   
  90. 用于处理映射路径,一本可以用于类上面或方法上面  
  91.   
  92. value  请求的URL  
  93. method 请求的方法   
  94. params 请求参数  http://localhost:8080/spring1/registerUI.html?id=123&name=tom  
  95.   
  96. headers 请求头信息  
  97. consumes  
  98. produces  
  99.   
  100.   
  101. 例如:  
  102. @Controller  
  103. @RequestMapping("/")  
  104. public class UserController {  
  105.   
  106.     @RequestMapping("/registerUI.html")  
  107.     public String registerUI() {  
  108.         return "registerUI";  
  109.     }  
  110.   
  111.     或者  
  112.   
  113.     @RequestMapping(value = "/registerUI.html", method = RequestMethod.GET, params = { "id""name" })  
  114.     public String registerUI(Integer id, String name) {  
  115.         System.out.println("请求参数:" + id);  
  116.         System.out.println("请求参数:" + name);  
  117.         return "registerUI";  
  118.     }  
  119.       
  120.     //要是有 params = { "id", "name" }则HTTP地址必须提供参数  
  121.     //若写成 http://localhost:8080/spring1/registerUI.html报错  
  122. }  
  123.   
  124. -------------------------------------------------ModelAndView详解-------------------------------------------------  
  125.   
  126. 用于返回模型与视图  
  127.   
  128. 用法一:(推荐)  
  129.   
  130. return new ModelAndView("registerSuccess""user", user); 视图名、属性名、属性值  
  131.   
  132. 用法二:(推荐)  
  133.   
  134. 用Map构造 属性名、属性值  
  135. Map<String, Object> modelMap = new HashMap<String, Object>();  
  136. modelMap.put("user", user);  
  137. modelMap.put("aaa""one");  
  138. modelMap.put("bbb""two");  
  139. return new ModelAndView("registerSuccess", modelMap); 视图名、Map对象  
  140.   
  141. 用法三:  
  142.   
  143. ModelAndView modelAndView = new ModelAndView();  
  144. modelAndView.addObject("user", user);  
  145.           
  146. Map<String, Object> modelMap = new HashMap<String, Object>();  
  147. modelMap.put("aaa""one");  
  148. modelMap.put("bbb""two");  
  149. modelAndView.addAllObjects(modelMap);  
  150. modelAndView.setViewName("registerSuccess");  
  151. return modelAndView;  
  152.   
  153. -------------------------------------------------@RequestParam详解-------------------------------------------------  
  154. 用于绑定请求参数  
  155.   
  156. 例如:  
  157.   
  158. value 请求参数的名  
  159. required 是否必须   
  160. defaultValue 默认值(支持不好,不推荐使用)  
  161.   
  162. @RequestMapping(value = "/register.html", method = RequestMethod.POST)  
  163. public ModelAndView register(  
  164.         @RequestParam(value = "username", required = true) String username,   
  165.         @RequestParam(value = "password", required = true) String password,  
  166.         @RequestParam(value = "email", required = false, defaultValue = "unknown") String email,   
  167.         @RequestParam(value = "age", required = false) Integer age) {  
  168.   
  169.     User user = new User();  
  170.     user.setUsername(username);  
  171.     user.setPassword(password);  
  172.     user.setEmail(email);  
  173.     user.setAge(age);  
  174.     userService.register(user);  
  175.   
  176.     return new ModelAndView("registerSuccess""user", user);  
  177. }  
  178.   
  179. -------------------------------------------------使用命令表单绑定请求参数 详解-------------------------------------------------  
  180. @RequestMapping(value = "/register.html", method = RequestMethod.POST)  
  181. public ModelAndView register(User user) {  //这里的User对象绑定提交的表单  
  182.     userService.register(user);  
  183.     return new ModelAndView("registerSuccess""user", user);  
  184. }  
  185.   
  186. -------------------------------------------------使用 Servlet原生API 详解-------------------------------------------------  
  187.   
  188. @RequestMapping(value = "/register.html", method = RequestMethod.POST)  
  189. public ModelAndView register(HttpServletRequest request,HttpServletResponse response,HttpSession session) {  
  190.       
  191.     //session  
  192.     session.setAttribute("sessionId""9876");  
  193.     String sessionid=(String) session.getAttribute("sessionId");  
  194.       
  195.     //response和cookie  
  196.     response.addCookie(new Cookie("c_name""c_value"));  
  197.     Cookie[]cookies=request.getCookies();  
  198.     for(Cookie c:cookies){  
  199.         if(c.getName().equals("c_name")){  
  200.             System.out.println(c.getValue());  
  201.         }  
  202.         //System.out.println(c.getName()+"-->"+c.getValue());  
  203.     }  
  204.       
  205.     //request  
  206.     String username = WebUtils.findParameterValue(request, "username");  
  207.       
  208.     或者  
  209.       
  210.     String username = null;  
  211.     Integer age = null;  
  212.     try {  
  213.         username = ServletRequestUtils.getStringParameter(request, "username");  
  214.         age = ServletRequestUtils.getIntParameter(request, "age");  
  215.     } catch (ServletRequestBindingException e) {  
  216.         e.printStackTrace();  
  217.     }  
  218.     return null;  
  219. }  
  220.   
  221. ------------------------------------------------验证 详解-------------------------------------------------  
  222. package org.springfuncs.web.validator;  
  223.   
  224. import org.springframework.stereotype.Component;  
  225. import org.springframework.validation.Errors;  
  226. import org.springframework.validation.ValidationUtils;  
  227. import org.springframework.validation.Validator;  
  228. import org.springfuncs.domain.User;  
  229.   
  230. /** 
  231.  * 表单验证组件 实现Validator接口 
  232.  */  
  233. @Component  
  234. public class UserValidtor implements Validator {  
  235.   
  236.     @Override  
  237.     public boolean supports(Class<?> clazz) {  
  238.         return User.class.isAssignableFrom(clazz);  
  239.     }  
  240.   
  241.     @Override  
  242.     public void validate(Object target, Errors errors) {  
  243.         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username""required.username");  
  244.         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password""required.password");  
  245.         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email""required.email");  
  246.         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "birthday""required.birthday");  
  247.         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age""required.age");  
  248.   
  249.         User user = (User) target;  
  250.         if (user.getEmail() != null && !"".equals(user.getEmail())) {  
  251.             // Email的正则表达式  
  252.             String regex = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";  
  253.             if (!user.getEmail().matches(regex)) {  
  254.                 errors.rejectValue("email""invalid.email");  
  255.             }  
  256.         }  
  257.     }  
  258. }  
  259.   
  260. messages_zh_CN.properties  
  261.   
  262. required.username=username 是必须的  
  263. required.password=password 是必须的  
  264. required.email=email 是必须的  
  265. required.birthday=birthday 是必须的  
  266. required.age=age 是必须的  
  267.   
  268. invalid.email=非法的Email地址  
  269.   
  270. typeMismatch.birthday=非法的 birthday 格式  
  271. typeMismatch.age=非法的 age 格式  
  272.   
  273. spring-servlet.xml 添加如下配置  
  274.   
  275. <context:component-scan base-package="org.springfuncs.web.validator"/>  
  276.   
  277. <!-- 配置资源文件 -->  
  278. <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">  
  279.     <property name="basename" value="messages"/>  
  280. </bean>  
  281.   
  282. UserController 编写如下:  
  283.   
  284. @RequestMapping(value = "/register.html", method = RequestMethod.POST)  
  285. public String register(@ModelAttribute("user") User user, BindingResult result) {  
  286.     userValidtor.validate(user, result); // 验证  
  287.     if (result.hasErrors()) {  
  288.         return "registerUI";  
  289.     } else {  
  290.         userService.register(user);  
  291.         return "registerSuccess";  
  292.     }  
  293. }  
  294.   
  295. ------------------------------------------------Spring表单详解-------------------------------------------------  
  296.   
  297. package org.springfuncs.web.controller;  
  298.   
  299. import org.springframework.stereotype.Controller;  
  300. import org.springframework.web.bind.annotation.ModelAttribute;  
  301. import org.springframework.web.bind.annotation.RequestMapping;  
  302. import org.springframework.web.servlet.ModelAndView;  
  303. import org.springfuncs.domain.Form;  
  304.   
  305. @Controller  
  306. @RequestMapping("/")  
  307. public class FormController {  
  308.   
  309.     @RequestMapping("/formUI.html")  
  310.     public String formUI(@ModelAttribute("form") Form form) {  
  311.   
  312.         /** 设置默认值 */  
  313.         form.setId(9999);  
  314.         form.setName("your name");  
  315.         // form.setPassword("your password"); //TODO 密码框怎么设置默认值呢?  
  316.         form.setSex("1");  
  317.         form.setLove(new String[] { "1""2""3" });  
  318.         form.setCity("2");  
  319.         form.setInfo("write something...");  
  320.         return "formUI";  
  321.     }  
  322.   
  323.     /** 这是一个很笨的方法,仅仅为了演示而已 */  
  324.     @RequestMapping("/doForm.html")  
  325.     public ModelAndView doForm(@ModelAttribute("form") Form form) {  
  326.   
  327.         // 处理 sex  
  328.         if (form.getSex().equals("1")) {  
  329.             form.setSex("男");  
  330.         } else {  
  331.             form.setSex("女");  
  332.         }  
  333.   
  334.         // 处理 city  
  335.         if (form.getCity().equals("1")) {  
  336.             form.setCity("北京");  
  337.         } else if (form.getCity().equals("2")) {  
  338.             form.setCity("上海");  
  339.         } else if (form.getCity().equals("3")) {  
  340.             form.setCity("广州");  
  341.         }  
  342.   
  343.         // 处理 love  
  344.         String[] love = form.getLove();  
  345.         StringBuffer bufLove = new StringBuffer();  
  346.         for (int i = 0; love != null && i < love.length; i++) {  
  347.             if (love[i].equals("1")) {  
  348.                 bufLove.append("struts").append(",");  
  349.             } else if (love[i].equals("2")) {  
  350.                 bufLove.append("hibernate").append(",");  
  351.             } else if (love[i].equals("3")) {  
  352.                 bufLove.append("spring").append(",");  
  353.             }  
  354.         }  
  355.         bufLove.deleteCharAt(bufLove.length() - 1);  
  356.         form.setLove(new String[] { bufLove.toString() });  
  357.   
  358.         return new ModelAndView("formSuccess""form", form);  
  359.     }  
  360. }  
  361.   
  362.   
  363. formUI.jsp  
  364.   
  365. <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>  
  366.   
  367. <form:form action="${pageContext.request.contextPath }/doForm.html" method="post" modelAttribute="form">  
  368.     <form:errors path="*" cssClass="error"/>  
  369.     <form:hidden path="id"/>  
  370.     <table>  
  371.         <tr>  
  372.             <td>姓名:</td>  
  373.             <td><form:input path="name"/></td>  
  374.         </tr>  
  375.         <tr>  
  376.             <td>密码:</td>  
  377.             <td><form:password path="password"/></td>  
  378.         </tr>  
  379.         <tr>  
  380.             <td>性别:</td>  
  381.             <td>  
  382.                 <form:radiobutton path="sex" value="1"/>男  
  383.                 <form:radiobutton path="sex" value="2"/>女  
  384.             </td>  
  385.         </tr>  
  386.         <tr>  
  387.             <td>爱好:</td>  
  388.             <td>  
  389.                 <form:checkbox path="love" value="1"/>struts  
  390.                 <form:checkbox path="love" value="2"/>hibernate  
  391.                 <form:checkbox path="love" value="3"/>spring  
  392.             </td>  
  393.         </tr>  
  394.         <tr>  
  395.             <td>城市:</td>  
  396.             <td>  
  397.                 <form:select path="city">  
  398.                     <form:option value="">--请选择--</form:option>  
  399.                     <form:option value="1">北京</form:option>  
  400.                     <form:option value="2">上海</form:option>  
  401.                     <form:option value="3">广州</form:option>  
  402.                 </form:select>  
  403.             </td>  
  404.         </tr>  
  405.         <tr>  
  406.             <td>简介:</td>  
  407.             <td><form:textarea path="info" rows="3" cols="20"/></td>  
  408.         </tr>  
  409.         <tr>  
  410.             <td colspan="2"><input type="submit" value="注册"/></td>  
  411.         </tr>  
  412.     </table>  
  413. </form:form>  
  414.   
  415. formSuccess.jsp  
  416.   
  417. 姓名:${form.name }<br />  
  418. 密码:${form.password }<br />  
  419. 性别:${form.sex }<br />  
  420. 爱好:<c:forEach items="${form.love }" var="love">${love }</c:forEach><br />  
  421. 城市:${form.city }<br />  
  422. 简介:${form.info }<br />  
  423.   
  424. ------------------------------------------------Spring表单详解 2(推荐)-------------------------------------------------  
  425.   
  426. ***************************************  
  427. 通常select的值都是从数据库中读取出后,          
  428. 封装成一个对象,                             
  429. 然后存入集合中,比如List  
  430. ***************************************  
  431.   
  432. package org.springfuncs.web.controller;  
  433.   
  434. import java.util.ArrayList;  
  435. import java.util.List;  
  436.   
  437. import org.springframework.stereotype.Controller;  
  438. import org.springframework.web.bind.annotation.ModelAttribute;  
  439. import org.springframework.web.bind.annotation.RequestMapping;  
  440. import org.springframework.web.servlet.ModelAndView;  
  441. import org.springfuncs.domain.City;  
  442. import org.springfuncs.domain.Form;  
  443.   
  444. @Controller  
  445. @RequestMapping("/")  
  446. public class FormController {  
  447.   
  448.     // 重点  
  449.     @ModelAttribute("cityList")  
  450.     public List<City> populateCity() {  
  451.         List<City> cityList = new ArrayList<City>();  
  452.         cityList.add(new City(1"北京"));  
  453.         cityList.add(new City(2"上海"));  
  454.         cityList.add(new City(3"广州"));  
  455.         return cityList;  
  456.     }  
  457.   
  458.     @RequestMapping("/formUI.html")  
  459.     public String formUI(@ModelAttribute("form") Form form) {  
  460.   
  461.         /** 设置默认值 */  
  462.         form.setId(9999);  
  463.         form.setName("your name");  
  464.         // form.setPassword("your password"); //TODO 密码框怎么设置默认值呢?  
  465.         form.setSex("1");  
  466.         form.setLove(new String[] { "1""2""3" });  
  467.         // form.setCity(new City(2, "上海")); //不好用啊  
  468.         form.setInfo("write something...");  
  469.         return "formUI";  
  470.     }  
  471.   
  472.     /** 这是一个很笨的方法,仅仅为了演示而已 */  
  473.     @RequestMapping("/doForm.html")  
  474.     public ModelAndView doForm(@ModelAttribute("form") Form form) {  
  475.   
  476.         // 处理 sex  
  477.         if (form.getSex().equals("1")) {  
  478.             form.setSex("男");  
  479.         } else {  
  480.             form.setSex("女");  
  481.         }  
  482.   
  483.         // 处理 love  
  484.         String[] love = form.getLove();  
  485.         StringBuffer bufLove = new StringBuffer();  
  486.         for (int i = 0; love != null && i < love.length; i++) {  
  487.             if (love[i].equals("1")) {  
  488.                 bufLove.append("struts").append(",");  
  489.             } else if (love[i].equals("2")) {  
  490.                 bufLove.append("hibernate").append(",");  
  491.             } else if (love[i].equals("3")) {  
  492.                 bufLove.append("spring").append(",");  
  493.             }  
  494.         }  
  495.         bufLove.deleteCharAt(bufLove.length() - 1);  
  496.         form.setLove(new String[] { bufLove.toString() });  
  497.   
  498.         return new ModelAndView("formSuccess""form", form);  
  499.     }  
  500. }  
  501.   
  502.   
  503. 创建自定义类型  
  504. package org.springfuncs.web.propertyeditor;  
  505.   
  506. import java.beans.PropertyEditorSupport;  
  507.   
  508. import org.springfuncs.domain.City;  
  509. import org.springfuncs.service.CityService;  
  510.   
  511. /** 
  512.  * 实现自定义属性类型 继承PropertyEditorSupport类 
  513.  */  
  514. public class CityEditor extends PropertyEditorSupport {  
  515.   
  516.     private CityService cityService;  
  517.   
  518.     public CityEditor(CityService cityService) {  
  519.         this.cityService = cityService;  
  520.     }  
  521.   
  522.     @Override  
  523.     public void setAsText(String text) throws IllegalArgumentException {  
  524.         if (text != null && !"".equals(text)) {  
  525.             Integer id = Integer.parseInt(text);  
  526.             City city = cityService.findById(id);  
  527.             setValue(city);  
  528.         }  
  529.     }  
  530. }  
  531.   
  532. 装配自定义类型  
  533. package org.springfuncs.web.util;  
  534.   
  535. import org.springframework.beans.factory.annotation.Autowired;  
  536. import org.springframework.web.bind.WebDataBinder;  
  537. import org.springframework.web.bind.support.WebBindingInitializer;  
  538. import org.springframework.web.context.request.WebRequest;  
  539. import org.springfuncs.domain.City;  
  540. import org.springfuncs.service.CityService;  
  541. import org.springfuncs.web.propertyeditor.CityEditor;  
  542.   
  543. /** 
  544.  * 绑定自定义类型 实现WebBindingInitializer接口 
  545.  */  
  546. public class FormBindingInitializer implements WebBindingInitializer {  
  547.   
  548.     @Autowired  
  549.     private CityService cityService;  
  550.   
  551.     @Override  
  552.     public void initBinder(WebDataBinder binder, WebRequest request) {  
  553.         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
  554.         dateFormat.setLenient(false);  
  555.         binder.registerCustomEditor(Date.classnew CustomDateEditor(dateFormat, true));  
  556.         binder.registerCustomEditor(City.classnew CityEditor(cityService));  
  557.   
  558.     }  
  559. }  
  560.   
  561. 在spring-servlet.xml 中配置  
  562. <!-- 自定义属性类型 -->  
  563. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
  564.     <property name="webBindingInitializer">  
  565.         <bean class="org.springfuncs.web.util.FormBindingInitializer"/>  
  566.     </property>  
  567. </bean>  
  568.   
  569.   
  570. package org.springfuncs.service.impl;  
  571.   
  572. import org.springframework.stereotype.Service;  
  573. import org.springfuncs.domain.City;  
  574. import org.springfuncs.service.CityService;  
  575.   
  576. @Service  
  577. public class CityServiceImpl implements CityService {  
  578.   
  579.     public static final City BEIJING = new City(1"北京");  
  580.     public static final City SHANGHAI = new City(2"上海");  
  581.     public static final City GUANGZHOU = new City(3"广州");  
  582.   
  583.     @Override  
  584.     public City findById(Integer id) {  
  585.         switch (id) {  
  586.         case 1:  
  587.             return BEIJING;  
  588.         case 2:  
  589.             return SHANGHAI;  
  590.         case 3:  
  591.             return GUANGZHOU;  
  592.         default:  
  593.             return null;  
  594.         }  
  595.     }  
  596. }  
  597.   
  598. <form:select path="city">  
  599.     <form:option value="">--请选择--</form:option>  
  600.     <form:options items="${cityList }" itemLabel="name" itemValue="id"/>  
  601. </form:select>  
  602.   
  603. 另一种  
  604. <form:select path="city">  
  605.     <form:option value="">--请选择--</form:option>  
  606.     <form:options items="${cityMap }" itemLabel="value" itemValue="key"/>  
  607. </form:select>   
  608.   
  609. ------------------------------------------------文件上传-------------------------------------------------  
  610.   
  611. spring-servlet.xml  
  612.   
  613. <!-- 配置文件上传 -->  
  614. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  615.     <property name="defaultEncoding" value="UTF-8"/>   
  616.     <property name="maxUploadSize" value="5242880"/> <!-- 5M -->  
  617.     <property name="uploadTempDir" value="upload"/> <!-- 要在WebContent下建立一个upload文件夹 -->  
  618. </bean>  
  619.   
  620. uploadUI.jsp  
  621.   
  622. <form action="<c:url value="/upload.html"/>" method="post" enctype="multipart/form-data">  
  623.     文件名称:<input type="text" name="name"/><br />  
  624.     上传文件:<input type="file" name="file"/><br />  
  625.     <input type="submit" value="上传"/>  
  626. </form>  
  627.   
  628. UploadController.java  
  629.   
  630. package org.springfuncs.web.controller;  
  631.   
  632. import java.io.File;  
  633.   
  634. import javax.servlet.http.HttpServletRequest;  
  635. import javax.servlet.http.HttpSession;  
  636.   
  637. import org.springframework.stereotype.Controller;  
  638. import org.springframework.web.bind.annotation.RequestMapping;  
  639. import org.springframework.web.bind.annotation.RequestMethod;  
  640. import org.springframework.web.bind.annotation.RequestParam;  
  641. import org.springframework.web.multipart.MultipartFile;  
  642.   
  643. @Controller  
  644. @RequestMapping("/")  
  645. public class UploadController {  
  646.   
  647.     @RequestMapping("/uploadUI.html")  
  648.     public String uploadUI() {  
  649.         return "uploadUI";  
  650.     }  
  651.   
  652.     @RequestMapping(value = "/upload.html", method = RequestMethod.POST)  
  653.     public String upload(HttpServletRequest request, @RequestParam("name") String name, @RequestParam("file") MultipartFile file) throws Exception {  
  654.         if (!file.isEmpty()) {  
  655.   
  656.             // System.out.println("文件的MIME类型:" + file.getContentType());  
  657.             // System.out.println("表单的类型为file的name属性名:" + file.getName());  
  658.             // System.out.println("原始文件名:" + file.getOriginalFilename());  
  659.             // System.out.println("文件大小" + file.getSize());  
  660.   
  661.             String path = request.getSession().getServletContext().getRealPath(File.separator) + "upload" + File.separator + file.getOriginalFilename();  
  662.             file.transferTo(new File(path));  
  663.   
  664.             // System.out.println(path); //打印上传路径  
  665.   
  666.             // HttpSession session=request.getSession();  
  667.             // session.setAttribute("name", name);  
  668.             // session.setAttribute("path", path);  
  669.   
  670.             return "redirect:uploadSuccess.html";  
  671.         } else {  
  672.             return "redirect:uploadFailure.html";  
  673.         }  
  674.     }  
  675.   
  676.     @RequestMapping("/uploadSuccess.html")  
  677.     public String uploadSuccess() {  
  678.         return "uploadSuccess";  
  679.     }  
  680.   
  681.     @RequestMapping("/uploadFailure.html")  
  682.     public String uploadFailure() {  
  683.         return "uploadFailure";  
  684.     }  
  685. }  
  686.   
  687. uploadSuccess.jsp  
  688.   
  689. 上传成功!  
  690. <br />  
  691. 文件名称:<br />  
  692. ${name }  
  693. <br />  
  694. 图片样张:<br />  
  695. <img alt="${name }" src="${path }"/>  
  696.   
  697. uploadFailure.jsp  
  698.   
  699. 上传失败!  
  700.   
  701. ------------------------------------------------异常处理-------------------------------------------------  
  702. spring-servlet.xml  
  703.   
  704. <!-- 映射异常 -->  
  705. <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
  706.     <property name="defaultErrorView" value="error" />  
  707.     <property name="exceptionMappings">  
  708.         <props>  
  709.             <prop key="java.sql.SQLException">errorDB</prop>  
  710.             <prop key="java.lang.RuntimeException">errorRT</prop>  
  711.         </props>  
  712.     </property>  
  713.     <property name="defaultStatusCode" value="500"/>  
  714.     <property name="warnLogCategory" value="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"/>  
  715. </bean>  
  716.   
  717. error.jsp  
  718. 发生了未知的错误,请联系管理员。  
  719.   
  720. errorRT.jsp  
  721. <%Exception e=(Exception)request.getAttribute("exception");%>  
  722. <h1>Exception:</h1>  
  723. <%e.printStackTrace(new PrintWriter(out));%>  
  724. <hr/>  
  725. <%-- ${exception} --%>  
  726.   
  727. -------------------------------------------------单元测试-------------------------------------------------  
  728.   
  729. package junit.test;  
  730.   
  731. import java.util.Date;  
  732.   
  733. import org.junit.Test;  
  734. import org.junit.runner.RunWith;  
  735. import org.springframework.beans.factory.annotation.Autowired;  
  736. import org.springframework.test.context.ContextConfiguration;  
  737. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  738. import org.springframework.test.context.transaction.TransactionConfiguration;  
  739. import org.springframework.transaction.annotation.Transactional;  
  740. import org.springfuncs.domain.User;  
  741. import org.springfuncs.service.UserService;  
  742.   
  743. @RunWith(SpringJUnit4ClassRunner.class)  
  744. @ContextConfiguration(locations = { "classpath:beans.xml" })  
  745. @Transactional  
  746. @TransactionConfiguration(transactionManager = "txManager", defaultRollback = true)  
  747. public class SpringTest {  
  748.   
  749.     @Autowired  
  750.     private UserService userService;  
  751.   
  752.     @Test  
  753.     public void testRegister() {  
  754.         User user = new User();  
  755.         user.setUsername("monday");  
  756.         user.setPassword("1234");  
  757.         user.setEmail("monday@qq.com");  
  758.         user.setBirthday(new Date());  
  759.         user.setAge(23);  
  760.         userService.register(user);  
  761.     }  
  762. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值