shiro-web integration

Web integration

In most cases, web projects will integrate spring. The configuration of shiro in ordinary web projects and spring projects is different.

This time we will introduce common web projects without using any framework.

shiro configuration statement (shiro.ini)

 

Create a web project, then create shiro.ini under src

[main]
#The default login interface is /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"]

 

Here are a few to pay attention to:

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

When accessing the path /success, if there is no login, it will automatically jump to the login interface /login.jsp. When accessing the path /login, you can log in.

 

interface

Prepare the login interface and the interface for successful login

 

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 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>登录成功</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);
    }

}

 

 做到这里,基本的web集成就已经完成,但是在实际开发中,我们通常需要配置Realm等其他组件,从数据库中读取用户信息,用户的角色,权限等

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326117382&siteId=291194637