SpringMVC Exception Handling
1. customize an exception class: UserException. java
public class UserException extends RuntimeException {private static final long serialVersionUID = 1L;public UserException() {super();}public UserException(String message, Throwable cause) {super(message, cause);}public UserException(String message) {super(message);}public UserException(Throwable cause) {super(cause);}}
2. Example of User Logon: UserController. java
If the user name does not exist or the user password is incorrect, the system throws an exception and jumps to the error. jsp page.
@ Controller @ RequestMapping ("/user") public class UserController {// simulate database private map using Map
UserMap = new HashMap
(); Public UserController () {userMap. put ("zhangsan", new User ("zhangsan", "123"); userMap. put ("lishimin", new User ("lishimin", "456");} // handle User logon exceptions // access method: http: // localhost/springmvc_user/login. jsp @ RequestMapping (value = "/login", method = RequestMethod. POST) public String login (String username, String password, HttpSession session) {if (! UserMap. containsKey (username) {throw new UserException ("the User name does not exist");} user User user = userMap. get (username); if (! User. getPassword (). equals (password) {throw new UserException ("incorrect user password");} session. setAttribute ("loginUser", user); return "redirect:/user/users";}/*** local Exception Handling (only exceptions in this controller can be handled) */@ ExceptionHandler (value = {UserException. class}) public String handlerException (UserException e, HttpServletRequest request) {request. setAttribute ("exception", e); return "exception/error ";}}
3. configure global Exception Handling: user-servlet.xml
Exception/error
4. error message page: error. jsp
<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %>
Error PageError found: $ {exception. message}