![](/img/trans.png)
[英]Why am i not getting initialize HttpServletRequest object in Struts2 Action?
[英]How to create HttpServletRequest object in struts2 action
我試圖在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。
有什么想法嗎?
您可以在操作類中將屬性設置為類變量,然后為其添加吸氣劑。 然后,您可以在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" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.