I am trying to set some values in HttpServletRequest object in struts2 action but on JSP page, it is showing it as null.
Code on struts.xml is:
<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>
Action class is:
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;
}
}
Code on JSP Page is:
<%@ 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>
But on JSP Page it is showing as null.
Any idea on this?
You can set an attribute as a class variable in your action class and put a getter for it. In your jsp you can then access it using struts tags.
java code
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" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.