1.web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <servlet> <servlet-name>srpingMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>srpingMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
2.配置与srpingMVC对应的xml
srpingMVC-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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven/> <!-- 配置需要被扫描的包 --> <context:component-scan base-package="com.hqh.springmvc"/> <!-- 配置对静态资源文件的访问不被过滤 WebContent/resources目录中的文件都能访问 --> <mvc:resources location="/resources/" mapping="/resources/**"/> <!-- 配置返回的数据如何呈现:前缀+逻辑视图+后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
控制器
package com.hqh.springmvc.controller; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Random; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ExceptionHandler; 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.SessionAttributes; import org.springframework.web.servlet.view.InternalResourceViewResolver; import com.hqh.springmvc.exception.UserException; import com.hqh.springmvc.model.User; @Controller //访问本控制器的方法的路径都需要加/user @RequestMapping("/user") //只要往Model中添加loginUser,session中就会存储 @SessionAttributes("loginUser") public class UserController { //保证输出的数据与加入Map时的顺序一致,使用LinkedHashMap private static Map<String,User> users = new LinkedHashMap<String,User>(); { users.put("zs", new User(1,"zs",20,"bj")); users.put("ls", new User(2,"ls",20,"sh")); users.put("ww", new User(3,"ww",20,"gd")); users.put("zl", new User(4,"zl",20,"sz")); } //http://localhost:8080/spring_mvc_user/user/list @RequestMapping(value={"/list"}) public String list(Model model) { System.out.println("UserController.list()"); model.addAttribute("users", users); return "user/list"; } //查询用GET @RequestMapping(value={"/addUser"},method=RequestMethod.GET) public String addUser(Model model) { //传递页面中需要赋值的对象到request中,这样spring在处理时才能识别到modelAttribute="user"定义的user //modelAttribute="user" user(User小写:user)实际代表了User.class model.addAttribute(new User()); return "user/add"; } //注:请求addUser页面与提交表单都是访问的addUser(),通过method来区分 //1.请求页面使用get方式,故访问method为GET的addUser() //2.提交的时候使用post方式,故访问method为POST的addUser() //添加用POST @RequestMapping(value={"addUser"},method=RequestMethod.POST) public String addUser(User user) { user.setId(new Random().nextInt(100)); users.put(user.getName(), user); //页面重定向,访问list() return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"/user/list"; } //REST风格:以资源为导向! //通过传入的参数值作为访问方法的后缀名 //http://localhost:8080/spring_mvc_user/user/getUser?name=zs ---> //http://localhost:8080/spring_mvc_user/user/zs @RequestMapping(value={"/{name}"},method=RequestMethod.GET) public String getUser(@PathVariable String name,Model model) { System.out.println("UserController.getUser()"); model.addAttribute(users.get(name)); return "user/detail"; } @RequestMapping(value="/{name}/update",method=RequestMethod.GET) public String updateUser(@PathVariable String name,Model model) { model.addAttribute(users.get(name)); return "user/update"; } @RequestMapping(value="/{name}/update",method=RequestMethod.POST) public String updateUser(@PathVariable String name, User user) { users.put(name, user); return "redirect:/user/list"; } @RequestMapping(value="/{name}/delete",method=RequestMethod.GET) public String deleteUser(@PathVariable String name) { users.remove(name); return "redirect:/user/list"; } @RequestMapping(value="/login",method=RequestMethod.GET) public String login() { return "user/login"; } @RequestMapping(value="/login",method=RequestMethod.POST) public String login(String name, Model model) { if(!users.containsKey(name)) { throw new UserException("用户不存在"); } //将"loginUser"放入session中 model.addAttribute("loginUser",users.get(name)); return "redirect:/user/list"; } /** * 异常处理 * @param ex * @param req * @return */ @ExceptionHandler(value={UserException.class}) public String handlerException(Exception ex, HttpServletRequest req) { req.setAttribute("ex", ex); return "error"; } }
模型
package com.hqh.springmvc.model; public class User { private int id; private String name; private int age; private String addr; public User() { super(); } public User(int id, String name, int age, String addr) { super(); this.id = id; this.name = name; this.age = age; this.addr = addr; } 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } }
异常类
package com.hqh.springmvc.exception; public class UserException extends RuntimeException { public UserException() { super(); } public UserException(String message, Throwable cause) { super(message, cause); } public UserException(String message) { super(message); } public UserException(Throwable cause) { super(cause); } }
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% request.setAttribute("context", this.getServletContext().getContextPath()); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <link rel="stylesheet" type="text/css" href="${context}/resource/css/main.css"> </head> <body> <h1>users</h1> 当前登陆用户:${loginUser.name}<br/> <a href="addUser">add user</a><br/> <c:forEach items="${users}" var="user"> <a href="${user.value.name}">${user.value.name}</a> <a href="${user.value.name}/update">更新</a> <a href="${user.value.name}/delete">删除</a> <br/> </c:forEach> </body> </html>