Checking a session value in Struts 2 web application [duplicate] - java

This question already has answers here:
Is there a way to redirect to another Action class without using on struts.xml
(2 answers)
Closed 6 years ago.
I am creating a web application using Struts 2. I have a login page in it. As the user click the login button after entering the username and password, the credentials are checked and if the credentials are found correct, then a session is created and its attributes are set and control is redirected to WELCOME JSP.
Now before the welcome.jsp is opened, I want to check, if the session attributes are set. How to do it in Struts 2?
Can anyone clear me the concept of interceptors. I read that we create interceptors to perform any function before or after an action is called. Can I create an interceptor that checks if the session is set, every time before WELCOME JSP is called.

you can use <s:if> tag to test presence of your attribute in Session.I am assuming that you are setting value in your action class and here is how you can do that in jsp page
<s:if test="%{#session.logged_in ==true}">
I am assuming that here i am setting a flag indicating if user is logged in or not on similar way you can test as per your requirements
For Interceptors, They are set of utility classes being provided by Struts2 out of the box to make your life easy.Interceptors are just java classes with certain functionality which is being provide by the framework, some of them are
fileUpload
i18n
params
token etc
These Interceptors are called based on the interceptor stack being configured in your application and they will be called at 2 places
when you send request to your action
when request processing done and view rendered.
in first case they will be called before your action execute or custom method defined by you is called, Interceptors are responsible to provide required data to your action class, some of the work done by interceptors before your action called are
File uploading
Handling i18n
Passing form values to respected fields in your action class
validation of your data
there are certain set of interceptors being provided by struts2 , you can have look at struts-defaultxml.
You can create any number of interceptors and configure them to be executed as per your requirements,a ll you need to extends AbstractInterceptor an provide your custom logic inside intercept(ActionInvocation invocation) method
I suggest you to follow below mentioned links to get more overview
building-your-own-interceptor
Struts2 Interceptors
writing-interceptors

