Struts2 - Check Login Interceptor

Struts2使用Interceptor做用户登陆检查:

1)新增一个bean: User.java

package com.my.beans;

import java.util.Date;

import org.apache.struts2.json.annotations.JSON;

public class User {
    
    private int userId;
    private String username;
    private String password;
    private int age;
    private Date createTime;
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    
    public User(int userId, String username, String password, int age,
            Date createTime) {
        this.userId = userId;
        this.username = username;
        this.password = password;
        this.age = age;
        this.createTime = createTime;
    }
    
    public User() {
    }
    
}

 

2)新增一个:CheckLoginInterceptor.java

package com.my.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.my.beans.User;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

@SuppressWarnings("serial")
public class CheckLoginInterceptor extends AbstractInterceptor {

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        // invocation invoke result
        String result = null;

        // get invocation proxy
        ActionProxy ap = invocation.getProxy();
        if (ap.getNamespace().equals("/")
                && ap.getActionName().equals("login")
                && (ap.getMethod().equals("execute") || ap.getMethod().equals("signin"))) {
            result = invocation.invoke();
        } else {
            // check user already login
            HttpSession session = ServletActionContext.getRequest().getSession();
            Object userObject = session.getAttribute("USER");
            User user = (User) userObject;
            if (null != user) {
                result = invocation.invoke();
            } else {
                HttpServletResponse response = ServletActionContext.getResponse();
                HttpServletRequest request = ServletActionContext.getRequest();
                // get query string
                String strQueryString = (String) request.getQueryString() != null ? "?" + request.getQueryString() : "";
                // redirect URL
                response.sendRedirect(request.getContextPath() + "/login?path="
                        + java.net.URLEncoder.encode(request.getRequestURI() + strQueryString, "UTF-8"));
            }
        }

        // return action
        return result;
    }
}

 

3) 新建一个LoginController.java

package com.my.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.my.beans.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class LoginController extends ActionSupport {

    private String path;
    private User user;

    public synchronized User getUser() {
        return user;
    }

    public synchronized void setUser(User user) {
        this.user = user;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    @Override
    public String execute() throws Exception {
        return SUCCESS;
    }

    public String signin() throws IOException {
        if (user != null) {
            // check user name and password
            if (user.getUsername().equals("admin") && user.getPassword().equals("admin")) {
                HttpSession session = ServletActionContext.getRequest().getSession();
                session.setAttribute("USER", user);
                HttpServletResponse response = ServletActionContext.getResponse();
                response.sendRedirect(getPath());
            }
        }
        return SUCCESS;
    }

}

 

4)新增一个: login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
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>Insert title heretitle>
head>
<body>
    <s:form action="login!signin">
        User name:<s:textfield name="user.username">s:textfield><br/>
        password:<s:password name="user.password">s:password><br/>
        <s:hidden name="path">s:hidden>
        <s:submit value="Login">s:submit>
    s:form>
body>
html>

 

5)加入struts.xml

xml version="1.0" encoding="UTF-8"?>
DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    
    <constant name="struts.devMode" value="true" />
    
    <constant name="struts.convention.classes.reload" value="true"/>
    
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    
    <constant name="struts.convention.result.path" value="/WEB-INF/content/" />
    
    
    <constant name="struts.convention.action.packages" value="com.my.controller">constant>
    
    <constant name="struts.convention.action.suffix" value="Controller"/>
    
    <constant name="struts.convention.action.mapAllMatches" value="true"/>
    
    <constant name="struts.convention.action.name.separator" value="-" />
    
    <constant name="struts.custom.i18n.resources" value="i18n" />
    
    <constant name="struts.i18n.reload" value="true" />
    
    <constant name="struts.serve.static.browserCache" value="false" />
     
    <constant name="struts.multipart.maxSize" value="-1" />
    
    <constant name="struts.ui.theme" value="simple" />
    
    <constant name="struts.i18n.encoding" value="UTF-8" />
    
    <constant name="struts.convention.default.parent.package" value="default">constant>

    <package name="default" namespace="/" extends="json-default">
        <interceptors>
            <interceptor name="cacheInterceptor" class="com.my.interceptor.CacheInterceptor" />
            <interceptor name="loginInterceptor" class="com.my.interceptor.CheckLoginInterceptor" />
            <interceptor-stack name="cacheStack">
                <interceptor-ref name="defaultStack">interceptor-ref>
                <interceptor-ref name="paramsPrepareParamsStack">interceptor-ref>
                <interceptor-ref name="cacheInterceptor">interceptor-ref>
                <interceptor-ref name="loginInterceptor">interceptor-ref>
            interceptor-stack>
        interceptors>
        <default-interceptor-ref name="cacheStack">default-interceptor-ref>
        <default-action-ref name="index" />
        <global-results>
            
            <result name="json" type="json">
                
                
                
                
            result>
        global-results>
        <global-exception-mappings>
            <exception-mapping exception="java.lang.Exception" result="error"/>
        global-exception-mappings>
    package>

struts>

 

关键点在于:

 

使用此方法可以对所有的action进行监控。

如果使用web.xml的filter做监控的话,那将会对所有的资源都会监控,比如jsp、css、js等。使用Interceptor只对action做监控即可。

转载于:https://www.cnblogs.com/HD/p/3678665.html

你可能感兴趣的:(Struts2 - Check Login Interceptor)