Playframework dynamic form handling - java

Hallo guys im new to the playframework and run into a little problem
regarding form handling.
Here is my view
<form action="#routes.Account.changeemail()" method="Post">
email:<input name ="email">
<button type="submit" name="action" value="Change_email">save</button>
<br />
</form>
<form action="#routes.Account.changepassword()" method="Post">
password:<input name ="password">
<button type="submit" name="action" value="change_password">save</button>
</form>
<br />
And here is my controller
public static Result changeemail(){
final DynamicForm form = Form.form().bindFromRequest();
Logger.info(form.get("email"));
return TODO;}
public static Result changepassword(){
final DynamicForm forms = Form.form().bindFromRequest();
Logger.info(forms.get("password"));
return TODO;}
Here the routes:
GET /account controllers.Account.accountview()
POST /account controllers.Account.changeemail()
POST /account controllers.Account.changepassword()
The problem is if i press the Change_email button it does the right thing, but if i press the password button it is doing the changeemail action , even if it should handle the changepasswort action. I checked it with the firefox networkanalysis and it seems that it is sending the correct action.
In forward thanks for the help
Greetings Alex

The problem comes from your routes, the order is important. Your router always takes the first POST /account which executes the changeemail() action. You can't have POST /account for two different actions. It should be :
GET /account controllers.Account.accountview()
POST /account/change-email controllers.Account.changeemail()
POST /account/change-password controllers.Account.changepassword()

Related

How does <input type="hidden" name.../> work with JSP Servlets

