JSP doesn't pass values on request - java

I'don't understand why servlet doesn't pass values to .jsp file. If somebody could explain my, why it works only when a call request.getSession.setAtribute() method. What should i do to avoid creating session.
Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
moviesList(request, response);
if (request.getParameter("command").equals("ADD"))
addMovie(request, response);
if (request.getParameter("command").equals("DELETE"))
deleteMovie(request, response);
if (request.getParameter("command").equals("SEARCH_IN_TMDB"))
searchInTmdb(request, response);
} catch (Exception e) {
e.getMessage();
}
}
private void searchInTmdb(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<MovieDb> movieDbs;
String title = request.getParameter("title_themoviedb");
String year = request.getParameter("year_themoviedb");
System.out.println("title " + title + " year " + year);
int year_int = Integer.parseInt(year);
movieDbs = TheMovieDbApiUtil.getInstance().getListFoundMovies(title, year_int);
request.getSession().setAttribute("TMDB_LIST", movieDbs);
RequestDispatcher dispatcher = request.getRequestDispatcher("/movie-list.jsp");
dispatcher.forward(request, response);
}
JSP file:
<div class="row top-buffer">
<form action="ServletMovieController" method="get">
<input type="hidden" name="command" value="SEARCH_IN_TMDB">
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
<button type="submit">Szukaj...</button>
<input type="text" name="title_themoviedb" title="title_themoviedb" class="form-control">
<input type="text" name="year_themoviedb" title="year_themoviedb" class="form-control">
<ul class="list-group" id="myList">
<c:forEach var="tempMovieTmdb" items="${TMDB_LIST}">
<li class="list-group-item">${tempMovieTmdb.getTitle()}</li>
</c:forEach>
</ul>
</input>
</div>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3">
</div>
</form>
</div>
As I mentioned before it works when I use requset.getSession(), but whitout it passed value is null.

I think i've understood what is going wrong and it's a common mistake people make when they first start out with the servlet/jsp request flow.
As someone has already mentioned you need to swap out
request.getSession().setAttribute("TMDB_LIST", movieDbs);
with:
request.setAttribute("TMDB_LIST", movieDbs);
Now the reason why you're getting null, is because you're not running the servlet. You're trying to access the jsp directly and expecting the request variable to be there. That's not how servlet/jsp request flow works. The servlet sets the request variable "TMDB_LIST" and it forwards this variable to the jsp page ("/movie-list.jsp"). Once you go to a different page the variable expires and will be null. If you try and access the jsp directly, it will just be null because you need the servlet to pass the variable to the jsp. I'm guessing this is what you're doing or you have a redirect after reaching the jsp.
Session variables are different in that the variables you set persist across the whole application/website (until you delete them or change them), for as long as the server specifies.
Request variables are only available after the first request. (i.e. servlet passes request variables to the jsp or the jsp passes request variables to the servlet)

if you want to avoid using Session, in your servlet, use
request.setAttribute("TMDB_LIST", movieDbs);

Related

How to map submit button of a JSP to a servlet to?

