How to set and destroy a session variable in struts2? - struts2

I'm a beginner in Struts2. I am used in PHP, while logging to save authentification in a session variable, which I can destroy after logging out. I wonder how I can do the same process in Struts2 : to set a session variable while logging in and to destroy it while logging out. Thank you a lot.
Update ( An additional solution )
In addition to the useful answers and comments, we can use :
session.remove("session_var_name"); // instead of session.clear();
to remove one exact session variable instead of removing all the session variables. Thank you all.

You can do one of the following
public class MyAction extends ActionSupport implements ServletRequestAware
{
private HttpServletRequest httpServletRequest;
public void setServletRequest(HttpServletRequest request)
{
this.httpServletRequest = request;
}
public String login()
{
httpServletRequest.getSession(false).setAttribute("key", your_session_object);
return SUCCESS;
}
public String logout()
{
httpServletRequest.getSession(false).removeAttribute("key");
return SUCCESS;
}
}
public class MyAction extends ActionSupport implements SessionAware
{
private Map sessionMap;
public void setSession(Map map)
{
this.sessionMap = map;
}
public String login()
{
sessionMap.put(key, your_session_object);
return SUCCESS;
}
public String logout()
{
sessionMap.remove(key);
return SUCCESS;
}
}
The second alternative i.e. implementing SessionAware is preferred since it shields you from Servlet APIs.

You can use Scope Interceptor when you call logout, and with "end" type in your struts xml configuration, Interceptor set null to your session object:
<action name="scopea" class="com.mevipro.test.action.ScopeActionA">
<result name="success" type="dispatcher">/jsp/test.jsp</result>
<interceptor-ref name="basicStack"/>
<interceptor-ref name="scope">
<param name="key">funky</param>
<param name="session">person</param>
<param name="type">start</param>
</interceptor-ref>
</action>
<action name="scopeb" class="com.mevipro.test.action.ScopeActionB">
<result name="success" type="dispatcher">/jsp/test.jsp</result>
<interceptor-ref name="scope">
<param name="key">funky</param>
<param name="session">person</param>
<param name="type">end</param>
</interceptor-ref>
<interceptor-ref name="basicStack"/>
</action>
you must define "start" and "end" the start is when you initialise your object in session and the "end" for destroy your object
For more detail : https://struts.apache.org/docs/scope-interceptor.html

Related

Struts2 return in action cant find another class file

