码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2015-06-02 11:14:51      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:shiro

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

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

标签:shiro

原文地址:http://blog.csdn.net/u010837612/article/details/46325353

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!