#rickgaurav for your 1st question. make a login action like this
<action name="login_action" class="loginAction class">
<result name="success" type="chain">welcomeAction</result>
<result name="input">/index.jsp</result>
<result name="error">/index.jsp</result>
</action>
wher index.jsp is your login page
and in login interceptor first make a session map in which your session attribute will be store
Map<String, Object> sessionAttributes = invocation
.getInvocationContext().getSession();
after that check using this condition
if (sessionAttributes == null
|| sessionAttributes.get("userName") == null
|| sessionAttributes.get("userName").equals("")) {
return "login";
}else{
if (!((String) sessionAttributes.get("userName")).equals(null)){
return invocation.invoke();
}else{
return "login";
}
for your 2nd question assume you are calling a welcomeAction to go to the welcome.jsp page
so you can add action like this
<action name="welcomeAction" class="class">
<interceptor-ref name="logininterceptor"></interceptor-ref>
<result name="login" type="chain">loginaction</result>
<result name="success" >/welcome.jsp</result>
</action>
hope so this will work for you

In Struts.xml write this:
<interceptors>
<interceptor name="loginInterceptor"
class="com.mtdc.interceptor.LoginInterceptor"></interceptor>
<interceptor-stack name="loginStack">
<interceptor-ref name="loginInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
2.Now After aAction which you want to check session put this: <interceptor-ref name="loginStack"></interceptor-ref>
3.Our LoginACtion in struts.xml: `
<action name="login_action" class="com.action.LoginAction">
<result name="success">/welcome.jsp</result>
<result name="input">/login.jsp</result>
<result name="error">/login.jsp</result>
</action>
`
4.Now define LOgin interceptor for that make com,interceptor.LoginInterceptor :
`
public String intercept(ActionInvocation invocation) throws Exception {
Map<String, Object> sessionAttributes = invocation
.getInvocationContext().getSession();
if (sessionAttributes == null
|| sessionAttributes.get("userName") == null
|| sessionAttributes.get("userName").equals("")) {
return "login";
} else {
if (!((String) sessionAttributes.get("userName")).equals(null)
|| !((String) sessionAttributes.get("userName")).equals("")) {
return invocation.invoke();
} else {
return "login";
}
}
}
`
[5]. Now make Login Action class where you assign session:
`
public String execute() {
String result = LOGIN;
UserLogin userlogin;
try {
userlogin = userlogindao.authenticateUser(signin_username, signin_password);
if (userlogin != null && userlogin.getUsername() != null) {
session.put("userID", userlogin.getUserId());
session.put("userName", userlogin.getUsername());
result = SUCCESS;
} else {
result = LOGIN;
}
} catch (Exception e) {
result = LOGIN;
e.printStackTrace();
}
return result;
}
`
[6]. Now final step on your login page on click call action LoginAction.

Yes you can use interceptor.
Make a Action class Which will store UserId / Username of user (after user is authenticated) in session like this.
session.put("userID", userlogin.getUserId());
after that make a Interceptor class which impl. interceptor
public class LoginInterceptor implements **Interceptor** {
public String intercept(ActionInvocation invocation) throws Exception {
get the session attribute using
sessionAttributes.get("userId");
and check it is not null if it is null then return login to forward user to the login page
or else return invocation.invoke(); to continue the action.
and in struts.xml file configure interceptor inside package
<interceptors>
<interceptor name="loginInterceptor" class=".....LoginInterceptor"></interceptor>
<interceptor-stack name="loginStack">
<interceptor-ref name="loginInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
and for action you can write
<action name="anything" class="anyclass" method="default">
<interceptor-ref name="loginStack"></interceptor-ref>
<result name="login">/index.jsp</result>
<result name="success" type="redirect">success.jsp</result>
</action>

Related

Struts2 one class with 2 result bug?

i use struts 2 , definen 2 results for 1 class to output 2 pages code:
public String init() throws SystemException {
return "index";
}
public String emailVerify() throws SystemException {
return "emailVerify";
}
and on struts xml
<action name="RegisterAction_*" class="com.app.action.RegisterAction" method="{1}">
<result name="index">/WEB-INF/jsp/app/user_register.jsp</result>
<result name="emailVerify">/WEB-INF/jsp/app/user_email_verify.jsp</result>
</action>
init with result "success does work,but the emailVerify only work 1 time , if i reload the page it shows struts error, is this a bug?
fixed, this mvc has a Interceptor blocks non-init request

How to get form data after action chaining in last action

Here i am chaining action then want to get data on last preview action
My First action call first.jsp. I Enter some value here I want to get that value on next Action call
<action name="first">
<result name="success">/first.jsp</result>
</action>
<action name="second" class="com.ved.action.FirstAction">
<result name="success">/second.jsp</result>
</action>
<action name="preview" class="com.ved.action.SecondAction">
<result name="success">/preview.jsp</result>
</action>
I want to display first.jsp data on preview.jsp
first.jsp
<s:form action="second">
<s:textfield name="username" label="UserName"/>
<s:submit name="next" value="Next"/>
</s:form>
second.jsp
<s:form action="preview">
<s:textfield name="address"/>
<s:submit name="priview" value="priview"/>
preview.jsp
<s:property value="username"/>
<s:property value="address"/>
i want display both page data on preview
my Action is as
public class FirstAction extends ActionSupport{
private String firstname;
public String execute() throws Exception {
return SUCCESS;
}
//setter getter for firstname
}
public class SecondAction extends ActionSupport{
private String address;
public String execute() throws Exception {
return SUCCESS;
}
//setter getter for address
}
HTTP is stateless.
Solution:
1) You have to use session to persist the data.
2) During transition from first to second, the data should be in second.jsp. Use html hidden element to store the data of first.jsp. So, you have to restore the data in request scope.

Passing a key value in query string from one page to another in a project using Struts 2

I am trying to pass a key value in query string from one page to another in a project using the Struts 2 framework.
URL Mapping:
<struts>
<package name="default" namespace="/" extends="struts-default">
<!-- Line -->
<action name="line" class="com.example.a.b.action.LineAction">
<result name="success">/line.jsp</result>
</action>
</package>
</struts>
URL For HTML Anchor Link:
http://localhost/line?key=value
When it goes to LineAction I want to get the query string key value part but could find anything online for it.
If I understand you correctly. In your action class create Getters and Setters for key. You will get a value in your action class.
May be You try this way..
try{
URL url = new URL("http://www.google.com?gender=male&name=jagga");
System.out.println(url.getQuery());
}catch(MalformedURLException e)
{
e.printStackTrace();
}
You build your URL of that Action
You can get parameters from the action context like
Map<String, Object> parameters = ActionContext.getContext().getParameters();
But a better way is to implement ParameterAware
private Map<String, String[]> parameters;
public void setParameters(Map<String, String[]> parameters){
this.parameters = parameters;
}

Struts.xml action configuration

If no methods will will be specified for a action , then which method will be called out for that specified class under that action
Override execute method in action class. If no method is provided in action tag of struts.xml file, execute method will be called by default.
Suppose this is your struts action tag. HelloWorld is the action class mentioned. No method is specified. Then execute method will be called in action class.
<action name="add" class="example.HelloWorld">
<result name="SUCCESS" type="redirect">HelloWorld</result>
</action>
This is HelloWorld action class.
public class HelloWorld extends ActionSupport {
#Override
public String execute() {
return SUCCESS;
}
}

Result is null with JSON and Struts2

I have created a simple form in Extjs4.1.
I am sending the request to Struts2 framework, and using the Strtus2JSON plugin, i have to recieve the response. But unfortunately, the response is null.
Action class
public String execute()throws Exception{
Employee emp = new Employee();
emp.setAddress(getAddress());
emp.setDepartment(getDepartment());
emp.setName(getName());
emp.setSalary(getSalary());
AddEmployeeService empService = new AddEmployeeService();
boolean flag = empService.addEmployee(emp);
resultJSONobj = new JSONObject();
if(flag == true)
resultJSONobj.put("success","Inserted Successfully");
else
resultJSONobj.put("failure","An error occured");
System.out.println(resultJSONobj);
return SUCCESS;
}
struts.xml
<struts>
<package name="default" extends="struts-default, json-default">
<action name="AddEmp" class = "actions.AddEmpAction">
<result name = "success" type="json">
<param name ="root">resultJSONobj</param>
</result>
</action>
</package>
</struts>
Can anybody tell why iam getting the response as null ?
Do you have a Getter for resultJSONobj like this?:
public JSONObject getResultJSONobj(){
return this.resultJSONobj;
}
Add a namespace to your package, like this:
<package name="default" namespace="/" extends="struts-default, json-default">
And see if something has changed...
EDIT
As described in the guide,
'transient' fields are not serialized
fields without getter method are not serialized
Try like this:
Use a Map instead of your JSONObject. Not every class is accepted, and I'm not sure your JSONObject is serializable (do you implement serializable? do you declare a serialVersionUID? etc)
private Map resultJSONobj = new HashMap(); //instantiated at class level
// accessors
public Map getResultJSONobj() {
return resultJSONobj;
}
public void setResultJSONobj(Map resultJSONobj) {
this.resultJSONobj = resultJSONobj;
}
//...
public String execute()throws Exception{
Employee emp = new Employee();
emp.setAddress(getAddress());
emp.setDepartment(getDepartment());
emp.setName(getName());
emp.setSalary(getSalary());
AddEmployeeService empService = new AddEmployeeService();
boolean flag = empService.addEmployee(emp);
if(flag == true)
resultJSONobj.put("success","Inserted Successfully");
else
resultJSONobj.put("failure","An error occured");
System.out.println(resultJSONobj);
return SUCCESS;
}
And change struts config like this:
<struts>
<package name="default" extends="struts-default, json-default">
<action name="AddEmp" class = "actions.AddEmpAction">
<result name="success" type="json" />
</action>
</package>
</struts>
Success is not necessary, but leave it for a clearer code, you can always remove it later.
Now, you should see this as result (if you doesn't have any other getter):
{
"resultJSONobj": {
"success":"Inserted Successfully"
}
}
or
{
"resultJSONobj": {
"failure":"An error occured"
}
}
in your configuration file struts.xml, please use
<param name="includeProperties">resultJSONobj.*</param>
Instead of
<param name="includeProperties">resultJSONobj</param>
I was facing the same issue before in my project, after I made the above change it works.
There are few things missing in your struts.xml file. After result is success, where are you going?
Create json object instance outside your execute method and inside action class.
Struts2JSON plugin serializes all action variables inside an action class. It might be that since you have only declared JSONobject in action class and actually creating it inside execute, JSON might be getting it {}.
Put
private JSONObject resultJSONobj = new JSONObject();
inside action class and outside execute and see, it might work.
For more information you can go here
http://struts.apache.org/2.2.3/docs/json-plugin.html

Categories