Author Login
Post Reply
user Digest 20 Jul 2009 14:13:49 -0000 Issue 8761
Topics (messages 200890 through 200912):
Login mechanism - preserve Action parameters
200890 by: mathias-ewald
200891 by: Dave Newton
200892 by: mathias-ewald
Re: Struts w/Ajax with Struts again
200893 by: cpanon
200898 by: Pawe³ Wielgus
200903 by: cpanon
200905 by: Pawe³ Wielgus
Re: unit testing Struts2 application (with Spring and Hibernate)
200894 by: Pawe³ Wielgus
200895 by: Dave Newton
200896 by: Dimitrios Christodoulakis
200897 by: Wes Wannemacher
How to have a gridview like control in Struts 1.2
200899 by: lplpp
Problem with LoginInterceptor
200900 by: mathias-ewald
200902 by: Nils-Helge Garli Hegvik
200904 by: mathias-ewald
200906 by: Dave Newton
200910 by: mathias-ewald
200912 by: mailtolouis2020-struts.yahoo.com
Prevent persisting data when validation fails
200901 by: taltun
200907 by: Jim Kiley
200909 by: taltun
200911 by: Greg Lindholm
Re: null and zero issue
200908 by: Russo, Joe
Administrivia:
---------------------------------------------------------------------
To post to the list, e-mail: user@(protected)
To unsubscribe, e-mail: user-digest-unsubscribe@(protected)
For additional commands, e-mail: user-digest-help@(protected)
----------------------------------------------------------------------

Attachment:
user_200890.ezm (zipped)
Hi,
a few days ago I implemented a login mechanism into my web application.
Therefore I use an abstract BaseAction, that asks the implementing class
wheter it want to be password protected or not. If it does and there's no
object named "user" available the Login.jsp is shown. When the Login form
returns the user object is placed into session scope.
The Problem is, that after the Login.jsp has returned to the BaseAction all
parameters that were passed to the implementing Action are lost.
What can I do?
Here' my code:
BaseAction.java
-------------------------------------------------------------------------------
public abstract class BaseAction {
public static final Integer ALLOWED = 0;
public static final Integer DENIED = 1;
public static final Integer DENIED_GROUP = 2;
private String logout = "false";
private String username;
private String password;
protected Log log;
public BaseAction() {}
public String execute() {
if(log == null) {
log = LogFactory.getLog(getClass());
}
Map<String, Object> session = ActionContext.getContext().getSession();
/*
* if the user wants to logout, delete the object
* from session scope.
*/
if("true".equals(logout)) {
Object userObj = session.get("user");
if(userObj != null) {
session.put("user", null);
log.info("User " + ((UserAccount)userObj).getName() + " logged out.");
}
}
/*
* in case the username and password values are set, perform
* the login process.
*/
if (username != null && password != null) {
Session s = HibernateUtil.getSessionFactory().openSession();
Transaction tx = s.beginTransaction();
UserAccount user = (UserAccount)s.createCriteria(UserAccount.class)
.add(Restrictions.eq("name", username))
.uniqueResult();
tx.commit();
s.close();
if(user == null) {
log.info("Error authenticating user " + username);
return "loginError";
}
String dbHash = user.getPasswordhash().toLowerCase();
String formHash = MD5Util.md5(password).toLowerCase();
if(dbHash.equals(formHash)) {
session.put("user", user);
log.info("User " + user.getName() + " logged in.");
} else {
log.info("Password mismatch for user " + username);
return "loginError";
}
}
/*
* If we get this far, userObject is either successfully logged
* in or null, so get the UserAccount object or set it null.
*/
Object userObject = session.get("user");
UserAccount user = null;
if(userObject != null && userObject instanceof UserAccount) {
user = (UserAccount)userObject;
}
/*
* Now ask the "real" action if access is allowed.
*/
int retVal = isAllowed(user);
if(retVal == ALLOWED) {
return executeAction();
} else if(retVal == DENIED_GROUP) {
return "permissionError";
} else {
return "login";
}
}
public abstract String executeAction();
public abstract Integer isAllowed(UserAccount user);
// getter and setter methods
}
-------------------------------------------------------------------------------
Login.jsp
-------------------------------------------------------------------------------
<html>
<head>
<jsp:include page="/common/Head.jsp"/>
</head>
<body>
<div id="container">
<jsp:include page="/common/Header.jsp"/>
<div id="navi">
Main > Login
</div>
<div id="body">
<br><br><br><br><br>
<div style="width: 40%; margin: 0 auto;">
This page is protected! Please login:
<br><br>
<s:form method="post">
<s:textfield label="Username" name="username"></s:textfield>
<s:password label="Password" name="password"></s:password>
<s:submit></s:submit>
</s:form>
</div>
</div>
<jsp:include page="/common/Footer.jsp"/>
</div>
</body>
</html>
-------------------------------------------------------------------------------
Is there any chance to have the parameters preserved?
cu
mathias
--
Sent from the Struts - User mailing list archive at Nabble.com.

