Struts2框架之在动作类中访问Servlet API

版权声明:本文为博主原创文章,遵循 CC 4.0 BY 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_41855420/article/details/102648782

Struts2框架将Servlet进行了封装,但是有时候我们又希望获取request、response、session等对象,因为有些数据需要使用这些域对象进行前后端的传递。下面将介绍动作类中访问Servlet API的两种方式。

方式一:通过ServletActionContext获取 【推荐使用】

Demo结构:
在这里插入图片描述
LoginAction.java文件

package cn.hestyle.web.action;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginAction extends ActionSupport {
    //方法必须是public,并且返回值为String类型,参数表列为空
    public String login() throws IOException {
    	//通过ServletActionContext获取request、response
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();

        //request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        System.out.println("username:" + username + "\tpassword:" + password);
        //为了方便演示,所以随意写了一个模拟过程,千万别学这种方式啊
        if (!"hestyle".equals(username) || !"123456".equals(password)) {
            request.setAttribute("msg", "用户名或密码错误!");
            return "error";
        } else {
            request.setAttribute("msg", "登陆成功!");
            return "success";
        }
    }
}

struts.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
    <package name="p1" extends="struts-default">
        <action name="login" class="cn.hestyle.web.action.LoginAction" method="login">
            <!-- 根据action的返回值,转发到不同的界面 -->
            <result name="error">/index.jsp</result>
            <result name="success">/success.jsp</result>
        </action>
    </package>
</struts>

web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

index.jsp文件

<%--
  Created by IntelliJ IDEA.
  User: hestyle
  Date: 2019/10/20
  Time: 2:35 下午
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户登录</title>
</head>
<body>
    <span>${msg}</span>
    <form action="login.action" method="post">
        <table border="1px">
            <tr>
                <td>用户名</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input type="password" name="password"></td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit"></td>
            </tr>
        </table>
    </form>
</body>
</html>

success.jsp文件

<%--
  Created by IntelliJ IDEA.
  User: hestyle
  Date: 2019/10/20
  Time: 2:35 下午
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录成功</title>
</head>
<body>
    <span>${msg}</span>
</body>
</html>

浏览器访问结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述在这里插入图片描述

方式二:通过注入方式

先让Action实现两个接口ServletRequestAware,ServletResponseAware
Demo01Action.java文件

package cn.hestyle.web.action;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class Demo01Action extends ActionSupport implements ServletRequestAware, ServletResponseAware {
    private HttpServletRequest request;
    private HttpServletResponse response;

    //方法必须是public,并且返回值为String类型,参数表列为空
    public String sayHello() throws IOException {
        System.out.println(request);
        System.out.println(response);
        return "success";
    }

    //通过实现ServletRequestAware、ServletResponseAware进行注入
    @Override
    public void setServletRequest(HttpServletRequest httpServletRequest) {
        request = httpServletRequest;
    }

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

struts.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
    <package name="p1" extends="struts-default">
        <action name="action1" class="cn.hestyle.web.action.Demo01Action" method="sayHello">
            <result name="success">/success.jsp</result>
        </action>
    </package>
</struts>

浏览器访问:
在这里插入图片描述
在这里插入图片描述

原理:

在struts-default.xml配置文件中有一个拦截器ServletConfigIntercepto。
在这里插入图片描述
ServletConfigIntercepto.java的源码如下:
在这里插入图片描述
如图可以看出还可以通过注入获得HttpParametersApplicationSession等对象。

猜你喜欢

转载自blog.csdn.net/qq_41855420/article/details/102648782