In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "how to use SpringMVC interceptor in Java". The content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "how to use SpringMVC interceptor in Java".
Function of interceptor (interceptor)
Spring MVC's interceptor is similar to the filter Filter in Servlet development and is used for pre-processing and post-processing of processors.
The interceptor is connected into a chain in a certain order, which is called the interceptor chain (Interceptor Chain). When you access an intercepted method or field, the interceptors in the interceptor chain are called in the order they were previously defined. Interceptor is also a concrete implementation of AOP idea.
The difference between interceptor and filter
Getting started with interceptor
Interceptor Quick start Custom Interceptor is simple, with only the following three steps:
① creates interceptor class to implement Handlerlnterceptor interface
② configuration interceptor
③ tests the interception effect of the interceptor
① creates interceptor class to implement Handlerlnterceptor interface
Public class MyInterceptor1 implements HandlerInterceptor {/ / execute public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {System.out.println ("preHandle."); String param = request.getParameter ("param"); if ("yes" .equals (param)) {return true before the target method executes } else {request.getRequestDispatcher ("/ error.jsp") .forward (request,response); return false;// returns true for release, return false for no release}} / / execute public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {modelAndView.addObject ("name", "itheima") before the view object is returned after the execution of the target method System.out.println ("postHandle...");} / / execute public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {System.out.println ("afterCompletion....");}} after the process has been executed
② configuration interceptor
③ tests the interception effect of the interceptor
@ Controllerpublic class TargetController {@ RequestMapping ("/ target") public ModelAndView show () {System.out.println ("target resource execution."); ModelAndView modelAndView = new ModelAndView (); modelAndView.addObject ("name", "itcast"); modelAndView.setViewName ("index"); return modelAndView;}} case: user login permission control
Requirements: when the user is not logged in, the background menu cannot be accessed. Click the menu to jump to the login page. Only after the user has successfully logged in can the background function be operated.
Public class PrivilegeInterceptor implements HandlerInterceptor {public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {/ / Logic: determine whether a user is logged in in nature: determine whether there is user HttpSession session = request.getSession () in session; User user= (User) session.getAttribute ("user"); if (user==null) {/ / does not log in to response.sendRedirect (request.getContextPath () + "/ login.jsp") Return false;} / / release access to the target resource return true;}}
Spring-mvc.xml:
UserServiceImpl
Public User login (String username, String password) {try {User user = userDao.findByUsernameAndPassword (username,password); return user;} catch (EmptyResultDataAccessException e) {return null;}}
UserService
User login (String username, String password)
UserDaoImpl
Public User findByUsernameAndPassword (String username, String password) throws EmptyResultDataAccessException {User user = jdbcTemplate.queryForObject ("select * from sys_user where username=? and password=?", new BeanPropertyRowMapper (User.class), username, password); return user;}
UserDao
User findByUsernameAndPassword (String username, String password); interceptor method description
The thought of exception handling in SpringMVC
Exceptions in the system include two types of ∶ expected exceptions and run-time exception RuntimeException. The former obtains exception information by capturing exceptions, while the latter mainly reduces the occurrence of runtime exceptions by means of standard code development and testing.
The Dao, Service and Controller of the system are all thrown up through throws Exception, and finally the SpringMVC front-end controller hands over the exception handler to handle the exception, as shown below:
Two ways of exception handling
1. Use the simple exception handler SimpleMappingExceptionResolver provided by Spring MVC
SpringMVC has defined the type converter, and when using it, you can map the exception to the view according to the project situation.
2. Implement Spring's exception handling interface HandlerExceptionResolver to customize your own exception handler.
① creates exception handler classes to implement HandlerExceptionResolver
Public class MyExceptionResolver implements HandlerExceptionResolver {/ * parameter Exception: exception object return value ModelAndView: jump to error view message * / public ModelAndView resolveException (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {ModelAndView modelAndView = new ModelAndView (); if (e instanceof MyException) {modelAndView.addObject ("info", "custom exception") } else if (e instanceof ClassCastException) {modelAndView.addObject ("info", "class conversion exception");} modelAndView.setViewName ("error"); return modelAndView;}}
② configuration exception handler
③ writes exception page
Title common error prompt page ${info}
④ test abnormal jump
The above is all the content of the article "how to use SpringMVC interceptor in Java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.