Attachment:
user_200891.ezm (zipped)Have you considered using an interceptor for determining whether or not
the user is logged in? Actions requiring login can be marked with an
interface, annotation, etc. IMO this is a substantially cleaner
architecture.
I'd also *strongly* discourage tying your actions to Hibernate like
this; it makes testing more difficult than necessary and introduces an
unnecessary level of coupling.
All that said, I'm not really sure which parameters aren't being
preserved--are you doing a redirect?
Dave
mathias-ewald wrote:
> Hi,
>
> a few days ago I implemented a login mechanism into my web application.
> Therefore I use an abstract BaseAction, that asks the implementing class
> wheter it want to be password protected or not. If it does and there's no
> object named "user" available the Login.jsp is shown. When the Login form
> returns the user object is placed into session scope.
>
> The Problem is, that after the Login.jsp has returned to the BaseAction all
> parameters that were passed to the implementing Action are lost.
>
> What can I do?
>
> Here' my code:
>
> BaseAction.java
> -------------------------------------------------------------------------------
> public abstract class BaseAction {
>
> public static final Integer ALLOWED = 0;
>
> public static final Integer DENIED = 1;
>
> public static final Integer DENIED_GROUP = 2;
>
>
> private String logout = "false";
>
> private String username;
>
> private String password;
>
> protected Log log;
>
>
> public BaseAction() {}
>
>
> public String execute() {
> if(log == null) {
> log = LogFactory.getLog(getClass());
> }
>
> Map<String, Object> session = ActionContext.getContext().getSession();
>
> /*
> * if the user wants to logout, delete the object
> * from session scope.
> */
> if("true".equals(logout)) {
> Object userObj = session.get("user");
> if(userObj != null) {
> session.put("user", null);
> log.info("User " + ((UserAccount)userObj).getName() + " logged out.");
> }
> }
>
> /*
> * in case the username and password values are set, perform
> * the login process.
> */
> if (username != null && password != null) {
> Session s = HibernateUtil.getSessionFactory().openSession();
> Transaction tx = s.beginTransaction();
>
> UserAccount user = (UserAccount)s.createCriteria(UserAccount.class)
> .add(Restrictions.eq("name", username))
> .uniqueResult();
>
> tx.commit();
> s.close();
>
> if(user == null) {
> log.info("Error authenticating user " + username);
> return "loginError";
> }
>
> String dbHash = user.getPasswordhash().toLowerCase();
> String formHash = MD5Util.md5(password).toLowerCase();
>
> if(dbHash.equals(formHash)) {
> session.put("user", user);
> log.info("User " + user.getName() + " logged in.");
> } else {
> log.info("Password mismatch for user " + username);
> return "loginError";
> }
> }
>
> /*
> * If we get this far, userObject is either successfully logged
> * in or null, so get the UserAccount object or set it null.
> */
> Object userObject = session.get("user");
> UserAccount user = null;
> if(userObject != null && userObject instanceof UserAccount) {
> user = (UserAccount)userObject;
> }
>
> /*
> * Now ask the "real" action if access is allowed.
> */
> int retVal = isAllowed(user);
> if(retVal == ALLOWED) {
> return executeAction();
> } else if(retVal == DENIED_GROUP) {
> return "permissionError";
> } else {
> return "login";
> }
> }
>
> public abstract String executeAction();
>
> public abstract Integer isAllowed(UserAccount user);
>
> // getter and setter methods
>
> }
> -------------------------------------------------------------------------------
>
> Login.jsp
> -------------------------------------------------------------------------------
> <html>
> <head>
> <jsp:include page="/common/Head.jsp"/>
> </head>
> <body>
>
> <div id="container">
> <jsp:include page="/common/Header.jsp"/>
>
> <div id="navi">
> Main > Login
> </div>
>
> <div id="body">
> <br><br><br><br><br>
> <div style="width: 40%; margin: 0 auto;">
> This page is protected! Please login:
> <br><br>
> <s:form method="post">
> <s:textfield label="Username" name="username"></s:textfield>
> <s:password label="Password" name="password"></s:password>
> <s:submit></s:submit>
> </s:form>
> </div>
> </div>
>
> <jsp:include page="/common/Footer.jsp"/>
> </div>
>
> </body>
> </html>
> -------------------------------------------------------------------------------
>
> Is there any chance to have the parameters preserved?
>
>
> cu
> mathias

Attachment:
user_200892.ezm (zipped)
Hi,
newton.dave wrote:
>
> Have you considered using an interceptor for determining whether or not
> the user is logged in? Actions requiring login can be marked with an
> interface, annotation, etc. IMO this is a substantially cleaner
> architecture.
>
Okay - I didn't really care about interceptors yet. Maybe its time to do
that now.
newton.dave wrote:
>
> I'd also *strongly* discourage tying your actions to Hibernate like
> this; it makes testing more difficult than necessary and introduces an
> unnecessary level of coupling.
>
What do you suggest? Abstracting Hibernate from the Actions placing a data
access object in between? This is a university project I have to finish
untill 22nd July - I am definitly not going to do any testing ;)
newton.dave wrote:
>
> All that said, I'm not really sure which parameters aren't being
> preserved--are you doing a redirect?
>
One Action, for example, receives a parameter with the URL. The BaseAction
the shows the Login and returns to the same Action. After that the parameter
is gone.
cu
mathias
--
Sent from the Struts - User mailing list archive at Nabble.com.

Attachment:
user_200893.ezm (zipped)Hi Nils & Martin
Thanks and I am sorry about being obtuse and I hope you will continue to make this an edifying moment for me.
When I initially put up the form I code a value in the actionForm, myFormBean as myFormBean.setSeeMe("firstTime") and put into the session with session.setAttribute("fb00", myFormBean) I display this value on the form page within a html:text with ...value="${sessionScope.fb00.seeMe}, and it shows "firstTime" on the form. Good. I process the Ajax call in another Action, fed with the same class of actionForm. No matter whether I remove the action form session.removeAttirbute("fb00") or if I set it a different value, myFormBean2.setSeeMe("fromAjax");session.setAttribute("fb00",myFormBean2). I still see "firstTime".
I am looking for the simplest technique that would reprocess the session objects from the new values, regenerate the full jsp, ancilliary to the json object I am setting, in the action processing the Ajax. Specifically I am using the iterate tags to display a series of records and that is what I want to be reprocessed and redrawn to the user with the new values that will be in the session object set in the Ajax processing action.
I understand that actions should/must be thread-safe, I just want to reprocess objects that are unique to state maintained by the session object. I am suspecting this is not possible.
--- On Sun, 7/19/09, Nils-Helge Garli Hegvik <nilsga@(protected):
From: Nils-Helge Garli Hegvik <nilsga@(protected)>
Subject: Re: Struts w/Ajax with Struts again
To: "Struts Users Mailing List" <user@(protected)>
Date: Sunday, July 19, 2009, 9:56 AM
The form will not be updated unless you refresh the values or the part
of the page that displays the values you want to be updated. So you
would have to "manually" do this processing some returned updated
values in a json result, or by returning the result of a "partial" jsp
which re-renders the part of the page that you want to be updated, and
then replace the existing html (using innerHTML).
Nils-H
On Sat, Jul 18, 2009 at 3:45 AM, cpanon<cpanon@(protected):
> Hello
> I am able to use an Ajax call to a struts action and with getInputForward() get the get the data back. (With prototpye and json, very, very elegant). I am now realizing that I have cases where I want to reprocess all components, i.e. I want the actionForm to be updated and the jsp recalculated, I want the session objects to be reprocessed so my iterate tags will show the updates, etc. I understand how with getInputForward it doesnt happen. If I setAttribute(), the original value that was processed when the form first generated is all that ever shows. A simple findForward() does not force the reprocessing,ie still the original values of the actionsForm members. Is there a way to force a complete reprocessing the jsp from within an action? tia.
>
---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@(protected)
For additional commands, e-mail: user-help@(protected)

