分享知识-快乐自己:Struts2中 获取 Request和Session

目录结构:

POM:

   <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>

        <!--测试JAR-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
        <!--javaee.jar包是支持javaweb编程的基础jar包,跟javase编程需要jre一样!-->
        <dependency>
            <groupId>javaee</groupId>
            <artifactId>javaee-api</artifactId>
            <version>5</version>
        </dependency>
        <!--Struts2-core核心-->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.3.4.1</version>
        </dependency>
        <!--xwork 的核心包,最主要的功能是 支持了过滤器(interceptor)。-->
        <dependency>
            <groupId>org.apache.struts.xwork</groupId>
            <artifactId>xwork-core</artifactId>
            <version>2.3.4.1</version>
        </dependency>
        
    </dependencies>

RequestActionContext:

package com.gdbd.action;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 获取 request 三种方式
 * 1):ActionContext.getContext().get("request")
 * 2):ServletActionContext.getRequest()
 * 3):实现 ServletRequestAware 接口
 * 推荐使用 实现 ServletRequestAware 接口方式通过IOC机制注入request对象
 *
 * @author asus
 */
public class RequestActionContext implements Action, ServletRequestAware {

    private HttpServletRequest request;

    /***
     * 默认执行的方法
     * @return
     * @throws Exception
     */
    @Override
    public String execute() throws Exception {
        return "success";
    }

    public String getRequest1() {
        Map request = (Map) ActionContext.getContext().get("request");
        request.put("message", "获取 request方式一:ActionContext.getContext().get(\"request\");");
        return "success";
    }

    public String getRequest2() {
        HttpServletRequest request = ServletActionContext.getRequest();
        request.setAttribute("message", "获取 request方式二:ServletActionContext.getRequest();");
        return "success";
    }

    public String getRequest3() {
        request.setAttribute("message", "获取 request方式三:实现 ServletRequestAware 接口;");
        return "success";
    }

    @Override
    public void setServletRequest(HttpServletRequest httpServletRequest) {
        this.request = httpServletRequest;
    }
}

Session_ActionContext_SessionAware:

package com.gdbd.action;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.interceptor.SessionAware;

import java.util.Map;

/**
 * 获取 Session 两种解耦方式
 * 1):ActionContext.getContext().getSession()
 * 2):实现 SessionAway 接口
 *
 * @author asus
 */
public class Session_ActionContext_SessionAware implements Action,SessionAware {

    private Map<String, Object> map;

    /***
     * 默认执行的方法
     * @return
     * @throws Exception
     */
    @Override
    public String execute() throws Exception {
        return "success";
    }

    public String getSession() {
        //解耦方式实现
        Map<String, Object> session = ActionContext.getContext().getSession();
        session.put("message", "解耦方式一:ActionContext.getContext().getSession();");
        return "success";
    }

    public String getSession1() {
        map.put("message", "解耦方式二:实现 SessionAway 接口;");
        return "success";
    }

    @Override
    public void setSession(Map<String, Object> map) {
        this.map = map;
    }
}

Session_ServletActionContext_SessionRequestAware:

package com.gdbd.action;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 获取 Session 两种耦合方式
 * 1):ActionContext.getContext().getSession()
 * 2):实现 SessionAway 接口
 *
 * @author asus
 */
public class Session_ServletActionContext_SessionRequestAware implements Action,ServletRequestAware {

    private HttpServletRequest request;

    /***
     * 默认执行的方法
     * @return
     * @throws Exception
     */
    @Override
    public String execute() throws Exception {
        return "success";
    }

    /***
     * 耦合方式实现1
     * @return
     */
    public String getSession1() {
        HttpSession session = ServletActionContext.getRequest().getSession();
        session.setAttribute("message", "ServletActionContext.getRequest().getSession()");
        return "success";
    }
    /***
     * 耦合方式实现2
     * @return
     */
    public String getSession2() {
        HttpSession session = request.getSession();
        session.setAttribute("message", "耦合方式二:实现ServletRequestAware接口;");
        return "success";
    }
    @Override
    public void setServletRequest(HttpServletRequest httpServletRequest) {
        this.request=httpServletRequest;
    }
}

