Spring3.1 MVC注解配置学习

来源:互联网 发布:淘宝收藏夹在哪里 编辑:程序博客网 时间:2024/05/17 08:20

DEMO结构:




1.导入Spring3.1 MVC所依赖的jar(具体根据项目来)

2.在web.xml中配置DispatcherServlet

<!-- 中文过滤器 --><filter><filter-name>CharacterFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>CharacterFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><servlet><servlet-name>demo</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>demo</servlet-name><url-pattern>/</url-pattern></servlet-mapping>

3.新建demo-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:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"><context:component-scan base-package="com.controller"/> <!--扫描到@Controller注解的Bean  --><mvc:annotation-driven/><!-- 静态文件处理 /resources/**映射到 ResourceHttpRequestHandler进行处理,location指定静态资源的位置 --><mvc:resources mapping="/resources/**" location="/resources/" />  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/><property name="prefix" value="/WEB-INF/jsp/"/><property name="suffix" value=".jsp"/></bean><!-- 文件上传处理 --><bean id="multipartResolver"       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">        <property name="maxUploadSize">        <value>1024</value>    </property>    <property name="maxInMemorySize">        <value>4096</value>    </property>   </bean><!-- 全局异常处理 --><bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"><property name="exceptionMappings"><props><prop key="com.exception.UserException">error</prop><prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error</prop></props></property></bean></beans>


4.创建UserContorller类

package com.controller;import java.io.File;import java.io.IOException;import java.util.HashMap;import java.util.Map;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import org.apache.commons.io.FileUtils;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.validation.BindingResult;import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.PathVariable;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.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import com.bean.User;import com.exception.UserException;@Controller@RequestMapping("/user") //要访问这个controller都要在前面加上/userpublic class UserController {private static Map<String,User> map = new HashMap<String,User>();public UserController() {map.put("u1", new User("u1","p1","u1@qq.com"));map.put("u2", new User("u2","p1","u1@qq.com"));map.put("u3", new User("u3","p1","u1@qq.com"));map.put("u4", new User("u4","p1","u1@qq.com"));map.put("u5", new User("u5","p1","u1@qq.com"));}@RequestMapping(value="/users",method=RequestMethod.GET)public String list(Model model){ //Model 用于传递值model.addAttribute("users", map);return "user/users";}@RequestMapping(value="/add",method=RequestMethod.GET)public String add(@ModelAttribute("user")User user){return "user/useradd";}@RequestMapping(value="/add",method=RequestMethod.POST)public String add(@Validated User user,BindingResult result,@RequestParam("files")MultipartFile[] files,HttpServletRequest req) throws IOException{//BindingResult必须紧跟@Validatedif(result.hasErrors()){System.out.println("error");return "user/useradd";}for (MultipartFile multipartFile : files) {if(multipartFile.isEmpty()){continue;}System.out.println(multipartFile.getName()+","+multipartFile.getOriginalFilename()+","+multipartFile.getContentType()+","+multipartFile.getSize());String path = req.getSession().getServletContext().getRealPath("/resources");//获取resources在工程下的路径File f = new File(path+"\\"+multipartFile.getOriginalFilename());System.out.println(path+"\\"+multipartFile.getOriginalFilename());FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), f);}map.put(user.getUsername(), user);System.out.println("no error");return "redirect:/user/users"; //客户端跳转}@RequestMapping(value="/{username}/show",method=RequestMethod.GET)//将URL中的占位符绑定到操作方法的入参中public String show(@PathVariable String username,Model model){model.addAttribute(map.get(username));return "user/show";}@RequestMapping(value="/{username}/update",method=RequestMethod.GET)public String update(@PathVariable String username,Model model){model.addAttribute(map.get(username));return "user/update";}@RequestMapping(value="/{name}/update",method=RequestMethod.POST)public String update(@PathVariable String name,@Validated User user,BindingResult br){if(br.hasErrors()){return "user/update";}map.put(name, user);return "redirect:/user/users";}@RequestMapping(value="/{name}/delete",method=RequestMethod.GET)public String delete(@PathVariable String name){map.remove(name);return "redirect:/user/users";}@RequestMapping(value="/login")public String login(String username,String password,HttpServletRequest req,Model model){if(!map.containsKey(username)){throw new UserException("用户名不正确!");}User user = map.get(username);if(!user.getPassword().equals(password)){throw new UserException("密码不正确!");}HttpSession  session = req.getSession();session.setAttribute("u", user);model.addAttribute("users", map);return "user/users";}//返回JSON数据@RequestMapping(value="/{username}/show",method=RequestMethod.GET,params="json")@ResponseBody //在SpringMVC中可以在Controller的某个方法上加@ResponseBody注解,表示该方法的返回结果直接写入HTTP response body中。 public User show(@PathVariable String username) {return map.get(username);}}


5.返回Map集合<users.jsp>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!-- 引入jstl标签用于遍历-->  <body>  <h1>当前用户-->${u.username }</h1><c:forEach var="um" items="${users}"><a href="${um.value.username}/show">${um.value.username}</a>----${um.value.password }----${um.value.email }----<a href="${um.value.username}/update">修改</a><a href="${um.value.username}/delete">删除</a><br/></c:forEach><a href="add">添加</a>  </body>
6.返回JSON数据
注:需导入jackson-all-1.9.4.jar
http://localhost:8080/SpringMVC_03/user/u2/show?json

结果将会解析到body

7.表单提交、文件上传、服务器表单验证

<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %><!-- 引入spring标签--><body>  <sf:form method="post" modelAttribute="user" enctype="multipart/form-data">  <ul style="list-style: none;">  <li>用户名:<sf:input path="username"/><sf:errors path="username"/></li>  <li>密码:<sf:password path="password"/><sf:errors path="password"/></li>  <li>Email:<sf:input path="email"/><sf:errors path="email"/></li>  <li>文件:<input type="file" name="files"/></li>  <li>文件:<input type="file" name="files"/></li>  <li>文件:<input type="file" name="files"/></li>  <li><input type="submit" value="添加"/></li>  </ul>  </sf:form>  </body>

8.error处理

新建UserException

package com.exception;public class UserException extends RuntimeException {private static final long serialVersionUID = 1L;public UserException() {super();// TODO Auto-generated constructor stub}public UserException(String arg0, Throwable arg1) {super(arg0, arg1);// TODO Auto-generated constructor stub}public UserException(String arg0) {super(arg0);// TODO Auto-generated constructor stub}public UserException(Throwable arg0) {super(arg0);// TODO Auto-generated constructor stub}}

异常页面

  <body>    <h1>${exception.message}</h1>  </body>
附:Demo下载