Attachment:
user_200898.ezm (zipped)Hi cpanon,
> I am looking for the simplest technique that would reprocess the session objects from the new values, regenerate the full jsp,
then just refresh the whole page, by javascript after completion of ajax.
Or do not use ajax at all, this will be most simple solution for You.
Best greetings,
Paweł Wielgus.

Attachment:
user_200903.ezm (zipped)Hi PW
But I cant access the session objects with JS, nor can I iterate the collections I have in the session to display the updated values that were written in the Ajax processing action. Correct?
--- On Mon, 7/20/09, Paweł Wielgus <poulwiel@(protected):
From: Paweł Wielgus <poulwiel@(protected)>
Subject: Re: Struts w/Ajax with Struts again
To: "Struts Users Mailing List" <user@(protected)>
Date: Monday, July 20, 2009, 2:18 AM
Hi cpanon,
> I am looking for the simplest technique that would reprocess the session objects from the new values, regenerate the full jsp,
then just refresh the whole page, by javascript after completion of ajax.
Or do not use ajax at all, this will be most simple solution for You.
Best greetings,
Paweł Wielgus.
---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@(protected)
For additional commands, e-mail: user-help@(protected)

Attachment:
user_200905.ezm (zipped)Hi cpanon,
what i meant is to do real refresh of the page,
just like the one when You hit F5 button or click "Refresh" on your browser.
Try this:
1. load the page
2. do some of that ajax stuff
3. hit F5
is the result like You have expected?
After all not using ajax at all may be best solution in your case.
Best greetings,
Paweł Wielgus.
2009/7/20 cpanon <cpanon@(protected)>:
> Hi PW
> But I cant access the session objects with JS, nor can I iterate the collections I have in the session to display the updated values that were written in the Ajax processing action. Correct?
>
> --- On Mon, 7/20/09, Paweł Wielgus <poulwiel@(protected):
>
> From: Paweł Wielgus <poulwiel@(protected)>
> Subject: Re: Struts w/Ajax with Struts again
> To: "Struts Users Mailing List" <user@(protected)>
> Date: Monday, July 20, 2009, 2:18 AM
>
> Hi cpanon,
>
>> I am looking for the simplest technique that would reprocess the session objects from the new values, regenerate the full jsp,
>
> then just refresh the whole page, by javascript after completion of ajax.
> Or do not use ajax at all, this will be most simple solution for You.
>
> Best greetings,
> Paweł Wielgus.
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: user-unsubscribe@(protected)
> For additional commands, e-mail: user-help@(protected)
>
>

Attachment:
user_200894.ezm (zipped)Hi Dave,
when i record my tests with selenium ide,
all click or assert alements takes various loactor addresses,
very often they contain DOM paths,
so when layout is changed from tables to divs,
all these addresses are no longer valid.
To present one simple example,
when i record logout click on one of my sites the recorded command i see is
clickAndWait //strong
instead of clickAndWait link=logout
i know this is plain wrong and i could manualy correct it but it
ilustrates the problem.
So when the layout will change and this logout will not be the first
element that is strong,
which is very probable, this test will fail to click the logout link.
I have done about 3 such huge layout changes and every time it
involved tests update.
Still, i use and promote selenium over junit for that kind of job.
Best greetings,
Paweł Wielgus.
2009/7/19 Dave Newton <newton.dave@(protected)>:
> Paweł Wielgus wrote:
>>
>> But You will hit the same scale of problems when You will change
>> layout - all selenium tests are dead,
>
> I haven't really found that to be the case--I only rarely test deep
> structure with Selenium, but instead look for the presence of specific CSS
> selectors containing text etc.
>
> That type of change is (generally) under my control, unlike a framework
> change that breaks *my* tests.
>
> Dave
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: user-unsubscribe@(protected)
> For additional commands, e-mail: user-help@(protected)
>
>

Attachment:
user_200895.ezm (zipped)Paweł Wielgus wrote:
> Hi Dave,
> when i record my tests with selenium ide,
> all click or assert alements takes various loactor addresses,
> very often they contain DOM paths,
> so when layout is changed from tables to divs,
> all these addresses are no longer valid.
On the rare occasions I use the IDE to generate the script I find I
always modify it pretty heavily--since I am pretty good about marking up
my HTML it's almost easier to just write the tests by hand so I can
target only the most-specific elements I'm looking for.
I'm rarely bitten by layout changes since the important stuff doesn't
change much regardless of its surroundings.
YMMV :)
Dave