struts.xml:

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

    <package name="default" namespace="/" extends="struts-default">

        <!--获取Session 解耦两种方式-->
        <action name="Session" class="com.gdbd.action.Session_ActionContext_SessionAware">
            <result name="success">/main.jsp</result>
        </action>
        <!--获取Session 耦合两种方式-->
        <action name="OSession" class="com.gdbd.action.Session_ServletActionContext_SessionRequestAware">
            <result name="success">/main.jsp</result>
        </action>
        <!--获取request 三种方式-->
        <action name="Request" class="com.gdbd.action.RequestActionContext">
            <result name="success">/main.jsp</result>
        </action>

    </package>

</struts>

index.jsp:

<%@ taglib prefix="s" uri="/struts-tags" %>
<%--
  Created by IntelliJ IDEA.
  User: asus
  Date: 2018/11/13
  Time: 12:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>第一天第一次测试</title>
</head>
<body>
<fieldset>
    <legend>获取Session 解耦方式一</legend>
    <a href="/Session!getSession">ActionContext.getContext().getSession();</a>
</fieldset>
<br/>
<fieldset>
    <legend>获取Session 解耦方式二</legend>
    <a href="/Session!getSession1">实现 SessionAway 接口;</a>
</fieldset>
<br/><br/>
<fieldset>
    <legend>获取Session 耦合方式一</legend>
    <a href="/OSession!getSession1">ServletActionContext.getRequest().getSession();</a>
</fieldset>
<br/>
<fieldset>
    <legend>获取Session 耦合方式二</legend>
    <a href="/OSession!getSession2">实现ServletRequestAware 接口;</a>
</fieldset>
<br/><br/>
<hr/>
<br/><br/>
<fieldset>
    <legend>获取Request 三种方式</legend>
    <a href="/Request!getRequest1">获取 request方式一:ActionContext.getContext().get("request");</a>
    &nbsp; &nbsp; &nbsp; &nbsp;
    <a href="/Request!getRequest2">获取 request方式二:ServletActionContext.getRequest();</a>
    &nbsp; &nbsp; &nbsp; &nbsp;
    <a href="/Request!getRequest3">获取 request方式三:实现 ServletRequestAware 接口;</a>
    <p style="color: red">
        推荐使用 实现 ServletRequestAware 接口方式通过IOC机制注入request对象
        <br/>
        该方法必须要实现,而且该方法是自动被调用这个方法在被调用的过程中,会将创建好的request对象通过参数的方式传递给你,你可以用来赋给你本类中的变量,然后request就可以使用了
        <br/>
        注意:
        <br/>
        setServletRequest()方法一定会再execute()方法被调用前执行在jsp页面中获取其中的值
        <br/>
        在上面的代码中,在Action实现了一个ServletRequestAware接口,并且实现了setServletRequest方法。
        <br/>
        如果一个动作类实现了ServletRequestAware接口,Struts2在调用execute方法之前,就会先调用setServletRequest方法,并将Request参数传入这个方法。
        <br/>
        如果想获得HttpServletResponse、HttpSession和Cookie等对象,动作类可以分别实现ServletResponseAware、SessionAware和CookiesAware等接口。这些接口都在org.apache.struts2.interceptor包中。
    </p>
</fieldset>
</body>
</html>

main.jsp:

<%@ taglib prefix="s" uri="/struts-tags" %>
<%--
  Created by IntelliJ IDEA.
  User: asus
  Date: 2018/11/13
  Time: 12:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>第一天第一次测试</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>

web.xml:

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>

    <display-name>Archetype Created Web Application</display-name>
    <!--核心过滤器-->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

源码下载:https://github.com/MlqBeginner/BlogGardenWarehouse/blob/master/StrutsDay02.rar

--欢迎评论:若有不足之处多多指教

Face your past without regret. Handle your present with confidence.Prepare for future without fear. keep the faith and drop the fear.

面对过去无怨无悔,把握现在充满信心,备战未来无所畏惧。保持信念,克服恐惧!一点一滴的积累,一点一滴的沉淀,学技术需要不断的积淀!

 

posted @ 2018-11-15 16:30  GDBD  阅读(279)  评论(0编辑  收藏  举报