SpringMVC Exception Handling

Source: Internet
Author: User

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}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.