Attachment:
user_200896.ezm (zipped)Primarily for the sake of learning the inner mechanics of the struts2
framework, and unit testing, I took some time to study and experiment
with the code published at:
http://depressedprogrammer.wordpress.com/2007/06/18/unit-testing-struts-2-actions-spring-junit/
When testing (junit 4) an action implementing the Sessionaware
interface (my login and register classes) I noticed that the session
object is set to null by BaseStrutsTestCase. This was mentioned before
in the author's blog, but not sure if ever addressed. I added a new
comment over there but the discussion could be inactive.
I was wondering if anyone who is using the BaseStrutsTestCase, or used
it in the past, came across this issue and if by any chance managed to
resolve it. Perhaps Haroon might have a comment on this?
Also, a couple of more general questions:
1) Is there a recommended way to check during testing which
interceptors are firing and when?
2) If one with general knowledge of servlets & jsp wants to dive into
the struts2 source code, to get better understanding of the basic
mechanics, what would be the starting point? So should I start lets
say with the struts.core package?, which would be the entry point
class Despatcher, then ActionProxy? -- To the untrained eye (myself),
when looking the code from a distance
(http://svn.apache.org/viewvc/struts/struts2/trunk/core/src/), it
looks somewhat like a ball of twine, so where should I look for the
piece of string that sticks out and will help me untangle it?
Well, the primary objective is testing our struts2 application, so I
will probably try other approaches mentioned in this discussion. So, I
would like to take a deeper look at Selenium next.
Kind regards and I appreciate all the input.
On Sun, Jul 19, 2009 at 4:35 PM, Dave Newton<newton.dave@(protected):
> Paweł Wielgus wrote:
>>
>> Hi Dave,
>> when i record my tests with selenium ide,
>> all click or assert alements takes various loactor addresses,
>> very often they contain DOM paths,
>> so when layout is changed from tables to divs,
>> all these addresses are no longer valid.
>
> On the rare occasions I use the IDE to generate the script I find I always
> modify it pretty heavily--since I am pretty good about marking up my HTML
> it's almost easier to just write the tests by hand so I can target only the
> most-specific elements I'm looking for.
>
> I'm rarely bitten by layout changes since the important stuff doesn't change
> much regardless of its surroundings.
>
> YMMV :)
>
> Dave
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: user-unsubscribe@(protected)
> For additional commands, e-mail: user-help@(protected)
>
>

