The blog tells the use of interceptors in the form of a demo
The project structure is shown in the figure:
Needed jar: There are jars required for springMVC configuration and jars required for jstl
Description of the function of SpringMVC package:
aopalliance.jar: This package is an AOP alliance API package, which contains interfaces for facets. Usually, other frameworks such as spring that have dynamic weaving functions rely on this jar
spring-core.jar: This jar file contains the basic core tool classes of the Spring framework. All other components of Spring need to use the classes in this package, which is the basic core of other components. Of course, you can also use these tool classes in your own application system.
External dependency Commons Logging, (Log4J).
spring-beans.jar: This jar file is used by all applications. It includes accessing configuration files, creating and managing beans, and performing Inversion of Control /
Dependency Injection (IoC/DI) operations are all classes related to. If the application only requires basic IoC/DI support, introduce spring-core.jar and spring-beans.jar files.
spring-aop.jar: This jar file contains the class and source-level metadata support required when using Spring's AOP feature in your application. Use Spring features based on AOP, such as Declarative Transaction Management, and also include this jar package in the application.
External dependencies spring-core, (spring-beans, AOP Alliance, CGLIB, Commons Attributes).
spring-context.jar: This jar file provides a lot of extensions to the Spring core. All classes you need to use the Spring ApplicationContext feature can be found, JDNI
All required classes, instrumentation components, and related classes for verification Validation.
External dependency spring-beans, (spring-aop).
spring-context-support: Spring-context extension support, used for MVC
spring-web.jar : This jar file contains the core classes required for use in Spring framework during web application development, including classes that automatically load the Web Application Context features, Struts and JSF integration classes, support classes for file uploads, Filter classes and a large number of tool auxiliary classes.
External dependency spring-context, Servlet API, (JSP API, JSTL, Commons FileUpload, COS).
spring-webmvc.jar: This jar file contains all classes related to the Spring MVC framework. Includes Servlets, Web MVC framework, controller and view support for the framework. Of course, if your application uses a standalone MVC framework, you do not need any classes in this JAR file.
External dependency spring-web, (spring-support, Tiles, iText, POI).
spring-aspects.jar: Provides support for AspectJ so that aspect-oriented functions can be easily integrated into IDEs, such as Eclipse AJDT.
External dependencies.
spring-jdbc.jar: This jar file contains all classes that encapsulate Spring's JDBC data access.
External dependency spring-beans, spring-dao.
spring-test.jar: Simple encapsulation of test frameworks such as Junit
spring-tx.jar: Spring's jar for tx transaction processing
spring-expression.jar: Spring expression language
Write a controller:
package com.mvc.action; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * Login authenticated controller*/ @Controller public class LoginControl { /** * Login* @param session * HttpSession * @param username * Username * @param password * Password * @return */ @RequestMapping(value="/login") public String login(HttpSession session,String username,String password) throws Exception{ //Save information in the Session session.setAttribute("username", username); //Redirect return "redirect:hello.action"; } /** * Exit the system* @param session * Session * @return * @throws Exception */ @RequestMapping(value="/logout") public String logout(HttpSession session) throws Exception{ //Clear Session session.invalidate(); return "redirect:hello.action"; } } Write an interceptor:
package com.mvc.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /** * Login authentication interceptor*/ public class LoginInterceptor implements HandlerInterceptor{ /** * Call this method after the Handler is executed*/ public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exc) throws Exception { } /** * After the Handler is executed, the ModelAndView returns to call this method before the ModelAndView returns*/ public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * This method is called before Handler execution*/ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //Get the requested URL String url = request.getRequestURI(); //URL:login.jsp is publicly accessible; this demo is intercepted except login.jsp, other URLs are intercepted if(url.indexOf("login.action")>=0){ return true; } //Get Session HttpSession session = request.getSession(); String username = (String)session.getAttribute("username"); if(username != null){ return true; } //If the conditions do not meet the conditions, jump to the login interface request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response); return false; } } SpringMVC configuration file:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- Use component scan --> <!-- Scan the action, register it in the spring container, and automatically configure the action in the spring container --> <context:component-scan base-package="com.mvc.action" /> <!-- Project Handler <bean name="/hello.action"></bean> --> <!-- Processor Mapper HandlerMapping --> <bean/> <bean> <property name="messageConverters"> <list> <bean></bean> </list> </property> </bean> <!-- View Resolver --> <!-- Parse jsp, default support for jstl --> <bean> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- In actual development, you usually need to configure the mvc:annotation-driven tag. This tag is to enable annotation--> <mvc:annotation-driven></mvc:annotation-driven> <!-- Interceptor--> <mvc:interceptors> <!-- Multiple interceptors, executed sequentially --> <mvc:interceptor> <mvc:mapping path="/**"/> <bean></bean> </mvc:interceptor> </mvc:interceptors> </beans>
Login interface:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'login.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="${pageContext.request.contextPath}/login.action" method="post"> Username:<input type="text" name="username" /><br> Password:<input type="text" name="password" /><br> <input type="submit" value="Login" /> </form> </body> </html> After logging in successfully, jump to the interface
hello.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://www.springframework.org/tags" prefix="spring" %> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'hello.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> Current user:${username} <c:if test="${username!=null}"> <a href="${pageContext.request.contextPath }/logout.action">Exit</a> </c:if> ${message} </body> </html> HelloControl.java, I write it in HelloWorld form, and I need to modify it according to the project.
package com.mvc.action; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; //Tag this class as a Handler processor @Controller public class HelloAction{ @RequestMapping("/hello")//Develop the url corresponding to this control class public String hello(Model model){ String message = "SpringMVC"; //Add Attribute for the model model.addAttribute("message",message); return "hello"; } // public ModelAndView handleRequest(HttpServletRequest request, // HttpServletResponse response) throws Exception { // // // Prompt a line of information on the page// String message = "hello world!"; // // // Display the information on the page through the request object// //request.setAttribute("message", message); // // ModelAndView modelAndView = new ModelAndView(); // // Equivalent to request.setAttribute(), pass data to the page to display // //model data// modelAndView.addObject("message", message); // // Set view// modelAndView.setViewName("hello"); // // return modelAndView; // } } The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.