Struts2(4)之Servlet API的访问

Struts2(4)之Servlet API的访问

微信搜索 zze_coding 或扫描 👉 二维码关注我的微信公众号获取更多资源推送:

准备

为后面测试示例编写代码及配置如下:

// com.zze.bean.User
package com.zze.bean;

import java.util.Date;

public class User {
    private String name;
    private Integer age;
    private Date birthday;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }
}
<!-- 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"/>
    <package name="test" extends="struts-default" namespace="/">
        <action name="*" class="com.zze.action.{1}Action">
            <result>/show.jsp</result>
        </action>
    </package>
</struts>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>v1:${requestScope.key}
v2:${sessionScope.key}
v3:${applicationScope.key}

Servlet API 的三种访问方式

在使用 Struts2 的过程中,会发现 Struts2 和 Servlet 的 API 是松耦合的。但在实际开发中,经常用到 Servlet 的 API,比如将信息保存到 session 中、使用 response 响应一些内容等等..,这些都涉及到对 Servlet 的 API 的访问。下面为三种方式使用的示例:

松耦合方式

// com.zze.action.Test1Action
package com.zze.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import java.util.Arrays;
import java.util.Map;

public class Test1Action extends ActionSupport {

    /**
     * 解耦合方式
     */
    @Override
    public String execute() {
        ActionContext context = ActionContext.getContext();
        // 获取请求参数
        Map<String, Object> parameters = context.getParameters();
        for (String key : parameters.keySet()) {
            String[] values = (String[]) parameters.get(key);
            System.out.println(String.format("key:%s value:%s", key, Arrays.toString(values)));
        }
        // 存放参数到域对象
        context.put("key", "value from context.put"); // request.setAttribute("key","value from context.put")
        context.getSession().put("key", "value from context.getSession().put"); // session.setAttribute("key","value from context.getSession().put")
        context.getApplication().put("key", "value from context.getApplication().put"); // application.setAttribute("key","value from context.getApplication().put")
        return SUCCESS;
    }
}

image.png

image.png

使用 ServletActionContext 直接访问

// com.zze.action.Test2Action
package com.zze.action;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

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

public class Test2Action extends ActionSupport {

    @Override
    public String execute() throws Exception {
        // 获取原生 request 对象
        HttpServletRequest request = ServletActionContext.getRequest();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key : parameterMap.keySet()) {
            String[] values = (String[]) parameterMap.get(key);
            System.out.println(String.format("key:%s value:%s", key, Arrays.toString(values)));
        }
        // 存放数据到域对象
        request.setAttribute("key","value from request.setAttribute");
        request.getSession().setAttribute("key","value from request.getSession().setAttribute");
        // ServletActionContext.getServletContext()
        request.getServletContext().setAttribute("key","value from request.getServletContext().setAttribute");
        return super.execute();
    }
}

image.png

image.png

接口注入的方式

// com.zze.action.Test3Action
package com.zze.action;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;

/**
 * 接口注入的方式需要实现相应接口
 */
public class Test3Action extends ActionSupport implements ServletRequestAware, ServletResponseAware, ServletContextAware {
    private HttpServletRequest request;  // 接收注入的原生 request
    private HttpServletResponse response; // 接收注入的原生 response
    private ServletContext servletContext; // 接收注入的原生 servletContext

    @Override
    public String execute() throws Exception {
        // 接收请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key : parameterMap.keySet()) {
            String[] values = (String[]) parameterMap.get(key);
            System.out.println(String.format("key:%s value:%s", key, Arrays.toString(values)));
        }
        // 存放数据到域对象
        request.setAttribute("key", "value from request.setAttribute");
        request.getSession().setAttribute("key", "value from request.getSession().setAttribute");
        servletContext.setAttribute("key", "value from servletContext.setAttribute");
        return super.execute();
    }

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

    @Override
    public void setServletResponse(HttpServletResponse response) {
        this.response = response;
    }

    @Override
    public void setServletContext(ServletContext context) {
        this.servletContext = context;
    }
}

image.png

image.png

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://www.zze.xyz/archives/struts2-4.html

Buy me a cup of coffee ☕.