Attachment:
user_200897.ezm (zipped)On Sunday 19 July 2009 10:16:59 pm Dimitrios Christodoulakis wrote:
>
> 2) If one with general knowledge of servlets & jsp wants to dive into
> the struts2 source code, to get better understanding of the basic
> mechanics, what would be the starting point? So should I start lets
> say with the struts.core package?, which would be the entry point
> class Despatcher, then ActionProxy? -- To the untrained eye (myself),
> when looking the code from a distance
> (http://svn.apache.org/viewvc/struts/struts2/trunk/core/src/), it
> looks somewhat like a ball of twine, so where should I look for the
> piece of string that sticks out and will help me untangle it?
>
Depending on your goals, I think one place to start might be the xwork core.
Xwork is an implementation of the command design pattern...
http://en.wikipedia.org/wiki/Command_Pattern
Once you have a solid understanding of what is going on within xwork, then you
can start with the Dispatcher.
That being said, Struts is really the combination of many things. For
instance, it lets xwork drive the core flow of request processing, but there is
also the tag library. The tag library does a good job of breaking up
processing into models, templating and jsp tag specific stuff. If you are
interested in the tag library, start with Component and take a look at a few
of the easier to follow tags (s:if, s:url, etc.). Part of understanding the
tag library means learning freemarker, but freemarker is easy to learn as you
go.
-Wes
--
Wes Wannemacher
Author - Struts 2 In Practice
Includes coverage of Struts 2.1, Spring, JPA, JQuery, Sitemesh and more
http://www.manning.com/wannemacher

Attachment:
user_200899.ezm (zipped)
Hi there,
I am using struts 1.2.9. I am trying to display a record (which has an image
and title) into a 3x3 grid with paging. I am fetching these records from by
database and would like to display them to automatically be set on my page.
Is there a control in struts which could help me ahieve this with ease. I
have tried to look into datagrid but could not find if this was the correct
approach. Plesae help me.
Thanks
--
Sent from the Struts - User mailing list archive at Nabble.com.

Attachment:
user_200900.ezm (zipped)Hi,
recently I was told using Interceptors was better than using a BaseAction
object performing the login process. I agree. Still I have some trouble:
This is what happens: I have a JSP that creates a button liked with another
action:
AgencyDetails.jsp
---------------------------------
...
<s:url id="url" value="/rating/Rate">
<s:param name="staffResourceId"><s:property value="staffResource.id"
/></s:param>
</s:url>
<s:a href="%{url}"><button>Place Rating!</button></s:a><br>
...
---------------------------------
This is the struts.xml configuration for that Action:
rating.xml
---------------------------------
<package name="rating" namespace="/rating" extends="default">
<default-interceptor-ref name="defaultLoginStack" />
<action name="Rate"
class="de.mathiasewald.projektseminar.action.rating.Rate">
<result>
/rating/Rate.jsp
</result>
</action>
</package>
---------------------------------
This is the inteceptor stack in struts.xml
---------------------------------
<interceptors>
<interceptor name="login"
class="de.mathiasewald.projektseminar.interceptor.LoginInterceptor">
</interceptor>
<interceptor-stack name="defaultLoginStack">
<interceptor-ref name="login" />
</interceptor-stack>
</interceptors>
---------------------------------
and finally the LoginInterceptor.java
---------------------------------
public class LoginInterceptor extends AbstractInterceptor implements
StrutsStatics {
/**
*
*/
private static final long serialVersionUID = -6647897949084333127L;
private LoginManager loginManager = new LoginManager();
private static final Log log = LogFactory.getLog(LoginInterceptor.class);
private static final String USER_HANDLE = "QUADRAN_USER_SESSSION_HANDLE";
private static final String LOGIN_ATTEMPT = "QUADRAN_LOGIN_ATTEMPT";
private static final String USERNAME = "QUADRAN_USERNAME";
private static final String PASSWORD = "QUADRAN_PASSWORD";
public void init () {
log.info ("Intializing LoginInterceptor");
}
public void destroy () {}
public String intercept (ActionInvocation invocation) throws Exception {
// Get the action context from the invocation so we can access the
// HttpServletRequest and HttpSession objects.
final ActionContext context = invocation.getInvocationContext ();
HttpServletRequest request = (HttpServletRequest)
context.get(HTTP_REQUEST);
HttpSession session = request.getSession (true);
// Is there a "user" object stored in the user's HttpSession?
Object user = session.getAttribute (USER_HANDLE);
if (user == null) {
// The user has not logged in yet.
// Is the user attempting to log in right now?
String loginAttempt = request.getParameter (LOGIN_ATTEMPT);
if (loginAttempt != null && loginAttempt.trim().length() > 0) { // The
user is attempting to log in.
log.info("User tries to log in - processing attempt...");
// Process the user's login attempt.
if (processLoginAttempt (request, session) ) {
// The login succeeded send them the login-success page.
log.info("User " + loginAttempt + " logged in successfully.");
return invocation.invoke ();
} else {
// The login failed. Set an error if we can on the action.
log.info("Error authenticating user " + loginAttempt);
Object action = invocation.getAction ();
if (action instanceof
com.opensymphony.xwork2.ValidationAware) {
((
com.opensymphony.xwork2.ValidationAware) action).addActionError
("Username or password incorrect.");
}
}
}
// Either the login attempt failed or the user hasn't tried to login yet,
// and we need to send the login form.
return "login";
} else {
return invocation.invoke ();
}
}
/**
* Attempt to process the user's login attempt delegating the work to the
* SecurityManager.
*/
public boolean processLoginAttempt (HttpServletRequest request, HttpSession
session) {
// Get the username and password submitted by the user from the
HttpRequest.
String username = request.getParameter (USERNAME);
String password = request.getParameter (PASSWORD);
// Use the security manager to validate the user's username and password.
Object user = loginManager.login(username, password);
if (user != null) {
// The user has successfully logged in. Store their user object in
// their HttpSession. Then return true.
session.setAttribute (USER_HANDLE, user);
return true;
} else {
// The user did not successfully log in. Return false.
return false;
}
}
}
---------------------------------
Clicking the button I showed ealier, the Rate action is invoked and
intercepted by LoginInterceptor. As you can see the Action gets a parameter
"staffResourceId". As I click it the login page shows up and the address bar
of my browser tells
"http://localhost:8080/projektseminar/rating/Rate?staffResourceId=1".
Next, I enter my login credentials, the log tells me I was logged in
successfully, the browser address bar says
"http://localhost:8080/projektseminar/rating/Rate" and the log messages from
the Rate action say that there was no staffResourceId parameter set.
Why is that?
cu
mathias
--
Sent from the Struts - User mailing list archive at Nabble.com.

Attachment:
user_200902.ezm (zipped)You need to include one of the framework interceptor stacks (e.g
"defaultStack") in your "defaultLoginStack" stack. As you have
configured it, your interceptor is the only one that is being
executed, so none of the framework "magic" gets applied.
Nils-H
On Mon, Jul 20, 2009 at 10:09 AM, mathias-ewald<nitehoaxxer@(protected):
>
> Hi,
>
> recently I was told using Interceptors was better than using a BaseAction
> object performing the login process. I agree. Still I have some trouble:
>
> This is what happens: I have a JSP that creates a button liked with another
> action:
>
> AgencyDetails.jsp
> ---------------------------------
> ...
> <s:url id="url" value="/rating/Rate">
> <s:param name="staffResourceId"><s:property value="staffResource.id"
> /></s:param>
> </s:url>
> <s:a href="%{url}"><button>Place Rating!</button></s:a><br>
> ...
> ---------------------------------
>
> This is the struts.xml configuration for that Action:
>
> rating.xml
> ---------------------------------
> <package name="rating" namespace="/rating" extends="default">
> <default-interceptor-ref name="defaultLoginStack" />
> <action name="Rate"
> class="de.mathiasewald.projektseminar.action.rating.Rate">
> <result>
> /rating/Rate.jsp
> </result>
> </action>
> </package>
> ---------------------------------
>
> This is the inteceptor stack in struts.xml
>
> ---------------------------------
> <interceptors>
> <interceptor name="login"
> class="de.mathiasewald.projektseminar.interceptor.LoginInterceptor">
>
> </interceptor>
> <interceptor-stack name="defaultLoginStack">
> <interceptor-ref name="login" />
> </interceptor-stack>
> </interceptors>
> ---------------------------------
>
> and finally the LoginInterceptor.java
>
> ---------------------------------
> public class LoginInterceptor extends AbstractInterceptor implements
> StrutsStatics {
>
> /**
> *
> */
> private static final long serialVersionUID = -6647897949084333127L;
>
>
> private LoginManager loginManager = new LoginManager();
>
> private static final Log log = LogFactory.getLog(LoginInterceptor.class);
>
> private static final String USER_HANDLE = "QUADRAN_USER_SESSSION_HANDLE";
> private static final String LOGIN_ATTEMPT = "QUADRAN_LOGIN_ATTEMPT";
> private static final String USERNAME = "QUADRAN_USERNAME";
> private static final String PASSWORD = "QUADRAN_PASSWORD";
>
>
>
> public void init () {
> log.info ("Intializing LoginInterceptor");
> }
>
> public void destroy () {}
>
> public String intercept (ActionInvocation invocation) throws Exception {
> // Get the action context from the invocation so we can access the
> // HttpServletRequest and HttpSession objects.
> final ActionContext context = invocation.getInvocationContext ();
> HttpServletRequest request = (HttpServletRequest)
> context.get(HTTP_REQUEST);
> HttpSession session = request.getSession (true);
>
> // Is there a "user" object stored in the user's HttpSession?
> Object user = session.getAttribute (USER_HANDLE);
> if (user == null) {
> // The user has not logged in yet.
>
> // Is the user attempting to log in right now?
> String loginAttempt = request.getParameter (LOGIN_ATTEMPT);
> if (loginAttempt != null && loginAttempt.trim().length() > 0) { // The
> user is attempting to log in.
>
> log.info("User tries to log in - processing attempt...");
>
> // Process the user's login attempt.
> if (processLoginAttempt (request, session) ) {
> // The login succeeded send them the login-success page.
> log.info("User " + loginAttempt + " logged in successfully.");
> return invocation.invoke ();
> } else {
> // The login failed. Set an error if we can on the action.
> log.info("Error authenticating user " + loginAttempt);
> Object action = invocation.getAction ();
> if (action instanceof
com.opensymphony.xwork2.ValidationAware) {
> ((
com.opensymphony.xwork2.ValidationAware) action).addActionError
> ("Username or password incorrect.");
> }
> }
> }
>
> // Either the login attempt failed or the user hasn't tried to login yet,
> // and we need to send the login form.
> return "login";
> } else {
> return invocation.invoke ();
> }
> }
>
> /**
> * Attempt to process the user's login attempt delegating the work to the
> * SecurityManager.
> */
> public boolean processLoginAttempt (HttpServletRequest request, HttpSession
> session) {
> // Get the username and password submitted by the user from the
> HttpRequest.
> String username = request.getParameter (USERNAME);
> String password = request.getParameter (PASSWORD);
>
> // Use the security manager to validate the user's username and password.
> Object user = loginManager.login(username, password);
>
> if (user != null) {
> // The user has successfully logged in. Store their user object in
> // their HttpSession. Then return true.
> session.setAttribute (USER_HANDLE, user);
> return true;
> } else {
> // The user did not successfully log in. Return false.
> return false;
> }
> }
>
> }
> ---------------------------------
>
> Clicking the button I showed ealier, the Rate action is invoked and
> intercepted by LoginInterceptor. As you can see the Action gets a parameter
> "staffResourceId". As I click it the login page shows up and the address bar
> of my browser tells
> "http://localhost:8080/projektseminar/rating/Rate?staffResourceId=1".
> Next, I enter my login credentials, the log tells me I was logged in
> successfully, the browser address bar says
> "http://localhost:8080/projektseminar/rating/Rate" and the log messages from
> the Rate action say that there was no staffResourceId parameter set.
>
> Why is that?
>
> cu
> mathias
> --
> View this message in context: http://www.nabble.com/Problem-with-LoginInterceptor-tp24565562p24565562.html
> Sent from the Struts - User mailing list archive at Nabble.com.
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: user-unsubscribe@(protected)
> For additional commands, e-mail: user-help@(protected)
>
>

Attachment:
user_200904.ezm (zipped)Thx for the reply! I checked the Login Intercepter Tutorial once again and
recognized I forgot some Interceptors as you told. This is what they suggest
to define:
You need to include one of the framework interceptor stacks (e.g
"defaultStack") in your "defaultLoginStack" stack. As you have
configured it, your interceptor is the only one that is being
executed, so none of the framework "magic" gets applied.
---------------------------------------------------------------------------------
<interceptors>
<interceptor name="login"
class="de.mathiasewald.projektseminar.interceptor.LoginInterceptor">
</interceptor>
<interceptor-stack name="defaultLoginStack">
<interceptor-ref name="servlet-config" />
<interceptor-ref name="params" />
<interceptor-ref name="login" />
<interceptor-ref name="prepare" />
<interceptor-ref name="chain" />
<interceptor-ref name="model-driven" />
<interceptor-ref name="fileUpload" />
<interceptor-ref name="static-params" />
<interceptor-ref name="params" />
<interceptor-ref name="conversionError" />
<interceptor-ref name="validation" />
<interceptor-ref name="workflow" />
</interceptor-stack>
<interceptor-stack name="defaultInsecureStack">
<interceptor-ref name="servlet-config" />
<interceptor-ref name="params" />
<interceptor-ref name="prepare" />
<interceptor-ref name="chain" />
<interceptor-ref name="model-driven" />
<interceptor-ref name="fileUpload" />
<interceptor-ref name="static-params" />
<interceptor-ref name="params" />
<interceptor-ref name="conversionError" />
<interceptor-ref name="validation" />
<interceptor-ref name="workflow" />
</interceptor-stack>
</interceptors>
---------------------------------------------------------------------------------
This brings up the following Exception as Tomcat starts:
---------------------------------------------------------------------------------
Jul 20, 2009 12:38:50 PM
org.apache.tomcat.util.digester.SetPropertiesRulebegin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting
property 'source' to 'org.eclipse.jst.jee.server:projektseminar' did not
find a matching property.
Jul 20, 2009 12:38:50 PM
org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal
performance in production environments was not found on the
java.library.path:
/usr/lib/jvm/java-6-sun-1.6.0.14/jre/lib/amd64/server:/usr/lib/jvm/java-6-sun-1.6.0.14/jre/lib/amd64:/usr/lib/jvm/java-6-sun-1.6.0.14/jre/../lib/amd64:/usr/lib64/xulrunner-addons:/usr/java/packages/lib/amd64:/lib:/usr/lib
Jul 20, 2009 12:38:50 PM
org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Jul 20, 2009 12:38:50 PM
org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 692 ms
Jul 20, 2009 12:38:50 PM
org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Jul 20, 2009 12:38:50 PM
org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.20
12:38:51,865 INFO XmlConfigurationProvider:31 - Parsing configuration file
[struts-default.xml]
12:38:51,991 INFO XmlConfigurationProvider:31 - Parsing configuration file
[struts-plugin.xml]
12:38:52,075 INFO XmlConfigurationProvider:31 - Parsing configuration file
[struts.xml]
Jul 20, 2009 12:38:52 PM
org.apache.catalina.core.StandardContextfilterStart
SEVERE: Exception starting filter struts2
Unable to load configuration. - interceptor-ref -
file:/home/mathias/.workspace_j2ee/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/projektseminar/WEB-INF/classes/struts.xml:23:46
at
com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration (
ConfigurationManager.java:58)
at
org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration (
Dispatcher.java:360)
at
org.apache.struts2.dispatcher.Dispatcher.init (
Dispatcher.java:403)
at
org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:69)
at
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:48)
at
org.apache.catalina.core.ApplicationFilterConfig.getFilter (
ApplicationFilterConfig.java:275)
at
org.apache.catalina.core.ApplicationFilterConfig.setFilterDef (
ApplicationFilterConfig.java:397)
at
org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:108)
at
org.apache.catalina.core.StandardContext.filterStart (
StandardContext.java:3800)
at
org.apache.catalina.core.StandardContext.start (
StandardContext.java:4450)
at
org.apache.catalina.core.ContainerBase.start (
ContainerBase.java:1045)
at
org.apache.catalina.core.StandardHost.start (
StandardHost.java:722)
at
org.apache.catalina.core.ContainerBase.start (
ContainerBase.java:1045)
at
org.apache.catalina.core.StandardEngine.start (
StandardEngine.java:443)
at
org.apache.catalina.core.StandardService.start (
StandardService.java:516)
at
org.apache.catalina.core.StandardServer.start (
StandardServer.java:710)
at
org.apache.catalina.startup.Catalina.start (
Catalina.java:583)
at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke (
NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke (
DelegatingMethodAccessorImpl.java:25)
at
java.lang.reflect.Method.invoke (
Method.java:597)
at
org.apache.catalina.startup.Bootstrap.start (
Bootstrap.java:288)
at
org.apache.catalina.startup.Bootstrap.main (
Bootstrap.java:413)
Caused by: Unable to find interceptor class referenced by ref-name
servlet-config - interceptor-ref -
file:/home/mathias/.workspace_j2ee/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/projektseminar/WEB-INF/classes/struts.xml:23:46
at
com.opensymphony.xwork2.config.providers.InterceptorBuilder.constructInterceptorReference (
InterceptorBuilder.java:52)
at
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.lookupInterceptorReference (
XmlConfigurationProvider.java:1092)
at
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadInterceptorStack (
XmlConfigurationProvider.java:798)
at
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadInterceptorStacks (
XmlConfigurationProvider.java:811)
at
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadInterceptors (
XmlConfigurationProvider.java:834)
at
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage (
XmlConfigurationProvider.java:441)
at
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages (
XmlConfigurationProvider.java:265)
at
org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages (
StrutsXmlConfigurationProvider.java:111)
at
com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer (
DefaultConfiguration.java:189)
at
com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration (
ConfigurationManager.java:55)
... 22 more
Jul 20, 2009 12:38:52 PM
org.apache.catalina.core.StandardContext start
SEVERE: Error filterStart
Jul 20, 2009 12:38:52 PM
org.apache.catalina.core.StandardContext start
SEVERE: Context [/projektseminar] startup failed due to previous errors
log4j:ERROR LogMananger.repositorySelector was null likely due to error in
class reloading, using NOPLoggerRepository.
Jul 20, 2009 12:38:52 PM
org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Jul 20, 2009 12:38:52 PM
org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Jul 20, 2009 12:38:52 PM
org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/46 config=null
Jul 20, 2009 12:38:52 PM
org.apache.catalina.startup.Catalina start
INFO: Server startup in 1942 ms
---------------------------------------------------------------------------------
So obviously the additions Interceptors cannot be found. Where are they
defined??
cu
Mathias
--
Sent from the Struts - User mailing list archive at Nabble.com.

Attachment:
user_200906.ezm (zipped)mathias-ewald wrote:
> the additions Interceptors cannot be found. Where are they defined??
My first guess would be that you're using Struts 2.1+ and the reference
material you're using is for Struts 2.0. Interceptors are now named
using camelCase: modelDriven, servletConfig, etc. (or whatever they're
called).
Dave

Attachment:
user_200910.ezm (zipped)
Hi,
yes I am using the latest version of struts2. Most likely the tutorials I
used refer to other versions. I set the struts.xml as follows:
---------------------------------------------------
<interceptors>
<interceptor name="login"
class="de.mathiasewald.projektseminar.interceptor.LoginInterceptor" />
<interceptor-stack name="defaultLoginStack">
<interceptor-ref name="servletConfig" />
<interceptor-ref name="params" />
<interceptor-ref name="login" />
<interceptor-ref name="prepare" />
<interceptor-ref name="chain" />
<interceptor-ref name="modelDriven" />
<interceptor-ref name="fileUpload" />
<interceptor-ref name="staticParams" />
<interceptor-ref name="params" />
<interceptor-ref name="conversionError" />
<interceptor-ref name="validation" />
<interceptor-ref name="workflow" />
</interceptor-stack>
<interceptor-stack name="defaultInsecureStack">
<interceptor-ref name="servletConfig" />
<interceptor-ref name="params" />
<interceptor-ref name="prepare" />
<interceptor-ref name="chain" />
<interceptor-ref name="modelDriven" />
<interceptor-ref name="fileUpload" />
<interceptor-ref name="staticParams" />
<interceptor-ref name="params" />
<interceptor-ref name="conversionError" />
<interceptor-ref name="validation" />
<interceptor-ref name="workflow" />
</interceptor-stack>
</interceptors>
---------------------------------------------------
The errors about unfindable interceptors disappeard. But still, the
parameter is not preserved.
Any suggestions?
cu
mathias
--
Sent from the Struts - User mailing list archive at Nabble.com.

Attachment:
user_200912.ezm (zipped)I don't think it will preserve your parameter by default, I might be wrong, if it do, then that is another magic in S2 I didn't know that.
For what I understand is there are 2 request from the user,
1) http://localhost:8080/projektseminar/rating/Rate?staffResourceId=1
2) login submit
I don't think you store a staffResourceId as a hidden param in the login page, if its not there you won't expect to come into your url.
Regards
Louis
________________________________
From: mathias-ewald <nitehoaxxer@(protected)>
To: user@(protected)
Sent: Monday, July 20, 2009 2:53:39 PM
Subject: Re: Problem with LoginInterceptor
Hi,
yes I am using the latest version of struts2. Most likely the tutorials I
used refer to other versions. I set the struts.xml as follows:
---------------------------------------------------
<interceptors>
<interceptor name="login"
class="de.mathiasewald.projektseminar.interceptor.LoginInterceptor" />
<interceptor-stack name="defaultLoginStack">
<interceptor-ref name="servletConfig" />
<interceptor-ref name="params" />
<interceptor-ref name="login" />
<interceptor-ref name="prepare" />
<interceptor-ref name="chain" />
<interceptor-ref name="modelDriven" />
<interceptor-ref name="fileUpload" />
<interceptor-ref name="staticParams" />
<interceptor-ref name="params" />
<interceptor-ref name="conversionError" />
<interceptor-ref name="validation" />
<interceptor-ref name="workflow" />
</interceptor-stack>
<interceptor-stack name="defaultInsecureStack">
<interceptor-ref name="servletConfig" />
<interceptor-ref name="params" />
<interceptor-ref name="prepare" />
<interceptor-ref name="chain" />
<interceptor-ref name="modelDriven" />
<interceptor-ref name="fileUpload" />
<interceptor-ref name="staticParams" />
<interceptor-ref name="params" />
<interceptor-ref name="conversionError" />
<interceptor-ref name="validation" />
<interceptor-ref name="workflow" />
</interceptor-stack>
</interceptors>
---------------------------------------------------
The errors about unfindable interceptors disappeard. But still, the
parameter is not preserved.
Any suggestions?
cu
mathias
--
Sent from the Struts - User mailing list archive at Nabble.com.
---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@(protected)
For additional commands, e-mail: user-help@(protected)

