Shiro Study notes (5)--web integration

Source: Internet
Author: User

    • Web integration
      • Shiro configuration file Shiroini
      • Interface
      • Webxml the key
      • Servlet
      • Test
      • Basic-Based Interceptor authentication

Web integration

In most cases, the Web project will integrate spring. Shiro is not the same configuration in a normal Web project and in a spring project. For Spring-shiro integration, you can refer to the example code in the JSP tag authorization section of the Shiro Learning Note (3)-Authorization (Authorization)

This article describes a common Web project and does not use any framework.

Shiro configuration file (Shiro.ini)

Create a Web project and create a Shiro.ini under SRC

[main]#默认的登录界面是/login.jspauthc.loginUrl=/login.jsproles.unauthorizedUrl=/unauthorizedperms.unauthorizedUrl=/unauthorizedauthcBasic.applicationName=please login[users]zhang=123,adminwang=123[roles]admin=user:*,menu:*[urls]/login=anon/success=authc/unauthorized=anon/static/**=anon/authenticated=authc/role=authc,roles[admin]/permission=authc,perms["user:create"]

For a specific description of the configuration file, refer to the Shiro Learning Note (4)--ini configuration

Here are a few of the areas to focus on:

    • authc.loginurl=/login.jsp
    • /login=anon
    • /success=authc

When accessing/success this path, if not logged in, will automatically jump to the login interface/login.jsp, Access/login This path, you can not login

Interface

Ready to login interface and login successful interface

Login interface

<%@ page language="java" contenttype="text/html; Charset=iso-8859-1 "pageencoding="iso-8859-1"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" ><html><head><meta http-equiv="Content-type" Content="text/html; Charset=iso-8859-1 "><title>Please login</title></head><body>    <H1>Login</H1>    <form Action="Login">        <label>Username</label>        <input type="text" name="username"/>        <label>Password</label>        <input type="text" name="password"/>        <input type="Submit" value="Submit"/>    </form></body></html>

Login Success Screen

<%@ page language="java" contenttype="text/html; Charset=iso-8859-1 "pageencoding="iso-8859-1"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" ><html><head><meta http-equiv="Content-type" Content="text/html; Charset=iso-8859-1 "><title>Login successful</title></head><body><H1>Successful</H1></body></html>
Web. XML (most critical)

This is the most critical step.

<?xml version= "1.0" encoding= "UTF-8"?><web-app xmlns: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>Shiro-web</display-name>  <!--The purpose of this configuration is to have the Shiro start when the project starts.  <listener>    <listener-class>Org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>  </listener>  <!--Configure the location of the Shiro configuration file, the default location is/web-inf/shiro.ini--  <context-param>    <param-name>Shiroconfiglocations</param-name>    <param-value>Classpath:shiro.ini</param-value>  </context-param>  <!--Shiro Filters --  <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>    <dispatcher>REQUEST</Dispatcher>    <dispatcher>FORWARD</Dispatcher>    <dispatcher>INCLUDE</Dispatcher>    <dispatcher>ERROR</Dispatcher>  </filter-mapping></Web-app>
Servlet

Loginservlet: servlet handling Login request, redirect to/success if login is successful

 PackageCom.shiro.servlet;ImportJava.io.IOException;ImportJavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.shiro.SecurityUtils;ImportOrg.apache.shiro.authc.AuthenticationException;ImportOrg.apache.shiro.authc.IncorrectCredentialsException;ImportOrg.apache.shiro.authc.UnknownAccountException;ImportOrg.apache.shiro.authc.UsernamePasswordToken;ImportOrg.apache.shiro.subject.Subject;/** * Servlet Implementation class Loginservlet */@WebServlet(name="/loginservlet", urlpatterns="/login") Public  class loginservlet extends httpservlet {    Private Static Final LongSerialversionuid =1Lprotected void Doget(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {String username = request.getparameter ("username"); String Password = request.getparameter ("Password");        Subject CurrentUser = Securityutils.getsubject (); Usernamepasswordtoken token =NewUsernamepasswordtoken (Username,password);Try{Currentuser.login (token); }Catch(Unknownaccountexception e) {System.out.println ("There's no such user."); }Catch(Incorrectcredentialsexception e) {System.out.println ("Password Bug"); }Catch(Authenticationexception e) {//Other errors, such as locking, if you want to handle it individually, catch processing separatelySystem.out.println ("Other error:"+ e.getmessage ()); } response.sendredirect (Request.getcontextpath () +"/success"); }protected void DoPost(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {doget (request, response); }}

Successservlet: Login Success Interface corresponds to Servlet, only plays the role of forwarding

 PackageCom.shiro.servlet;ImportJava.io.IOException;ImportJavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/** * Servlet Implementation class Successservlet */@WebServlet(name="/successservlet", urlpatterns="/success") Public  class successservlet extends httpservlet {    Private Static Final LongSerialversionuid =1L/** * @see httpservlet#doget (httpservletrequest request, httpservletresponse response) */    protected void Doget(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {request.getrequestdispatcher ("/web-inf/views/success.jsp"). Forward (request, response); }/** * @see httpservlet#dopost (httpservletrequest request, httpservletresponse response) */    protected void DoPost(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {doget (request, response); }}
Test
    • Visit/success,shiro Discovery We are not logged in and automatically jump to the/login.jsp interface

    • Enter user name password (config in Shiro.ini), login successful, jump to successful interface

To do this, the basic Web integration has been completed, but in the actual development, we usually need to configure other components such as realm, from the database to read user information, user's role, permissions, etc., can refer to Shiro study notes (2)--Realm of authentication

Basic-Based Interceptor authentication

What is a basic-based interceptor? In the code above, when we visited/success, Shiro found that we were not logged in and automatically jumped to the/login.jsp interface.
The so-called basic-based interceptors, when we are not logged in, do not jump to the/login.jsp interface, but jump out of the box below to let us log in

The whole process and effect is the same as above, but usually it will not be used. And I found that this does not work in Google Chrome, Firefox and IE can. I do not know whether I character problem.

How to do?? Modify a row of configurations in Shiro.ini

[urls]/success=authcBasic

Shiro Study notes (5)--web integration

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.