• 欢迎访问VPS岛网站,国外VPS,国内VPS,国外服务器,国内服务器,服务器主机,测评及优惠码,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站 QQ群

Apache Shiro学习笔记(五)Web集成简单配置

Apache技术 luchunli1985 20次浏览 已收录 0个评论

鲁春利的工作笔记,好记性不如烂笔头


http://shiro.apache.org/web-features.html

ShiroFilter

Shiro 提供了与Web集成的支持,其通过一个ShiroFilter来指定拦截的URL,然后进行相应的控制。ShiroFilter类似于如Strut2/SpringMVC这种Web框架的前端控制器,其负责读取配置(如ini 配置文件),然后判断URL 是否需要登录/权限等工作。

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>Invicme</display-name>
  <listener>
    <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
  </listener>
  
  <context-param>
    <param-name>shiroEnvironmentClass</param-name>
    <param-value>org.apache.shiro.web.env.IniWebEnvironment</param-value>
  </context-param>
  
  <!-- 修改默认实现及其加载的配置文件位置 -->
  <context-param>
    <param-name>shiroConfigLocations</param-name>
    <param-value>classpath:shiro/normal-shiro.ini</param-value>
  </context-param>
  
  <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>
  
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
  • 1、EnvironmentLoaderListener

通 过EnvironmentLoaderListener 来创建相应的WebEnvironment, 并自动绑定到ServletContext,默认使用IniWebEnvironment实现。

  • 2、shiroConfigLocations

默认是“/WEB-INF/shiro.ini”,IniWebEnvironment 默认是先从/WEB-INF/shiro.ini加载,通过配置指定后就加载classpath:shiro/normal-shiro.ini。

wKioL1ed7VygTWJYAADm4XVitxY844.jpg


normal-shiro.ini

[main]
#默认是/login.jsp
authc.loginUrl=/login
# unauthorizedUrl属性指定如果授权失败时重定向到的地址。
# roles 是org.apache.shiro.web.filter.authz.RolesAuthorizationFilter类型的实例。
roles.unauthorizedUrl=/unauthorized
# perms 是org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter类型的实例。
perms.unauthorizedUrl=/unauthorized

[users]
# 用户名=密码,角色
# 说明:这里的密码是加密之后的数据
lucl=e10adc3949ba59abbe56e057f20f883e,admin
wang=e10adc3949ba59abbe56e057f20f883e

[roles]
admin=user:*,menu:*

[urls]
/login=anon
/static/**=anon
/role=authc,roles[admin]
/permission=authc,perms["user:create"]
/unauthorized=anon
/logout=logout

说明:

    其中最重要的就是[urls]部分的配置,其格式是: “url=拦截器[参数],拦截器[参数]”;即如果当前请求的url匹配[urls]部分的某个url模式,将会执行其配置的拦截器。
    比如anon拦截器表示匿名访问(即不需要登录即可访问);

    authc拦截器表示需要身份认证通过后才能访问;

    roles[admin]拦截器表示需要有admin 角色授权才能访问;

    而perms[“user:create”]拦截器表示需要有“user:create”权限才能访问。

Servlet定义

  • LoginServlet

package com.invicme.apps.servlet.authc;

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.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
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;

/**
 * @author lucl
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public LoginServlet() {
        super();
    }

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

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            request.getRequestDispatcher("shiro/admin/login.jsp").forward(request, response);
            return;
        }
        
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, DigestUtils.md5Hex(password));
        String msg = "";
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            msg = "用户名/密码错误";
        } catch (IncorrectCredentialsException e) {
            msg = "用户名/密码错误";
        } catch (AuthenticationException e) {
        //其他错误,比如锁定,如果想单独处理请单独catch 处理
            msg = "其他错误:" + e.getMessage();
        }
        if(!StringUtils.isBlank(msg)) {//出错了,返回登录页面
            request.setAttribute("msg", msg);
            request.getRequestDispatcher("shiro/admin/login.jsp").forward(request, response);
        } else { // 登录成功
            request.setAttribute("subject", subject);
            request.getRequestDispatcher("shiro/admin/success.jsp").forward(request, response);
        }
    }
    
    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(DigestUtils.md5Hex("123456"));
    }
}

  • PermissionServlet

package com.invicme.apps.servlet.authc;

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;

/**
 * @author lucl
 */
@WebServlet("/permission")
public class PermissionServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public PermissionServlet() {
        super();
    }

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

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("shiro/user/perms.jsp").forward(request, response);
    }

}

  • RoleServlet

package com.invicme.apps.servlet.authc;

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;

/**
 * @author lucl
 */
@WebServlet("/role")
public class RoleServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public RoleServlet() {
        super();
    }

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

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("shiro/user/role.jsp").forward(request, response);
    }

}

  • UnauthorizedServlet

package com.invicme.apps.servlet.authc;

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;

/**
 * @author lucl
 */
@WebServlet("/unauthorized")
public class UnauthorizedServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public UnauthorizedServlet() {
        super();
    }

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

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("shiro/user/unauthorized.jsp").forward(request, response);
    }

}

Jsp

wKioL1ed8H3DtOyCAAEfIb295uI409.jpg

  • 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">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>登录页</title>
    </head>
    <body>
        <h1>This is login page.</h1><font color="red">${msg}</font>
        <form name="loginForm" action="<%=request.getContextPath()%>/login" method="POST">
            用户名:<input type="text" name="username"    value="" />
            <br/>
            密码:<input type="password" name="password"    value="" />
            <br/>
            <input type="submit" name="sub" value="提交" />
        </form>
    </body>
</html>

  • success.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">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>登录成功</title>
    </head>
    <body>
        <h1>Welcome,${subject.principal}.</h1>
    </body>
</html>

  • perms.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">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>权限</title>
    </head>
    <body>
        <h1>This is permission page.</h1>
    </body>
</html>

  • role.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">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>角色</title>
    </head>
    <body>
        <h1>This is role jsp.</h1>
    </body>
</html>

  • unauthorized.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">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>未授权</title>
    </head>
    <body>
        <h1>无访问权限</h1>
    </body>
</html>


VPS岛 的文章和资源来自互联网,仅作为参考资料,如果有侵犯版权的资源请尽快联系站长,我们会在24h内删除有争议的资源。丨 转载请注明Apache Shiro学习笔记(五)Web集成简单配置
喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址