I am old to JAVA but very new to the topics of JSPs & Servlets. I am trying to do some jdbc operations by taking the values from JSP into servlet. To do that, I have written a JSP with a drop down list and a submit button.
Jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<div align='left' >
<div align='left' >
<label class="text-white mb-3 lead">Which report do you want to generate?</label>
<select id="reportSelection" data-style="bg-white rounded-pill px-5 py-3 shadow-sm " class="selectpicker w-100" name="reportselection">
<option>Outage</option>
<option>DataQuality</option>
<option>Latency</option>
</select>
</head>
<body>
<p id = "demo"> </p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</body>
</div>
</div>
</body>
<hr class="colorgraph">
<div class="row">
<div class="col-xs-12 col-md-6"><input type="submit" value="Submit" class="btn btn-primary btn-block btn-lg register" tabindex="7"></div>
</div>
</body>
</html>
And this is how my servlet class looks like.
#WebServlet("/getdata.do")
public class DataServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
GetTableColumn gt = new GetTableColumn();
String issue = request.getParameter("reportSelection");
String message;
try {
if ("Latency".equals(issue)) {
message = gt.process("latency");
} else if ("DataQuality".equals(issue)) {
message = gt.process("DataQuality");
System.out.println("Data quality");
} else if ("Outage".equals(issue)) {
message = gt.process("Outage");
}
} catch (SQLException s) {
s.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
I am reading the JSP drop down values in my servlet class and passing a String to method process based on the value received. I looked online to configure the web.xml file as below.
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>DataServlet</servlet-name>
<display-name>DataServlet</display-name>
<description>Begin servlet</description>
<servlet-class>com.servlets.DataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DataServlet</servlet-name>
<url-pattern>/parse</url-pattern>
</servlet-mapping>
I am trying to run the code on IntelliJ and here is how I have configured my tomcar server on IntelliJ.
When I run the code, I see the page is generating the jsp as expected.
What I don't understand is how to configure the submit with onclick so that I click on submit and the java program in the backed triggers. I have written the java code just to read values from a database by taking the input from the method process. This was running fine and I was asked to take the input from JSP and display the result back on a JSP.
When I click on submit button, I don't see any progress in the console output. I guess I didn't map it correctly.
Most of the links online contain JSP & JAVA together which is even more confusing.
Could anyone let me know how can I trigger the program by clicking the submit button
Since you are using #WebServlet, you do not need mapping in web.xml. Just add the following line inside body of your JSP:
<form action="getdata.do" method="post">
Look at your JSP file, pay attention at your head and body tag. I think it's a wrong that you have body inside other body and closing head tag inside body.
Other case that can be more important that to send a form by clicking to submit button you should put it inside tag form, something like this.
<form action = "getdata.do" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>

`null` result from request in servlets

I am new in servlets-
I am filling text in form but value in request is null-
In login page-
<body>
<form action="">
<input type="text" name="uname">
<input type="text" name="pwd">
link
</form>
</body>
In DisplayPage-
<body>
Display:
<%
String uname=(String)request.getParameter("uname");
String upass=(String)request.getParameter("pwd");
out.println(uname+" - "+upass);
Enumeration<String> enumeration = request.getParameterNames();
boolean b=enumeration.hasMoreElements();
out.println(b);
while (enumeration.hasMoreElements()) {
String name = (String) enumeration.nextElement();
String data=(String)request.getParameter(name);
out.println(name+" - "+data);
}
%>
</body>
Now in my result value of uname and upass is null and hence boolean b is false.Weird!
My Question Is- If request object is created when we use anchor tag since there is no NPE on calling getParameter() on request object,so what kind of data attached with this request object.why this is provided to us?
Because you are not submitting your form to server or not passing any value in url, instead you are clicking on link, which will redirect it to your link.
<body>
<form action="display.jsp"> // added action
<input type="text" name="uname">
<input type="text" name="pwd">
<button type="submit">Link</button> // added submit button
</form>
</body>
For Updated Question
On server side every request is handled as HttpServletRequest object. So when we submit the form, every input field is submitted and then it is retrieved from the request object on server side.

message after form validation

I have a JSP page which has several input fields and a servlet validates the fields when I click on the submit button and redirects to another page.
I would like to add a popup window: "all the fields are ok" after a correct server-side validation.
So I started with:
<form ="alert('success');">
<input type="submit" value="submit">
</form>
The problem is that "success" is printed even if the fields are incorrect.
I thought about setting a parameter in the
protected void doPost(HttpServletRequest request,HttpServletResponse response, which calls an execute() function to say if things are OK or not but I do not know how to get this parameter just after the submit so I could make a conditional:
if (checkSubmitParameter == OK )
callsPopup()
Try something like this (see jsfiddle):
<script>
function checkit(){
var val = document.getElementById('txt').value;
if(val == "good"){
alert("success");
}else{
alert("failure!");
}
}
</script>
<form onsubmit='checkit()'>
<input type='text' id="txt" />
<input type='submit' value='Submit' />
</form>

How do I show error information in web form?

This question is related to this. But since I haven't solved that question yet, I want to restate my problem a bit. I'm using Java Jersey REST API as my backend web service. The client side is a simple web form HTML page. Basically what I want is: If the user submits a web form and there are some errors caused by database unique constraint violation, I want the user to see an error message showing along with the id field in the form such as "ID already exists!". The web form is a simple form.html:
<form action="/myapp/rest/customer/created" method="POST">
<table border="1">
<tr>
<td>Customer name:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Customer ID:</td>
<td><input type="text" name="id"></td>
</tr>
<tr>
<td>Customer DOB:</td>
<td><input type="text" name="dob"></td>
</tr>
</table>
<br/>
<input type="submit" value="Submit">
</form>
If there is an error occurred, how to pass the error information from Jersey API to the client-side? My server-side POST call associated with this form submission is as follows:
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Path("created")
public Response createCustomer(#FormParam("id") int id,
#FormParam("name") String name, #FormParam("dob") Date dob)
throws ServletException, IOException {
URI uri = URI.create(uriInfo.getPath());
Response r;
r = Response.created(uri).build();
try {
dbController.create(id, name, dob); //This may throw exception.
} catch (DataAccessException ex) {
//To do: How to pass the error message to the client-side UI via e.g., Ajax?
}
return r;
}
First of all add this somewhere in your code. It will display the error message:
<span id="errorDiv" name="errorDiv" class="errorDiv" ></span>
Next, modify your form declaration as:
<form action="/myapp/rest/customer/created" method="POST" onsubmit="return checkForm()">
Before submitting the form it will call checkForm() function. if the function returns true then it will post the form. if not then it will prevent form from submission and display error message.
Assuming that you are submitting the form contents by using jQuery/AJAX calls. You can return a String(default value = 'success') from the server. In case there is an error change the specific string and return it and check the value client-side.
responseTxt is the value returned.
function checkForm(){
//get values from form
var name= $("#name").val();
var id= $("#id").val();
var dob= $("#dob").val();
$.post('DESTINATION',{name:name,id:id,dob:dob},function(responseTxt) {
//MAKE YOUR CHECK HERE. JUST AN EXAMPLE
if (responseTxt.substring(0,4)=='succ'){
//redirect to destination
return true;
}else{
//display error in errorDiv span
$('#errorDiv').html('<font color=red>Wrong username or password.</font>');
//prevents form to be submitted
return false;
}
});
}
Hope it helps

How to pass a session value as request parameter from JSP to servlet?

<c:forEach var="it" items="${sessionScope.projDetails}">
<tr>
<td>${it.pname}</td>
<td>${it.pID}</td>
<td>${it.fdate}</td>
<td>${it.tdate}</td>
<td> Related Documents</td>
<td>${it.pdesc}</td>
<form name="myForm" action="showProj">
<td><input id="button" type="submit" name="${it.pID}" value="View Team">
</td>
</form>
</c:forEach>
Referring to the above code, I am getting session object projDetails from some servlet, and displaying its contents in a JSP. Since arraylist projDetails have more than one records the field pID also assumes different value, and the display will be a table with many rows.
Now I want to call a servlet showProj when the user clicks on "View Team" (which will be in each row) based on the that row's "pID".
Could someone please let me know how to pass the particular pID which the user clicks on JSP to servlet?
Instead of an <input> for each different pID, you could use links to pass the pID as a query string to the servlet, something like:
View Team
In the showProj servlet code, you'll access the query string via the request object inside a doGet method, something like:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String pID = request.getParameter("pID");
//more code...
}
Here are some references for Java servlets:
HttpServletRequest object
Servlet tutorials
Pass the pID along in a hidden input field.
<td>
<form action="showProj">
<input type="hidden" name="pID" value="${it.pID}">
<input type="submit" value="View Team">
</form>
</td>
(please note that I rearranged the <form> with the <td> to make it valid HTML and I also removed the id from the button as it's invalid in HTML to have multiple elements with the same id)
This way you can get it in the servlet as follows:
String pID = request.getParameter("pID");
// ...
Define onclick function on the button and pass the parameter
<form name="myForm" action="showProj">
<input type='hidden' id='pId' name='pId'>
<td><input id="button" type="submit" name="${it.pID}" value="View Team" onclick="populatePid(this.name)">
</td>
.....
Define javascript function:
function populatePid(name) {
document.getElementById('pId') = name;
}
and in the servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String pID = request.getParameter("pId");
.......
}

Categories