How to detect who sent the registration form to the action? - java

I have two different forms to register users and an action, form 1 is used by Users of type A and form 2 is used by Users of type B. Therefore when they get to index they will choose the form based on their type so I do not have any option to figure out their type, the only way is to receive the request and find out which form has sent the request to the action.
I need some hints on how can I find out which form has sent the request to the action.
jsp file of UserA
<s:form name="form1" action="register">
.... registration form for User A .....
</s:form>
jsp file of UserB
<s:form name="form2" action="register">
.... Registration form for User B .......
</s:form>
please note the forms are different
action
public String Register() {
if (request is from form1)
{
.....
}
if (request is from form2)
{
....
}
}

Some options:
Put a hidden value in the form.
Look at the session user to determine their type.
Separate logic appropriately and have separate action methods.

Assuming they already have Sessions, you can use
ActionContext.getContext().getSession().getId()
in the Struts2-Bean to identify the Session.
From now, you can differ the user1's actions and user2's actions using the Session-ID;

Related

Java Spring MVC PRG Pattern preserve Data on reload

i'm currently woking on a spring mvc project. I have a page with a form, which represents a configurator.
The user can choose some data in a bunch of select fields and proceeds to the next step, where he gets the same jsp-page but with some more fields, depending on his inputs he made. This will be repeated a few times until he gets his result on another page. Each time a POST will be performed.
Now if the user uses the back function of the Browser he doesn't get to the previous page, but to a browser default "broken page", where Chrome for example says something like "Please confirm resubmission of the form data...". To actually resubmit the data he has to press reload and confirm a popup.
The resubmission itself isn't really a problem, because the data does not get inconsistent, it just performs another call to the backend and receives the data it provides.
The real no-go is the fact that the user has to manually refresh the page and by chance gets confused by the default browser page.
I did some research and found out, that the PRG (Post-Redirect-Get) Pattern might solve this problem.
In fact i can now navigate through the browser or reload the page and does not get the popup or broken page - because it's now a GET request of course.
The problem now is, that if i navigate back, the last page does not contain the data it contained before, but is now empty because no data at all is existing.
I understand that it is now a GET request and no data gets posted, but i thought the previous page would be "reused", like shown here.
Now with the PRG-Pattern the handling of the application is even worse, because if the user reloads or navigates back, he basically has to start from scratch.
Did i misunderstood the meaning of this Pattern?
A quick look into some code, how i implemented this:
#PostMapping("/config")
public String handlePostRequestConfig(RedirectAttributes redirectAttributes, ProductForm productForm){
//Handle productForm and add additional content to it
if(noMoreStepsLeft){
return "redirect:/result";
}
redirectAttributes.addFlashAttribute("form", productForm);
return "redirect:/config";
}
#GetMapping("/config")
public String handleGetRequestConfig(Model model, #ModelAttribute("form") ProductForm productForm{
model.addAttribute("form", productForm);
return getJsp("product");
}
Inside JSP:
<form method="post" action="/config">
<c:foreach items="${form.selectFields}" var="selectField">
<input...>
</c:foreach>
<button type="submit">Submit</button>
</form>
In PRG, P is not the first step of user action flow. PRG is a part of the full flow.
The following shows a flow and how PRG fits in it:
User will hit a URL. For example: http://localhost:8080/myContextPath/config.
This will be handled using a GET handler:
#GetMapping("/config")
public String show(ModelMap model) {
// code
model.put("form", productForm);
return "product"; // returning view name which will be resolved by a view resolver
}
product.jsp:
<form commandName="form" method="post">
<c:foreach items="${form.selectFields}" var="selectField">
<input...>
</c:foreach>
<input type="submit" value="Submit"/>
</form>
This submit action will be handled by a POST handler:
#PostMapping("/config")
public String submit(#ModelAttribute("form") ProductForm productForm,
RedirectAttributes redirectAttributes){
// code, may be service calls, db actions etc
return "redirect:/config";
}
This redirect to /config will be handled again by /config GET handler. (Or you can redirect to any GET handler of course)

Playframework forms

I'm creating a form to allow users to edit my objects, but it seems that only the object fields that are editable in the form are available within my controller once the form is submitted. My example is a user object that I present in a form to allow the user to edit the name field, when they submit the form my controller needs to determine if this is a new user or an exiting user. To determine this I check the ID field, but since the ID field is not editable on the form it is null, when I check it in the controller.
Have I missed something?
For this scenario, keep your id has hidden input in template. So that it will be available for you in controller after user hitting form's submit button.
<input type="hidden" name="id" value='#userForm.field("id").value' >

Collect user input in Servlet and return at the same point to continue program: Java