Attachment:
user_200901.ezm (zipped)
When submitting a form using manual validation in my action. Even when the
validation fails and the action method supposed to be called is not called
at all, the dirty data is persisted ?
How can I prevent data from being persisted if the validation fails ?
Note: I use prepare method to load e.g an user object from a
manager/service. And the data relates to the user object that is about.
-taltun
--
Sent from the Struts - User mailing list archive at Nabble.com.

Attachment:
user_200907.ezm (zipped)What are you using to manage persistence? Can we see your action's source
code?
On Mon, Jul 20, 2009 at 5:42 AM, taltun <tuncayxx@(protected):
>
> When submitting a form using manual validation in my action. Even when the
> validation fails and the action method supposed to be called is not called
> at all, the dirty data is persisted ?
>
> How can I prevent data from being persisted if the validation fails ?
>
> Note: I use prepare method to load e.g an user object from a
> manager/service. And the data relates to the user object that is about.
>
> -taltun
> --
> View this message in context:
> http://www.nabble.com/Prevent-persisting-data-when-validation-fails-tp24566713p24566713.html
> Sent from the Struts - User mailing list archive at Nabble.com.
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: user-unsubscribe@(protected)
> For additional commands, e-mail: user-help@(protected)
>
>
--
Jim Kiley
Senior Technical Consultant | Summa
[p] 412.258.3346
http://www.summa-tech.com

