JSP pass hidden input value to servlet when the page load - java

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

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.

Passing parameter back from JSP in a portlet app

In my Liferay 6 app I'm able to pass parameter from java to jsp via:
final PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher("view");
request.setAttribute("description", "some description");
rd.include(request, response);
Then I want user to change the description and pass it back to back-end:
<form method="POST" action="${addItem}">
<input name="description"
type="text"
value="${description}"/>
<button type="submit">UPDATE</button>
</form>
Nevertheless when I call then System.out.println("request.getAttribute("description")); , I'm getting null. What am I doing wrong?
Youre passing in the parameter but checking the request attribute (assuming that the outer quotes are a question typo). Based on the information you provided, the initial request attribute was only available in the JSP but not any subsequent servlet. Try
System.out.println(request.getParameter("description"));

request.getParameter() says its null when not

Hi i have a servlet which get a parameter form a jsp on a submit button. One of the parameters is reporting to be null though. However this is not the case. The text input in question is filled automatically by a session variable and is definitely not null and can be seen in the text box on the page. But when inside the servlet the java console indicates that the variable is null? below is the code that populates the box and reads the parameter.
<input type="text" id="cID" value="<%= session.getAttribute("cID")%>" readonly="readonly">
reading the parameter:
String cID = request.getParameter("cID");
On printing cID to the console in netbeans it is reportedly null?
Add the name attribute to the input tag
<input type="text" id="cID" name="cID" value="<%= session.getAttribute("cID")%>" readonly="readonly">
It's the name attribute, not the id attribute, that defines the name of the parameter that's sent to the server. id is purely a client-side thing.
I think you need to write:
<input type="text" id="cID" value="<%= session.getAttribute(\"cID\")%>" readonly="readonly">

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>

form values not submitted to the servlet

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.

Categories