I'm studying JSP and Servlets by reading a book and following some online tutorials. I'm totally new with web programming using JSP and Servlets.
I came across an example which I am trying to understand.
index.html
<form action="emailList" method="post">
<input type="hidden" name="action" value="add" />
<label>Email: </label>
<input type="email" name="email" required /> <br />
<label>First Name:</label>
<input type="text" name="firstName" required /> <br/>
<label>Last Name:</label>
<input type="text" name="lastName" required /> <br />
<label> </label>
<input type="submit" value="Join Now" id="submit" />
</form>
EmailServlet.java
public class EmailListServlet extends HttpServlet{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String url = "/index.html";
//get the current action
String action = req.getParameter("action");
if(action == null){
action = "join"; //default action
}
//perform action and set URL to appropriate page
if(action.equals("join")){
url = "/index.html"; //the join page
}
else if(action.equals("add")){
//get parameters from the request
String firstName = req.getParameter("firstName");
String lastName = req.getParameter("lastName");
String email = req.getParameter("email");
//store data in User object and save User object in database
User user = new User(firstName, lastName, email);
UserDB.insert(user);
//set User object in request object and set URL
req.setAttribute("user", user);
url = "/thanks.jsp"; //the thanks page
}
//forward request and response objects to specified url
getServletContext().getRequestDispatcher(url).forward(req, resp);
}
The thing I don't understand is the IF-ELSE part.
I read somewhere that the main purpose of using hidden <input> is to determine the state of a form. The way I understand it is that of, a way to check if form fields (or parameters) are null or not.
If that's the case, then what is the purpose of the value="add" attribute?
Because on else if(action.equals("add")) , add was used.
What could the req.getParameter() return ?
//get the current action
String action = req.getParameter("action");
I'm asking because in the past I did some CRUD project on PHP where it used the ff to check if form has no null parameters.
if(isset($_POST['btnSave'])){
}
<form method ="POST" action="index.php">
<label>First Name<input type="text" name="firstname" required></label>
<br /><br />
<label>Last Name<input type="text" name="lastname" required></label>
<br /><br />
<input type = "submit" name="btnSave" value="Save" />
<input type = "submit" name="btnSearch" value="Search" />
</form>
Instead, in the last form example it used the btnSave (form button) instead of a hidden input.
I just don't see the point of using a value="add" and what req.getParameter("action") could return. Because it was used on the IF-ELSE
I'd appreciate any explanation.
Thank you.
Covering your questions in reverse order:
What could the req.getParameter() return ?
It could return anything. The <form> you posted will generate a request to the server that looks like this:
POST /emailList HTTP/1.1
Host: example.com
Cache-Control: no-cache
action=add&email=MyEmail&firstName=MyFirstName&lastName=MyLastName&submit=Join Now
Now, consider the case where someone submits the following request instead:
POST /emailList HTTP/1.1
Host: example.com
Cache-Control: no-cache
action=edit&id=1&email=NewEmail&firstName=TypoFreeName&lastName=TypoFreeLastName&submit=Update Details
Since you don't have an "edit" case in your servlet, but you do have that if check, your servlet will just redirect to /index.html instead of changing a user's details or inserting a new user.
A logical next step for code like this would be to add new sections to your servlet:
if(action.equals("join")){
url = "/index.html"; //the join page
}
else if (action.equals("delete") {
//Call UserDB.delete()
}
else if (action.equals("edit") {
//Call UserDB.update()
}
else if(action.equals("add")){
...
}
what is the purpose of the value="add" attribute?
It's partly to control the flow of your servlet and partly to act as an error prevention measure; if the request includes action=add, you proceed with the assumption that you'll have the other form elements (better practice would be to check to make sure that firstName, lastName, and email are set in the request before calling UserDB).
The code is frankly a bit odd. It appears to be designed to handle the case where a different form (without an action field) is POSTed to the servlet, and to handle it by presenting the index.html page. Perhaps there's another form somewhere else in the chapter that does that?
If the form in the question is posted to the server, the servlet will receive an action parameter. (Well, unless JavaScript code actively removes the input from the form first.) So getParameter("action") will not return null. It might (if JavaScript code changed the input's value) get a different string, even a "" string, but not null.
It's probably worth noting that it doesn't handle the possibility that a different form with an action=add field is posted to the server, and happily uses the other parameters without checking them server-side, which is poor practice. Validation must be done server-side.

Spring MVC - multiple submit buttons handled in single #requestmapping

I have a form with 2 submit type buttons(Yes/ No), i would like to handle this form with single #RequestMapping in my controller class. I certainly wish to handle multiple submit in single request mapping method only.
My first question is this possible. Can multiple submit buttons be handled with single request mapping of form action in the controller class ?
If yes, then below is the code I have written. Please suggest if this a correct way of implementing it or if it needs to be updated.
Currently, my code looks like this:
Form.jsp:
<form:form action="doAction">
<input type="submit" name="buttonClick" class="button" value="yes, do Someting" />
<input type="submit" name="buttonClick" class="button" value="no, do nothing" />
</form:form>
Controller.java:-
private String buttonClick;
#RequestMapping(value = "/doAction", method = RequestMethod.POST, params="buttonClick") {
if("yes, do Something".equalsIgnoreCase(buttonClick))
//
else if("no, do Nothing".equalsIgnoreCase(buttonClick))
//
}
You can change the form action on button click e.g. to
"doAction?buttonClick="+<some value from clicked button>.
Or introduce a hidden input in the form. On click change the input value to reflect clicked button. Then the input is available on server side.
You can use a hidden field and change its value on every button click using jQuery:
<form:form action="doAction">
<input type="hidden" name="buttonClick" id="buttonClick" />
<input type="submit" name="buttonClickYes" class="button" value="yes, do Someting" />
<input type="submit" name="buttonClickNo" class="button" value="no, do nothing" />
</form:form>
<javascript>
$(document).ready(function(){
$("input[type=submit]").click(function(){
$("#buttonClick").val($(this).val());
return true;
});
});
</javascript>

implementation of post redirect get in java web

am i implementing the post redirect get approach in java web. i have this index.jsp which i can add information to database.
<form action="servlet" method="post>
<input type="text" placeholder="itemname"/>
<input type="text" placeholder="itemprice"/>
<input type="submit" value="add item"/>
</form>
and in servlet i process the username and password
//returns a boolean if success or not
if(processItem(itemname,itemprice)){
response.sendRedirect("secondservlet?ADD=success");
}
and in the secondservlet
if(request.getParameter("ADD").equals("SUCCESS"))
request.getRequestDispatcher("success.jsp").forward(request,response);
am i doing it right?
am i doing it right?
You are sending a POST, then redirecting, which results in a GET. If that is what you were trying to do, then yes, you are doing it right.
Note that your second servlet should probably check if getParameter(..) returns null. You might get to the second servlet from some other call that doesn't include any request parameters.

How to send label parameter from JSP to servlet?

I have a jQuery dialogue box which contains values as checkboxes. On selecting the checkboxes I am storing the selected values into label. Next I have to send these values from label as parameter through form to servlet but I don't know how to complete it.
Here is my code:
<form action="CallTimer" method="GET">
<label class="button2">Set Date: </label>
<input type="text" name="date" id="date" size="4">
<input type="Submit" name="Submit" value="Submit" id="Submit">
<br/>
Select Reporting Level
<label class="button2" style="display:none" id="depart"> Department</label>
</form>
I am retrieving these parameters in my Servlet as:
String reportname=request.getParameter("depart");
System.out.println(reportname);
But it is returning null values. Please help me.
Thanks in advance.
You have to use hidden input field:
<input type="hidden" name="depart" />
You need to understand what gets passed on form submission and what is not. In a nutshell, only values of the input fields get sent to the server. You have several ways to solve your problem:
Write value to a hidden input field
Modify the query string (what gets sent after ? in your GET request) during form submission (using java script):
?...&depart=xxx

Hidden input in JSP produces null when passing it to the servlet

In my JSP I do the following :
<!-- Bank manager's permissions -->
<!--more stuff goes here -->
<fieldset>
<legend>To open a new account</legend>
<form action="blablabla">
<input type="hidden" name="hdField" value="myValue" /> // note I pass a "myValue" as string
Press here to continue
</form>
</fieldset>
And in my Servlet I grab the hidden input :
#WebServlet("/employeeTransaction1")
public class Employee1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String getHiddenValue=request.getParameter("hdField");
System.out.println("Hidden field Value :"+getHiddenValue);
// forwards to the page employeeOpenNewAccount.jsp
request.getRequestDispatcher("/WEB-INF/results/employeeOpenNewAccount.jsp").forward(request, response);
}
}
And System.out.println produces : null at the Console
Why do I get a null of not the actual value is I pass ?
Regards
EDIT:
After changing to :
<fieldset>
<legend>To open a new account</legend>
<form action="/employeeTransaction1" method="GET">
<input type="hidden" name="hdField" value="myValue"/>
Press here to continue
</form>
</fieldset>
A null is still presented at the console .
What you are trying to do is to send a form to the server. But, in fact, you don't do that. You just issue a GET request (when the user clicks your link: Press here to continue)
If you want to send the form make sure you set the attributes of the form tag properly and add a submit button to the form:
<form action="/employeeTransaction1" method="GET">
...
<input type="submit" value="Submit" />
...
</form>
Depending on your preferred way of sending the form, you can change the method="GET" paramater to method="POST" and make sure that in the servlet you handle the form in the doPost() method
Alternatively, if your purpose is not to send the from to the server but just to pass the value of the hidden input, you should add its value as a prameter encoded in the GET request. Something like:
/employeeTransaction1?hdField=myValue
To achieve this, you need some client processing, i.e. when the user clicks the link, the hidden input should be added to the get and then the request should be issued.
Using an href tag does not submit your form, i.e. it does not pass the parameters defined in the form to the request. You should use input type="submit" or button tags instead. Also make sure the form action matches your #WebServlet definition.
<fieldset>
<legend>To open a new account</legend>
<form action="/employeeTransaction1">
<input type="hidden" name="hdField" value="myValue" /> // note I pass a "myValue" as string
<input type="submit" value="Submit" />
</form>
</fieldset>

Categories