Shiro and basic Web Environment integration Login Verification Instance

Source: Internet
Author: User

1. Importing Shiro dependency packages with Maven

 <Dependency>      <groupId>Org.apache.shiro</groupId>      <Artifactid>Shiro-web</Artifactid>      <version>1.2.2</version>  </Dependency>  <Dependency>          <groupId>Commons-logging</groupId>          <Artifactid>Commons-logging</Artifactid>          <version>1.1.3</version>    </Dependency> 

2. Configure Web. xml

   <!--Initialize Shiro Web environment -    <Listener>          <Listener-class>Org.apache.shiro.web.env.EnvironmentLoaderListener</Listener-class>  </Listener>  <!--setting up the Shiro interceptor -   <Filter>      <Filter-name>Shirofilter</Filter-name>      <Filter-class>Org.apache.shiro.web.servlet.ShiroFilter</Filter-class>  </Filter>    <filter-mapping>      <Filter-name>Shirofilter</Filter-name>      <Url-pattern>/*</Url-pattern>  </filter-mapping>

3. Configure the initialization Shiro configuration file Shiro.ini The class file root directory

[Main]authc.loginurl=/loginauthc.successurl=/index[users]zhang=123,role1,role2  wang=123,role1  [URLs] /login=authc/logout=logout/* = authc

4. Create a servlet and map to the login path/login

public class Loginservlet extends HttpServlet {private static final long serialversionuid = 1L;    Public Loginservlet () {super (); }/**get request to display the login interface with error messages */protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//Display Login Interface Request.getrequestdispatcher ("/login.jsp"). Forward (request, response);} /**formauthenticationfilter will intercept the POST request for login and we do not need to log in again. */protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {System.out.println ("Login failed to enter Dopost method. Because the interceptor intercepts the post request to log in, the login succeeds and jumps directly to the access page. Login failed to enter POST method "); SYSTEM.OUT.PRINTLN ("Login failed to login interface and add error message");//formauthenticationfilter.default_error_key_attribute_ The name value is shirologinfailure, the login error message is saved, and the class full name of the exception is string errorfullclassname = (string) Request.getattribute ( Formauthenticationfilter.default_error_key_attribute_name); String cerrorkey= "error";//The client displays an error message if (UnknownAccountException.class.getName (). Equals (Errorfullclassname)) {// Unknown account reqUest.setattribute (Cerrorkey, "User name password Error");} else if (IncorrectCredentialsException.class.getName () equals (Errorfullclassname)) {//Password error Request.setattribute ( Cerrorkey, "User name password Error");} else{//other errors such as account lockout, etc. request.setattribute (Cerrorkey, "other Error");} Display Login Interface Doget (request, Response);}}

  

  <servlet>      <Servlet-name>Loginservlet</Servlet-name>      <Servlet-class>Baseshiroweb. Loginservlet</Servlet-class>  </servlet>    <servlet-mapping>      <Servlet-name>Loginservlet</Servlet-name>      <Url-pattern>/login</Url-pattern>  </servlet-mapping>

5. Create a login interface login.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >Landing Interface <br/> <form action= "/baseshiroweb/login" method= "POST" >   <input type= "text" name= "username"/> <br/>   <input type= "password" name= "password"/><br/> <input   type= "checkbox" Name= "RememberMe" value= "true"/>remember me?<br/>   <input type= "Submit" value= "Submit"/></form >${error}</body>

6. Create a login successful message display servlet and add exit

public class Myservlet extends httpservlet{@Overrideprotected void doget (HttpServletRequest req, httpservletresponse RESP) throws Servletexception, IOException {resp.getwriter (). println ("
  <servlet>      <Servlet-name>Myservlet</Servlet-name>      <Servlet-class>Baseshiroweb. Myservlet</Servlet-class>  </servlet>      <servlet-mapping>      <Servlet-name>Myservlet</Servlet-name>      <Url-pattern>/index</Url-pattern>  </servlet-mapping>

Visit Http://localhost:8080/baseshiroweb/index at this time

Execution process:

1. The/index path will be requested

2. The AUTHC interceptor that matches the/* path within [URLs] in the Shiro configuration file, jumps to the login login interface/login

3. Login operation in/login, success jumps to/index, failure returns to/login interface and displays error message

After 4./index successfully logged in, click the hyperlink logout access/logout to exit the operation. /logout path matching logout interceptor.

The complete Web. XML is

<?XML version= "1.0" encoding= "UTF-8"?><Web-appXmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns= "Http://java.sun.com/xml/ns/javaee"xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"ID= "webapp_id"version= "3.0">   <Display-name>Archetype Created Web Application</Display-name>   <!--Initialize Shiro Web environment -    <Listener>          <Listener-class>Org.apache.shiro.web.env.EnvironmentLoaderListener</Listener-class>  </Listener>  <!--setting up the Shiro interceptor -   <Filter>      <Filter-name>Shirofilter</Filter-name>      <Filter-class>Org.apache.shiro.web.servlet.ShiroFilter</Filter-class>  </Filter>    <filter-mapping>      <Filter-name>Shirofilter</Filter-name>      <Url-pattern>/*</Url-pattern>  </filter-mapping>    <servlet>      <Servlet-name>Myservlet</Servlet-name>      <Servlet-class>Baseshiroweb. Myservlet</Servlet-class>  </servlet>      <servlet-mapping>      <Servlet-name>Myservlet</Servlet-name>      <Url-pattern>/index</Url-pattern>  </servlet-mapping>    <servlet>      <Servlet-name>Loginservlet</Servlet-name>      <Servlet-class>Baseshiroweb. Loginservlet</Servlet-class>  </servlet>    <servlet-mapping>      <Servlet-name>Loginservlet</Servlet-name>      <Url-pattern>/login</Url-pattern>  </servlet-mapping></Web-app>

Shiro and basic Web Environment integration Login Verification Instance

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.