public class Login extends ActionSupport {
//connection made
PreparedStatement pstmt = con.prepareStatement("select * from register1 where username=? and password=?");
pstmt.setString(1, username);
pstmt.setString(2, pwd);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
String role = rs.getString(3);
if (role == null || role.equals("user")) {
session.setAttribute("username", username);
return "Cart"; //here i want to go for another .java file
}
}
Struts.xml
<action name="Login" class="mypack.Login">
<result name="Cart" type="dispatcher">
<param name="location">mypack.CartSelect</param>//Another .java file which support Action Support
</result>
</action>
Class 3:
public class CartSelect extends ActionSupport implements ServletContextAware {
public String execute() throws Exception {
I think what you need is not a dispatcher but instead a redirect.
Here is the reference for redirect action result type.

displaytag not working with struts 2 use tiles

In my application using struts 2 framework and tiles.
Now, I want to use displaytag to display the data in a database table. I did the following:
in my struts.xml:
<action name="users_admin" class="com.controller.admin.UserAction">
<interceptor-ref name="checkSession" />
<result name="login">/login.jsp</result>
<result type="tiles" name="none">/users_admin.tiles</result>
</action>
In file UserAction:
public class UserAction extends ActionSupport{
private List<Users> listUsers;
private String myActionName;
public String getMyActionName() {
return myActionName;
}
public void setMyActionName(String myActionName) {
this.myActionName = myActionName;
}
public List<Users> getListUsers() {
return listUsers;
}
public void setListUsers(List<Users> listUsers) {
this.listUsers = listUsers;
}
#Override
public String execute() throws Exception {
listUsers = UserServices.selectAll();
return NONE;
}
}
And In file user_admin.jsp(file use in tiles):
<s:actionerror cssStyle="color:red"/>
<div class="well">
<display:table name="listUsers" id="listUsers" requestURI="/UserAction" cellpadding="5px;"
cellspacing="5px;" style="margin-left:50px;margin-top:20px;">
<display:column property="EMAIL" title="Email"/>
<display:column property="NAME" title="Name"/>
</display:table>
</div>
File user model:
package com.model;
public class Users {
private String EMAIL;
private String NAME;
public String getEMAIL() {
return EMAIL;
}
public void setEMAIL(String EMAIL) {
this.EMAIL = EMAIL == null ? null : EMAIL.trim();
}
public String getNAME() {
return NAME;
}
public void setNAME(String NAME) {
this.NAME = NAME == null ? null : NAME.trim();
}
}
When I run the application error occurs in apache tomcat log
org.apache.catalina.core.ApplicationDispatcher.invoke Servlet.service() for servlet jsp threw exception
java.lang.ClassNotFoundException: org.apache.commons.collections.IteratorUtils
Who can help me point out why the error, in the solution to overcome it?
Add commons-collections-3.1.jar to your libraries.
Note that you are using only one Interceptor, unless checkSession is the name of your stack.
EDIT
Interceptor checkSession to check my log on the website. How should I use.
You can define a custom interceptor stack, and then reference it, or include your custom interceptor AND another stack (for example, the default one) for a single action, like this:
<action name="users_admin" class="com.controller.admin.UserAction">
<interceptor-ref name="checkSession" />
<interceptor-ref name="defaultStack" />
<result name="login">/login.jsp</result>
<result type="tiles" name="none">/users_admin.tiles</result>
</action>

Struts2 - Annotation for having multiple action methods

Within in same action class, struts2 supports multiple action methods.
One sample of struts.xml - How to convert it to annotation ?
<action name="import"
class="com.action.MainAction" method="importFiles">
<result name="success">main.jsp</result>
<result name="error">error.jsp</result>
</action>
<action name="resourceRowAction"
class="com.action.MainAction" method="resourceRowAction">
<result name="success">main.jsp</result>
<result name="error">erro.jsp</result>
</action>
Annotation solution for above Dynamic Method Invocation can be found here :
http://struts.apache.org/release/2.1.x/docs/convention-plugin.html#ConventionPlugin-Actionannotation
In Action:
#Action(value="default")
#Override
public String execute()
{
return SUCCESS;
}
#Action(value="import")
public String importFiles()
{
return SUCCESS;
}
#Action(value="resourceRowAction")
public String resourceRowAction()
{
return SUCCESS;
}

issue with passing parameter through struts2 <s:url/>

i am calling a struts2 action by passing parameter from a dynamic image url
<img src="<s:url action='ImageAction?imageId=logo.jpg' />"/>
With this my action is calling properly but the parameter imageId=logo.jpg is not passing to my action class.
But if i manully pass parameter from the browser url then, parameter is correctly showing into my java page eg. http://localhost:8080/mypoject/jspHomepage/bookstransaction/secure/ImageAction?imageId=logo.jpg
What could be reason for this?
Please help me.
struts.xml
`
`<package name="Image" extends="struts-default,json-default">
<result-types>
<result-type name="imageResult"
class="v.esoft.actions.changetheme.CustomImageBytesResult" />
</result-types>
<action name="updatethemeimageform" class="v.esoft.actions.changetheme.ThemedetailsEditAction" method="updateThemesImage">
<result name="success" type="json"/>
<result name="input" type="json"/>
</action>
<action name="Display" class="v.esoft.actions.changetheme.DisplayAction">
<result name="success" type="json"/>
</action>
<action name="ImageAction" class="v.esoft.actions.changetheme.ImageAction">
<result name="success" type="imageResult">
</result>
</action>
</package>`
ImageAction.java
public class ImageAction extends ActionSupport implements ServletRequestAware {
byte[] imageInByte = null;
String imageId;
private HttpServletRequest servletRequest;
public String getImageId() {
return imageId;
}
public void setImageId(String imageId) {
this.imageId = imageId;
}
public ImageAction() {
System.out.println("ImageAction");
}
public String execute() {
return SUCCESS;
}
public byte[] getCustomImageInBytes() {
System.out.println("imageId" + imageId);
}
}
Following is untested.
Use param tags to add parameters.
<s:url package="Image" action="ImageAction" var="myUrl">
<s:parm name="imageId" value="'logo.jpg'"/>
</s:url>
<img src="<s:property value="#myUrl"/>"/>
Note: I suspect in the final line myUrl should be sufficient (without the #) but don't remember at the moment.

How can i invoke the "execute" method of an Action redirected from another action in Struts 2?

I've got a problem with redirecting from one action to another in struts 2.
In action one (called: StudentZuPruefungHinzufuegen) i am creating action errors and want to show these in action two (called:ZeigePruefungsliste).
If i just use the "redirectAction" from struts it shows the correct action error at the place i wanted to show it. The problem is that the framework doesn't invoke my "execute" method before showing the resultpage with the action errors. Though the table I am filling within my "execute" method is empty and the resulting page is in fact useless.
Can somebody tell me how I can tell Struts to invoke the method while redirecting to action two?
My struts.xml looks like that:
<action name="ZeigePruefungsliste"
class="de.nak.multiplechoice.action.ZeigePruefungslisteAction">
<interceptor-ref name="store">
<param name="operationMode">RETRIEVE</param>
</interceptor-ref>
<interceptor-ref name="defaultLoginStack" />
<result type="tiles" name="*">pruefungsListe</result>
</action>
<action name="StudentZuPruefungHinzufuegen"
class="de.nak.multiplechoice.action.EditiereTeilnehmerAction">
<result type="tiles">studentZuPruefungHinzufuegen</result>
<interceptor-ref name="store">
<param name="operationMode">STORE</param>
</interceptor-ref>
<interceptor-ref name="defaultLoginStack" />
<result name="input" type="redirectAction">
<param name="actionName">
ZeigePruefungsliste
</param>
</result>
</action>
EDIT:
Code of my action classes.
public class EditiereTeilnehmerAction extends AbstractAction {
private static final long serialVersionUID = 882657701678551299L;
private Long ausgewaehltePruefungId;
private List<Nutzer> studenten;
private List<Long> ausgewaehlteStudenten;
#Override
public String execute() {
if (ausgewaehltePruefungId == null) {
addActionError("Es muss eine Prüfung ausgewählt werden.");
return INPUT;
}
studenten = getNutzerService().ladeAlleStudenten();
return SUCCESS;
}
public String zuPruefungHinzufuegen() {
getPruefungService().registriereStudentenFuerPruefung(ausgewaehltePruefungId, ausgewaehlteStudenten);
return SUCCESS;
}
public List<Nutzer> getStudenten() {
return studenten;
}
public void setStudenten(List<Nutzer> studenten) {
this.studenten = studenten;
}
public Long getAusgewaehltePruefungId() {
return ausgewaehltePruefungId;
}
public void setAusgewaehltePruefungId(Long ausgewaehltePruefungId) {
this.ausgewaehltePruefungId = ausgewaehltePruefungId;
}
public List<Long> getAusgewaehlteStudenten() {
return ausgewaehlteStudenten;
}
public void setAusgewaehlteStudenten(List<Long> ausgewaehlteStudenten) {
this.ausgewaehlteStudenten = ausgewaehlteStudenten;
}
}
public class ZeigePruefungslisteAction extends AbstractAction {
private static final long serialVersionUID = -7559234907568287686L;
private List<Pruefung> pruefungen;
#Override
public String execute() {
pruefungen = getPruefungService().getAllePruefungen(getAktuellenNutzer());
return SUCCESS;
}
public List<Pruefung> getPruefungen() {
return pruefungen;
}
}
public abstract class AbstractAction extends ActionSupport {
private static final long serialVersionUID = -6905222101893534102L;
private INutzerService nutzerService;
private IPruefungService pruefungService;
public HttpSession getHttpSession() {
HttpServletRequest request = (HttpServletRequest) ActionContext
.getContext().get(StrutsStatics.HTTP_REQUEST);
return request.getSession(true);
}
public Nutzer getAktuellenNutzer() {
return nutzerService.get(((Nutzer) getHttpSession().getAttribute(
StrutsKonstanten.NUTZER)).getId());
}
protected INutzerService getNutzerService() {
return nutzerService;
}
public void setNutzerService(INutzerService nutzerService) {
this.nutzerService = nutzerService;
}
protected IPruefungService getPruefungService() {
return pruefungService;
}
public void setPruefungService(IPruefungService pruefungService) {
this.pruefungService = pruefungService;
}
}
Greetings,
Marcus

Resources