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>
Related
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.
I am performing validation of inputted data such as email, password, name, etc. But I am already stuck on the first stage of validation which is to check if User entered nothing.
I already added enctype="multipart/form-data" as mentioned here but now it is always recognizing email as null and I can't forward to the login page in case of success (when email is not null).
Code
signup.jsp
<form method="POST" action="signup" enctype="multipart/form-data">
<input type="email" name="email" placeholder="tonystark#mail.com">
<input type="submit" value="Submit">
</form>
SignUpAction.java
public class SignUpAction implements Action {
#Override
public String handleRequest(HttpServletRequest req, HttpServletResponse resp, DAOFactory dao)
throws ServletException, IOException {
String email = req.getParameter("email");
if (email == null || email.isEmpty()) {
return "signup"; // It loads signup page again (it works)
}
return "login"; // It should go to the login page (it doesn't work)
}
}
Unless you're planning to use your form for uploading a file, you don't need to specify the encoding type of "multipart/form-data".
<form method="POST" action="signup">
<input type="text" name="email" placeholder="tonystark#mail.com">
<input type="submit" value="Submit">
</form>
The last paragraph in your link states:
"When using enctype="multipart/form-data", all parameters are encoded in the request body. That means that request.getParameter(...) will return null for all posted parameters then."
Input type: email
Email is an html5 input type. How To Use The New Email, URL, and Telephone Input Types.
Since it is a multipart/form-data (usually used for the puropose of uploading one/more file(s)) form the request.getParameter() method will always return null.
You can try
<form method="POST" action="signup" enctype="application/x-www-form-urlencoded">
Or completely remove the enctype parameter.
Some references in another SO question.
How to upload files to server using JSP/Servlet?
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>
I should be using getRemoteUser functionality to get the logged in user. Until the authentication part get created I am trying to hard code the user in the jsp page and pass that in the my servlet. But when I try to print out the value its null:
<input type="hidden" name="userId" id="userId" value="123456789" />
Here is how I tried to get the user:
String fakeUser = request.getParameter("userId");
PrintWriter out = response.getWriter();
out.println(fakeUser);
System.out.println(fakeUser)
I also tried the solution mentioned following Stackoverflow post but that didn't work either.
passing value from jsp to servlet
As you are trying to use hidden-form field I assume that you are trying to do some sort of state management.
try something like this
<form action="urlOfYourServlet" method="post">
Enter your name : <input type ="text" name = "name">
<input type="hidden" name="hidden" value="Welcome">
<input type="submit" value="submit">
</form>
In servlet
String getHiddenValue=request.getParameter("hidden");
String name=request.getParameter("name");
System.out.println(name+" Hidden field Value is :"+getHiddenValue);
Disadvantage :
Only textual information can be persisted between request.
This method works only when the request is submitted through input form
Instead try url-redirecting or HttpSession
I am trying to submit the text field value and print it using the servlet. The index.jsp is my main page and I am using jsp:include to include the form which reside in another page which is login.html.
here is the code i have for login.html
<form id="f1" action="ControllerServlet" method="GET">
<p>username
<input class ="text-input" type="text" id="txtusername" />
</p>
<p>
<input type="submit" value="submit" />
</p>
the index.jsp
<div id="col3_content" class="clearfix">
<h1>H1 Heading</h1>
<jsp:include page="login.html"></jsp:include>
</div>
the controller servlet
String usrname = request.getParameter("txtusername").toString();
out.print(usrname);
The problem is this is throwing a null pointer exception. what am I doing wrong here ? any help appreciated. thanks
Please use name not id
<input class ="text-input" type="text" name="txtusername" />
The id is not used to identify the name of the input parameter. The right attribute for the parameter is name, currently you are using an input without a name. So use
<input class ="text-input" type="text" name="txtusername" id="txtusername" />
You need to define name attribute of input tag to get it in Servlet by name.
<input class ="text-input" type="text" id="txtusername" name="txtusername" />
Also make sure you are writing code in doGet or service method of servlet as you have GET as action in form tag.
Code for Login.html
<form action="ControllerServlet" method="GET">
<p>username :
<input type ="text" name="txtusername" /></p>
<p><input type="submit" value="submit" /> </p>
</form>
ControllerServlet.java
public void service(ServletRequest request, ServletResponse response)
{
String username = request.getParameter("txtusername");
PrintWriter out = response.getWriter();
out.println("User Name " + username)
I faced a similar situation, when I checked front end, the form seems to have all the value populated correctly. However, after form.submit, from server side using request.getParameter("the parameter") does not return the value populated. After tuning on the network traffic tab in browser, I see the parameter was there, but there was a typo.
Hopefully could save you some time if same thing happens to you.