如何在struts2动作中创建HttpServletRequest对象

时间:2014-10-29 12:12:05

标签: java jsp struts2

我试图在struts2动作中的HttpServletRequest对象中设置一些值,但在JSP页面上,它显示为null。

struts.xml上的代码是:

<action name="login" method="execute" class="com.ui.LoginAction">
    <result name="success">/tc/login.jsp</result>
    <result name="error">/tc/session_timeout.jsp</result>
 </action>

行动类是:

package com.ui;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;


public class LoginAction extends ActionSupport implements ServletRequestAware{

private String username;
private String password;

HttpServletRequest request;

public String execute() {
    try
    {

        request.setAttribute("demo", "value Stored in Request....");

        return "success"; 
    }
    catch (Exception e)
    {
        Logger.getLogger(Constants.LOG_NAME).error("Error with action!",e);
        return "error";
    }
}

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

public HttpServletRequest getServletRequest() {
    return this.request;
}


public String getJ_password()
{
   return this.password;
}

public String getJ_username()
{
   return this.username;
}

public void setJ_password(String string)
{
   this.password = string;
}

public void setJ_username(String string)
{
   this.username = string;
}

}

JSP页面上的代码是:

<%@ page contentType="text/html; charset=UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome Page - Struts 2 - Login Application</title>
</head>

<body>
    Login Page...<br>
    <%= request.getAttribute("demo") %>
</body>
</html>

但是在JSP页面上它显示为null。

对此有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以在动作类中将属性设置为类变量,并为其添加一个getter。在你的jsp中,你可以使用struts标签访问它。

java代码

public class LoginAction extends ActionSupport implements ServletRequestAware{
  private String demo;

  public String getDemo(){return this.demo;}

  public String execute() {
    try
    {
        //request.setAttribute("demo", "value Stored in Request....");
        this.demo = "value stored in request";
        return "success"; 
    }
    catch (Exception e)
    {
        Logger.getLogger(Constants.LOG_NAME).error("Error with action!",e);
        return "error";
    }
  }
}

JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<s:property value="demo" />