SPRINGMVC Interceptor Implementation Login Authentication _java

Source: Internet
Author: User
Tags aop xmlns

Blog in the form of demo to talk about the use of interceptors

Project structure as shown:


Required jars: Jars required for SPRINGMVC configuration and Jstl needed


SPRINGMVC Package Function Description:

Aopalliance.jar: This package is an AOP Federation API package that contains a facet-oriented interface. Often other frameworks with dynamic weaving capabilities, such as spring, depend on this jar

Spring-core.jar: This jar file contains the basic core tool classes of the spring framework. The classes in this package are used by other components of Spring and are the basic core of other components, but you can also use them in your own application system.
External Dependent Commons Logging, (log4j).

Spring-beans.jar: This jar file is for all applications, it contains access to configuration files, creating and managing beans, and inversion of control/
Dependency Injection (IOC/DI) All classes related to the operation. If the application requires only basic Ioc/di support, the introduction of Spring-core.jar and Spring-beans.jar files
It's OK.

Spring-aop.jar: This jar file contains the class and source-level metadata support required to use spring's AOP features in your application. Use the AOP-based spring features, such as declarative transaction management (declarative Transaction Management), and include this jar package in your application.

External dependent Spring-core, (SPRING-BEANS,AOP Alliance, Cglib,commons Attributes).

Spring-context.jar: This jar file provides a large number of extensions to the spring core. You can find all the classes you need to use the Spring applicationcontext feature, Jdni
All of the required classes, instrumentation components, and related classes for validating validation.
External dependent Spring-beans, (SPRING-AOP).
Spring-context-support: Extended support for Spring-context, for MVC

Spring-web.jar: This jar file contains the core classes needed to use the spring framework when Web application development, including classes that automatically load the Web application context feature, Struts and JSF integration classes, Support classes, Filter classes, and a large number of tool-assisted classes for file uploads.

External dependencies Spring-context, Servlet API, (JSP API, JSTL, Commons fileupload, COS).

Spring-webmvc.jar: This jar file contains all the classes associated with the Spring MVC framework. Includes the framework's Servlets,web MVC Framework, controller, and view support. Of course, if your application uses a separate MVC framework, you don't need any of the classes in the jar file.

External dependent spring-web, (spring-support,tiles,itext,poi).

Spring-aspects.jar: provides support for ASPECTJ so you can easily integrate aspect-oriented features into the IDE, such as Eclipse AJDT.
External dependencies.

Spring-jdbc.jar: This jar file contains all the classes that encapsulate the spring's access to JDBC data.
External dependent Spring-beans,spring-dao.

Spring-test.jar: simple encapsulation of test frameworks such as JUnit

Spring-tx.jar: The jar of Spring's TX transaction processing

Spring-expression.jar: Spring Expression Language

Write Controller:

Package com.mvc.action; 
 
Import javax.servlet.http.HttpSession; 
 
Import Org.springframework.stereotype.Controller; 
Import org.springframework.web.bind.annotation.RequestMapping; 
 
/** 
 * Login Certified controller/ 
@Controller Public 
class Logincontrol { 
 
 /** 
  * Login 
  * @param session 
  *   HttpSession * 
  @param username 
  *   user name 
  * @param password 
  *   password * 
  @return 
  * * 
 @RequestMapping (value= "/login") Public 
 String Login (HttpSession session,string username,string password) Throws exception{  
  //Save information in session 
  Session.setattribute ("username", username); 
  REDIRECT Return 
  "Redirect:hello.action"; 
 } 
  
 /** * 
  Exit System * @param session * 
  @return * 
  @throws Exception 
 * * Requestmapping (value= "/logout") public 
 String Logout (HttpSession session) throws exception{ 
  //Clear session 
  session.invalidate (); 
   
  return "Redirect:hello.action"; 
 } 
  
  
  
 

Writing interceptors:

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 Certified Interceptor/public class Logininterceptor implements handlerinterceptor{/** * Handler This method is called after execution is completed. public void Aftercompletion (HttpServletRequest request, httpservletresponse response, Object handler, Exception exc Throws Exception {}/** * handler after execution, this method is called by the Modelandview before it returns * * * public void Posthandle (Httpservle 
 
 Trequest request, HttpServletResponse response, Object handler, Modelandview Modelandview) throws Exception {} 
   /** * Handler to invoke this method before executing * * public boolean prehandle (HttpServletRequest request, httpservletresponse response, 
  Object handler) throws Exception {//Get the requested URL String url = Request.getrequesturi (); Url:login.jThe SP is public; This demo is open, except that the login.jsp is publicly accessible, and the other URLs are blocking control 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; 
   
  ///Not eligible, jump to 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=" 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/ Spring-aop-4.0.xsd Http://www.springframework.org/schema/context 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 scans--> <!--to scan the action, register in the spring container, and automatically configure the action in the spring container--> 
  Handler of <context:component-scan base-package= "Com.mvc.action"/> <!--project<bean name= "/hello.action" class= "com.mvc.action.HelloAction" ></bean>--> <!--processor Mapper Handlermappi ng--> <bean class= "org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/ > <!--processor set adapter Handleradapter--> <bean class= "ORG.SPRINGFRAMEWORK.WEB.SERVLET.MVC.METHOD.ANNOTATION.R Equestmappinghandleradapter "> <property name=" messageconverters "> <list> <bean class=" org . Springframework.http.converter.json.MappingJacksonHttpMessageConverter "></bean> </list> </pro Perty> </bean> <!--view parser Viewresolver--> <!--parse JSP, default support Jstl--> <bean class= "Org.s Pringframework.web.servlet.view.InternalResourceViewResolver "> <property name=" viewclass "value=" Org.springframework.web.servlet.view.JstlView "></property> <property name=" prefix "value="/web-inf/ jsp/"/> <property name=" suffix "value=". JSP "/> </bean> <!--usually need to configure Mvc:annotation-driven tags in actual development, which is to open annotations--> &LT;MVC:ANNOTATION-DRIVEN&G T;</mvc:annotation-driven> <!--Interceptor--> <mvc:interceptors> <!--multiple interceptors, sequentially executing--> <m vc:interceptor> <mvc:mapping path= "/**"/> <bean "class=" >< 
 /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" >  

After successful login, the Jump 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.G 
Etcontextpath (); 
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

Hellocontrol.java, I write HelloWorld form, I want to change according to the project Oh

Package com.mvc.action; 
Import Org.springframework.stereotype.Controller; 
Import Org.springframework.ui.Model; 
 
Import org.springframework.web.bind.annotation.RequestMapping; Tag This class is a handler processor @Controller public class helloaction{@RequestMapping ("/hello")//the URL public String corresponding to this control class 
  Hello (model model) {String message = "SPRINGMVC"; 
  Add attribute Model.addattribute for model ("message", message); 
 return "Hello";  
}//Public Modelandview HandleRequest (httpservletrequest request,//HttpServletResponse response) throws Exception { 
//Prompt a line on the page//String message = "Hello world!"; 
////request.setattribute The information on the page through the Request object ("message", messages); 
Modelandview Modelandview = new Modelandview (); 
Equivalent to Request.setattribute (), upload the data to the page display////model data//Modelandview.addobject ("message", message); 
Set view//Modelandview.setviewname ("Hello"); 
return modelandview; 
 // } 
  
  
 
  
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.