spring mvc 异常处理和session添加
在controller中进行设置
package com.stone.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; 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.ResponseBody; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.view.InternalResourceViewResolver; import com.stone.model.User; @Controller @RequestMapping("/user") @SessionAttributes("loginUser")//需要处理的session public class UserController { private final static Map<String, User> users = new HashMap<String, User>(); public UserController() { users.put("ldh", new User("ldh", "刘德华", "123", "123@123.com")); users.put("zxy", new User("zxy", "张学友", "123", "123@123.com")); users.put("gfc", new User("gfc", "郭富城", "123", "123@123.com")); users.put("lm", new User("lm", "黎明", "123", "123@123.com")); } @RequestMapping("/users") public String list(Model model) { model.addAttribute("users", users); return "user/list"; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String login() { return "user/login"; } @RequestMapping(value = "/login", method = RequestMethod.POST) public String login(String username, String password, Model model) { if (!users.containsKey(username)) { throw new RuntimeException("用户名不存在!"); } if (!password.equals(users.get(username).getPassword())) { throw new RuntimeException("用户密码不正确"); } // 进行session的设置 model.addAttribute("loginUser", users.get(username)); return "redirect:/user/users/"; } //进行异常处理 @ExceptionHandler(value = { RuntimeException.class }) public String handlerException(Exception ex, HttpServletRequest req) { req.setAttribute("ex", ex); return "error"; } }