Shiro学习笔记(5)——web集成

Web集成

大多数情况。web项目都会集成spring。shiro在普通web项目和spring项目中的配置是不一样的。关于spring-shiro集成,能够參考Shiro学习笔记(3)——授权(Authorization) 中的JSP标签授权部分演示样例代码

本次介绍普通的web项目,不使用不论什么框架。

shiro配置文件(shiro.ini)

创建web项目。然后在src下创建shiro.ini

[main]
#默认的登录界面是/login.jsp
authc.loginUrl=/login.jsp
roles.unauthorizedUrl=/unauthorized
perms.unauthorizedUrl=/unauthorized
authcBasic.applicationName=please login
[users]
zhang=123,admin
wang=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"]

关于配置文件的详细说明,能够參考Shiro学习笔记(4)——ini 配置

这里须要关注的有几个:

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

当訪问/success这个路径的时候,假设没有登录。将会自己主动跳转到登录界面/login.jsp,訪问/login这个路径的时候,能够不用登录

界面

准备登录界面和登录成功的界面

登录界面

<%@ 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>请登录</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>

登录成功界面

<%@ 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>登录成功</title>
</head>
<body>
<h1>SUCCESSFUL</h1>
</body>
</html>

web.xml(最关键)

这是最关键的步骤

<?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> <!-- 该配置的作用是让shiro在项目启动的时候随之启动 --> <listener> <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class> </listener> <!-- 配置shiro配置文件的位置,默认位置是/WEB-INF/shiro.ini --> <context-param> <param-name>shiroConfigLocations</param-name> <param-value>classpath:shiro.ini</param-value> </context-param> <!-- shiro过滤器 --> <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。假设登录成功,重定向到/success

package com.shiro.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet(name="/LoginServlet",urlPatterns="/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Subject currentUser = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            currentUser.login(token);
        } catch (UnknownAccountException e) {
            System.out.println("沒有這個用戶");
        } catch (IncorrectCredentialsException e) {
            System.out.println("密碼錯誤");
        } catch (AuthenticationException e) {
        //其它错误,比方锁定。假设想单独处理请单独 catch 处理
            System.out.println("其它错误:" + e.getMessage());
        }
        response.sendRedirect(request.getContextPath()+"/success");
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

SuccessServlet:登录成功界面相应Servlet,仅仅起到转发的作用

package com.shiro.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SuccessServlet
 */
@WebServlet(name="/SuccessServlet",urlPatterns="/success")
public class SuccessServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, 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) throws ServletException, IOException {
        doGet(request, response);
    }

}

測试

  • 訪问/success,shiro发现我们还未登录,自己主动跳转到/login.jsp界面

这里写图片描写叙述

  • 输入用户名密码(shiro.ini中有配置)。登录成功,跳转到成功界面

这里写图片描写叙述

做到这里,主要的web集成就已经完毕,可是在实际开发中,我们通常须要配置Realm等其它组件。从数据库中读取用户信息,用户的角色,权限等。能够參考Shiro学习笔记(2)——身份验证之Realm

基于 Basic 的拦截器身份验证

什么是基于Basic的拦截器呢?在上面的代码中。我们訪问/success时,shiro发现我们没登录。就自己主动跳转到/login.jsp界面
所谓的基于Basic的拦截器,就是当我们没登录时,不跳转到/login.jsp界面,而是跳出以下这个框让我们登录
这里写图片描写叙述

整个过程和效果和上面是一样的,只是平时一般也不会用到这个。

并且我发现这个在谷歌浏览器中不起作用。火狐和IE都能够。不知道是不是本人人品问题。

怎么做??在shiro.ini中改动一行配置就可以

[urls]
/success=authcBasic
原文地址:https://www.cnblogs.com/mengfanrong/p/5142608.html