Attachment:
user_200909.ezm (zipped)
I use JPA (hibernate) to persist.
An example of action that use prepare to load a person object from
transactional manager. When the validate fails and it return back to the
input page the request ends and the transaction persists the dirty user
object to database. The dirty user object should not be persisted if the
validation fails.:
public class PersonAction extends BaseAction implements Preparable {
private PersonManager personManager;
private Person person;
public void prepare() {
person = personManager.getPerson(id);
}
public String savePerson() {
manager.savePerson(person);
return SUCCESS;
}
public void validate() {
if (person.firstName.length < 5 and person.firstName > 10) {
addActionError("Firstname length should be between 5 and 10
characters.");
}
}
}
taltun wrote:
>
> When submitting a form using manual validation in my action. Even when the
> validation fails and the action method supposed to be called is not called
> at all, the dirty data is persisted ?
>
> How can I prevent data from being persisted if the validation fails ?
>
> Note: I use prepare method to load e.g an user object from a
> manager/service. And the data relates to the user object that is about.
>
> -taltun
>
--
Sent from the Struts - User mailing list archive at Nabble.com.

Attachment:
user_200911.ezm (zipped)> I use JPA (hibernate) to persist.
>
>
>
> An example of action that use prepare to load a person object from
> transactional manager. When the validate fails and it return back to the
> input page the request ends and the transaction persists the dirty user
> object to database. The dirty user object should not be persisted if the
> validation fails.:
>
> public class PersonAction extends BaseAction implements Preparable {
>
> private PersonManager personManager;
> private Person person;
>
> public void prepare() {
> person = personManager.getPerson(id);
> }
>
> public String savePerson() {
> manager.savePerson(person);
> return SUCCESS;
> }
>
> public void validate() {
> if (person.firstName.length < 5 and person.firstName > 10) {
> addActionError("Firstname length should be between 5 and 10
> characters.");
> }
> }
>
> }
>
>
This isn't really a Struts problem, it just the way Hibernate works.
If you make changes to a monitored object (Persistent state) from the
database then Hibernate will detect this and save the changes to the
database when you commit the transaction. There is actually no need to call
"save" to update a db object it will happen automatically.
To "fix" your problem you have a couple of choices:
1) Don't make changes to db objects unless you are sure you want them
saved. This would mean changing your actions to work with copies of the
objects or Detached objects instead of the actually db objects (this is what
I do).
2) Don't commit the transaction if the validation fails. Do a rollback
instead.

Attachment:
user_200908.ezm (zipped)I just put a post out on Enterprise Java Community under web services.
Thanks.
-----Original Message-----
From: Dave Newton [mailto:newton.dave@(protected)]
Sent: Friday, July 17, 2009 6:51 PM
To: Struts Users Mailing List
Subject: Re: null and zero issue
Russo, Joe wrote:
> I know this may not be the appropriate group to send this, but I think
> this is a general issue that I am not aware of and this group is
active
> and thought I'd give it a shot.
Wouldn't a web service list/forum be a better bet?
Dave
---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@(protected)
For additional commands, e-mail: user-help@(protected)
****
****