I have a web application in Java that performs title matching.
The Servlet is the controller and in one of the methods of the Servlet, I am comparing two list of titles. The first list is in a HashMap and the second is from a query ResultSet.
What I want to do is to automatically match those with same title and give the user the option to confirm the ones with some similarities (business logic). Basically, I need to get user input and then return at the same point to continue.
I tried JOptionPane dialog box and it didn't work.
Now I am trying to forward to another HTML page to get user input and then return to the Servlet.
Below is the Servlet code:
while (Querylist.next()) {
String title = Querylist.getString(1).trim().toLowerCase();
if (MyMap.containsKey(title))
{
// confirm match
} else
{
//some title2 is like title
request.setAttribute("Title1", title);
request.setAttribute("Title2", title2);
RequestDispatcher view = request.getRequestDispatcher("TitleMatch.jsp");
view.forward(request, response);
ResultMatch= request.getParameter("ResultMatch");
if (ResultMatch.equals("YES"))
{
// confirm match
}
}
}
HTML Page:
<B> <%= request.getAttribute("Title1")%></B>
<B> <%= request.getAttribute("Title2")%></B>
<FORM method="get" action="DataMerge">
<input type = "radio" name="MatchResult" value="YES" /> YES
<input type = "radio" name="MatchResult" value="NO" checked/>NO
<button type = "submit" formaction="DataMerge" > <b>CONFIRM</b>
</FORM>
EDIT: the loop works and I'm having a java.lang.IllegalStateException Exception.
Does anyone can help to figure out how to do that efficiently in plain Java?
I searched all over SO and haven't found something similar. Thanks in advance.
You might want to reconsider your approach as there are number of fundamental problems with the code you have written. For example:
The while loop test it not correct. Assuming that you are using an Iterator then the test should be list.hasNext();
The if test is nested and incorrect. You cannot use the identifier Map as it is the name of the class, you should use the name of the map object.
If the loop worked the view.forward(request, response); would result in an java.lang.IllegalStateException exception, on the second cycle, as its not possible to resend a response.
I suggest that instead of trying to send each title pair one at a time, that you display them all (or some if there are too many) on one JSP with a yes button next to each pair and as the user clicks the yes button an AJAX call is made to another servlet that updates the database (or an array to latter be used to update the database).
There are some good tutorial about using AJAX and JSP here of SOF and in YouTube.

Generating multiple events in JSP page having more than one button

I am a beginner in the JSP World as per I have noticed that, there is one form tag which has action and method attribute. In action tag we must write the URL of the servlet which gets activated after clicking the submit button.
But my problem start here. I am trying to develop a register page.
I have two servlets:
one checks for the availability of existing user,
second register the user.
Does anyone have any idea how to achieve it without a href link or image button?
Move the code that checks for availability of the existing user and register the user to its own service class say UserService. Make the form submit to 2nd servlet which uses UserService to perform both the operations.
You can have two separate forms but not nested forms in HTML. If you want a single form to change its actions (its target URL) depending on which submit is used, the only way you can achieve that is through javascript.
You can do this with your existing approach by registering a Javascript function
<body>
<script type="text/javascript">
function submitType(submitType)
{
if(submitType==0)
document.userForm.action="CheckUserAvailability.do";
else
document.userForm.action="RegisterUser.do";
}
</script>
<form name="userForm" method="post">
--Other elements here
<input type="submit" value="Check User Availabiliy" onClick="submitType(0)"/>
<input type="submit" value="Check User Availabiliy" onClick="submitType(1)"/>
</form>
</body>
Yes You can.. In the action you give the Servlet name. and inside that servlet you can call java methods which are written in other classes.
Which means you can check
1.one checks for the availability of existing user
2.second register the user
Using two java classes(may be according to your choice)
Just call those methods with in the same servlet..Guess you got an idea.

How do I access the ActionBeanContext within a JSP?

I'm new to Stripes and appreciate every hint that brings me nearer to a functioning web-app!
technological setup: java, dynamic web project, stripes, jsp
scenario:
users can login (index.jsp). After correct email-adress and password (LoginFormActionBean.java), the user is forwarded to a welcoming page (loggedin.jsp).
The content on this welcoming page is something like "welcome < username >, you've been successfully logged in!".
implementation:
i have a form in the index.jsp where i take the user input and pass it to a method in the LoginFormActionBean.java --> works!
in the corresponding method i check whether the user is correct and if so, i insert the user in the ActionBeanContext:
getContext.setUser(loggedinUser);
after that i forward to the loggedin.jsp:
return new ForwardResolution("/loggedin.jsp");
the loggedin.jsp contains following important lines:
<jsp:useBean id="loggedinBean" class="mywebapp.controller.LoggedinBean" scope="session" />
...
${loggedinBean.context.user} //show the whole user object
...
<s:form beanclass="mywebapp.controller.LoggedinBean" name="ButtonForm">
<s:submit name="foo" value="PrintUser" />
</s:form>
<s:form beanclass="mywebapp.controller.LoggedinBean" name="TextForm">
<s:text name="user" />
</s:form>
...
the LoggedinBean.java contains a MyActionBeanContext attribute (like the LoginFormActionBean.java).
to get the userobject out of the context i use:
public String getUser(){
return getContext().getUser().toString();
}
furthermore the LoggedinBean.java contains a method, which is annotated with #DefaultHandler and forwards to loggedin.jsp (the same page)
result:
now, what happens is: after logging in correctly, i'm forwarded to the loggedin.jsp,
the line "${loggedinBean.context.user}" is empty and so is the < s:text >-field.
BUT after clicking the "PrintUser" Button, the < s:text >-field in the "TextForm"-form is filled with the user object of the logged in user!
conclusion:
what i think happens, is that the "setContext()" method of the LoggedinBean.java is not called before i manually execute a method in the bean. Because the "setContext()" method in the bean is not called before i press the button!
the online documentation says to use a context attribute in a JSP just write "${actionBean.context.user}". But the context is null!
even the book "pragmatic stripes"(2008) gives no more information about using the ActionBeanContext.
question:
what happens there?
how can i get the "${loggedinBean.context.user}" line to display the logged in user at all?
and how can i get the < s:text >-field to display the user object after loading the JSP, but without pressing the button?
i hope my problem is clear and my remarks are satisfying
I would like to recommend the usage of the MVC pattern. This pattern will lead to an implementation were the Action Beans will act as controllers that handle all http requests and the JSP pages will become passive views with little logic, only accessible via the Action Bean controllers (no direct access to JSP pages any more!).
If you use this pattern, you always have an "actionBean" available in your JPS and thus you can refer to ${actionBean.context} (see: getContext).

Categories

Resources