Servlet to JSP always passing null value - java

I just started using JSP and Servlet, so I encountered a really basic problem.
I'm trying to make a request from JSP to servlet, where I set a parameter and then forward the answer from servlet back to the jsp.
Here is the code from my JSP:
<% String s = (String)request.getAttribute("name");
out.println(s);
%>
Here is my code from servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try (PrintWriter out = response.getWriter()) {
request.setAttribute("name", new String("aa"));
this.getServletContext().getRequestDispatcher("/index.jsp").forward(request,response);
}
}
So in the end, the servlet has the value, but my jsp doesn't.

Here you have already declared a String type but you cast it as String also, this is redundant.
<% String s = (String)request.getAttribute("name");
out.println(s);
%>
Also, there's a difference between <%= %> and <% %>. If you want to output the variable into your jsp use the one with the equals (<%= %>). The second line of your scriptlet code would also generate an error. The code you write in your servlet doesn't just continue on the JSP, it's not how it works.
if you want to output the name attribute just do this:
<%= request.getAttribute("name") %>
However since 2010 scriptlets are discouraged (outdated technology).. We use EL and JSTL instead. You should be able to just output the variable like this:
${name}
In your Servlet all you need to do is this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = "Jane"; //create a string
request.setAttribute("name", name); //set it to the request
RequestDispatcher rs = request.getRequestDispatcher("index.jsp"); //the page you want to send your value
rs.forward(request,response); //forward it
}
EDIT
You asked,
Is there a way to trigger the servlet let s say on a click of a button
or something like that?
Yes, there are multiple ways to do it and it really depends on how you want it setup. An easy way to trigger the servlet on a button click is like this. *(Assuming you have a servlet mapped onto /Testing):
<a href="/Testing">Trigger Servlet<a>
Another way could be with a form:
<form action="Testing" method="get">
<input type="hidden" name="someParameterName" value="you can send values like this">
<button type="submit">Do some magic</button>
</form>
There's also AJAX (which involves javascript). But this is fairly advanced and i don't recommend doing it until you are familiar with normal synchronous http behaviour.

Try without a writer, you don't want two writing contexts to a single response. You are also not using it:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("name", new String("aa"));
this.getServletContext().getRequestDispatcher("/index.jsp").forward(request,response);
}

I think you should call the request dispatcher method using request object. This is how you do it :
RequestDispatcher rs = request.getRequestDispatcher("index.jsp");
rs.forward(request,response);

Related

Passing parameter from JSTL to servlet through <a href> and jstl tags

So this is the code i'm using to send the parameter "idemp" that contains the value ${masession.idemp}
<a href="<c:url value="/consultertickets">
<c:param name="idemp" value="${masession.idemp}"/>
</c:url>">
<img src="<c:url value="/inc/liste.png"></c:url>" alt="consulter tickets" />
</a>
when redirected to the servlet "/consultertickets" the browser URL shows:
http://localhost:4040/monprojet2/consultertickets?idemp=64
so the parameter is passed and working but the method used to obviously GET and not POST, which is the method i'm using in the servlet, here's the servlet's code.
#WebServlet(urlPatterns= {"/consultertickets"})
public class ConsulterTickets extends HttpServlet {
private String VUE = "/WEB-INF/ListeTickets.jsp";
#EJB
private TicketDao ticketDao;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CreationTicketForm ticketform = new CreationTicketForm(ticketDao);
List<Ticket> lticket = ticketform.recupererTickets(request);
boolean resultat;
if(lticket.isEmpty())
{
//resultat="Vous n'avez soumit aucun ticket";
resultat = false;
request.setAttribute("resultat", resultat);
this.getServletContext().getRequestDispatcher("/ListeTickets2.jsp").forward(request, response);
}else{
//String VUE = "/ListeTickets.jsp";
resultat=true;
request.setAttribute("resultat", resultat);
request.setAttribute("lticket", lticket);
this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
}
}
}
is there any way to pass a parameter to a servlet through POST method, without going through the <form></form>
Solution 1:
Modifying doGet method
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
doPost(request, response);
}
Solution 2:
Remove the doGet() and change doPost() to service()
Edit1:
See, Hyperlinks(<a> tag) are meant to send GET request but not POST.
So, if you want to achieve sending POST request using Hyperlink there is no straight way. But, Javascript can be your help.
Using Javascript you can guide <a> to send POST request along with the help of <form>.
I just modified your code little bit. This should help you.
<a href="javascript:document.getElementById('form1').submit()">
<img src="<c:url value="/inc/liste.png"></c:url>" alt="consulter tickets" />
</a>
<form action="<c:url value="/consultertickets"/>" method="post" id="form1">
<input type="hidden" name="idemp" value="${masession.idemp}"/>
</form>

JSP servlet not executing doPost method

I have recently started programming in java and have been trying out some JSP development. I am trying to make a login page which uses the POST method to transfer data to the servlet. Here is my code:
<form method="POST" name ="loginForm" action="userAuth">
<input type="hidden" name="userAction" value="login">
Username: <input type="text" name="txtUsername"> <br>
Password : <input type="password" name="txtPassword">
<br><input type="submit" value="Login">
</form>
The above code is from the initial login page.
The code below is from the userAuth.java file.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
String userAction = request.getParameter("userAction");
if (userAction.equals("Login")) {
String userName = request.getParameter("txtUsername");
String passWord = request.getParameter("txtPassword");
if (userName.equals("hello") && passWord.equals("hello")) {
response.sendRedirect("Homepage.jsp");
}
}
}
The problem I have is that when I input the correct username and password, the doPost method is not executed, so none of the redirects take place. Rather only the ProcessRequest method is executed which just displays the initial template to the web browser.
Thank you in advance.
P.S I am using Apache Tomcat 8.0.27.0
I have solved the issue...
The issue was with the following line
<input type="hidden" name="userAction" value="**login**">
and the subsequent processing in the second block:
if (userAction.equals("**Login**")) {}
The login value didnt have an uppercase L.
Just changed this.
What does the processRequest() method do? If executes as you say then the server gives a response to the client and the remaining block of code does not execute. Have you tried to run without this function?
Hide the process request method.
Like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
String userAction = request.getParameter("userAction");
if (userAction.equals("Login")) {
String userName = request.getParameter("txtUsername");
String passWord = request.getParameter("txtPassword");
}
}

Passing a Java Result to JSP

I have recently been thrown into the wonderful world of programming websites with Java. I have a little experience with Java but would still consider myself a beginner.
I have created a Java class that has a simple SQL query in it. I am trying to display onto a JSP page but am unsure on how to achieve this.
Here is my Java class called Main.java:
public static void main(String[] args) throws Exception {
//Accessing driver from JAR
Class.forName("com.mysql.jdbc.Driver");
//Creating a variable for the connection called "con"
//jdbc:mysql://host_name:port/dbname
//Driver name = com.mysql.jdbc.Driver
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
PreparedStatement statement = con.prepareStatement("select name from user");
ResultSet result = statement.executeQuery();
while(result.next()) {
System.out.println(result.getString(1));
}
}
How would I get system.out.println on a JSP page?
If you need to save results and display to JSP .
save the results in request and in view layer iterate using JSTL to display the result.
which means , in servlet get the request and forward it new jsp
I recommend to use JSF instead JSP ,
JSP also allows you to write blocks of Java code inside the JSP. You do this by placing your Java code between <% and %> characters.
A scriptlet contains Java code that is executed every time the JSP is invoked.
Here is a link to simple jsp web app that should help you to get started.
http://j2ee.masslight.com/Chapter1.html#mygreeting
you could use below sample code as a reference.
JSP page
<form action="servlet1" method="get">
<% ModelClass class = new ModelClass();
class.connectDb();
class.performDBoperations();
%>
<table><tr><td>
<%
class.id;
%>
</form>
Model Class:
class ModelClass {
int id;
public static void connectDb() {
dbConnection code
}
public void performDBoperations() {
get info from table with SQL thru JDBC.
id=update it;
}
A basic concept in web programming is that you don't start actions from a method (main or any other). Someone request's a JSP or servlet and the corresponding class answers. You can do both things in a JSP and leave the work of connecting to a database to an auxiliar class as #chaitanya10 answer shows.
The Nebeans tutorial for JSP's is not a bad starting point. There are several JSP/Servlets tutorial in the web, but I'd recommend to stay away from the Java EE tutorials.
For the example you post, what you need to do is program a servlet, in that servlet you would have your business logic calls (in this case the data base query), after getting the data, you have to pass it to the JSP page. With servlets there is no need for main method, but they must be deployed in a servlet container (like Tomcat).
Here is the code:
public class UserListServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Accessing driver from JAR
Class.forName("com.mysql.jdbc.Driver");
//Creating a variable for the connection called "con"
//jdbc:mysql://host_name:port/dbname
//Driver name = com.mysql.jdbc.Driver
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
PreparedStatement statement = con.prepareStatement("select name from user");
ResultSet result = statement.executeQuery();
//creates a list with the user names
List<String> userList = new ArrayList<String>();
while(result.next()) {
userList.add(result.getString(1));
}
//passing the data to the JSP
request.setAttribute("users", userList);
getServletContext().getRequestDispatcher("/user_list.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
Now in the JSP you could have something like this:
<%# page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import="java.util.List" %>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User List</title>
</head>
<body>
<%
if (request.getAttribute("userList") != null) {
List<String> users = request.getAttribute("userList");
%>
<h1>Users: </h1>
<table>
<tr>
<td>Name<</td>
</tr>
<% for (String name : users) {%>
<tr>
<td><%= name%></td>
</tr>
<% }
}%>
</table>
</body>
</html>
You can improve this example by using JSTL instead of Scriptlets (<% ... %>).
Are you sure that is this good way to create java websites?
Ask google for Java EE, Servlets and get into it.

How can I pass object from servlet to JSP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to pass an Object from the servlet to the calling JSP
How can I pass object from servlet to JSP?
I have used the following code in the servlet side
request.setAttribute("ID", "MyID");
request.setAttribute("Name", "MyName");
RequestDispatcher dispatcher = request.getRequestDispatcher("MangeNotifications.jsp");
if (dispatcher != null){
dispatcher.forward(request, response);
}
and this code in JSP side
<td><%out.println(request.getAttribute("ID"));%> </td>
<td><%out.println(request.getAttribute("Name"));%> </td>
I get null results in the JSP Page
I think servlet's service (doGet/doPost) method is not requested. In order to access request attributes in JSPs, you must request the servlet via url-pattern and that way you don't have to use session.
SampleServlet.java
#WebServlet(name = "SampleServlet", urlPatterns = {"/sample"})
public class SampleServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("ID", "MyID");
request.setAttribute("Name", "MyName");
RequestDispatcher dispatcher = request
.getRequestDispatcher("/MangeNotifications.jsp");
if (dispatcher != null){
dispatcher.forward(request, response);
}
}
}
MangeNotifications.jsp (I presume that this file is located at root of web-context)
<br/>ID : ${ID} Or scriptlets <%-- <%=request.getAttribute("ID")%> --%>
<br/>ID : ${Name}
Now open the browser and set request url somersetting like this,
http://localhost:8084/your_context/sample
Put it in the session (session.setAttribute("foo", bar);) or in the request; then it is accessible from the JSP through the name you gave it ("foo" in my example).
EDIT :
Use simply <%= ID %> and <%= Name %> instead of <%out.println.....%>. Note the = at the beginning of the java tag, indicating to output the result of the expression.

reading the form data in servlet. data posted with post method and servlet called with ?q=test1

Hey I am trying to read the form data in a servlet sent with post method. And the servlet is called as OnlineExam?q=saveQuestion. Now the servlet is working as:
public class OnlineExam extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("q").equals("saveQuestion")){
/*
* Save the question provided with the form as well as save the uploaded file if any.
*/
saveQuestion(request);
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// doGet(request, response);
saveQuestion(request);
}
public String saveQuestion(HttpServletRequest request){
System.out.println(request.getParameter("question"));
return "";
}
}
HTML form:
<form action="OnlineExam?q=saveQuestion" method="post">
<fieldset>
<legend>Question</legend>
<textarea class="questionArea" id="question" name="question">Enter Question.</textarea>
<br class="clearFormatting"/>
<input class="optionsInput" value="optionA" name="optionA" onfocus = "clearValues('optionA')" onblur = "setValues('optionA')"/>
<br class="clearFormatting"/>
<input class="optionsInput" value="optionB" name="optionB" onfocus = "clearValues('optionB')" onblur = "setValues('optionB')"/>
<br class="clearFormatting"/>
<input class="optionsInput" value="optionC" name="optionC" onfocus = "clearValues('optionC')" onblur = "setValues('optionC')"/>
<br class="clearFormatting"/>
<input class="optionsInput" value="optionD" name="optionD" onfocus = "clearValues('optionD')" onblur = "setValues('optionD')"/>
<br/>
<input class="optionsInput" value="answer" name="answer" onfocus="clearValues('answer')" onblur="setValues('answer')"/>
<input type="submit" value="Save" />
<input type="reset" value="Cancel" />
<button style="display: none" onclick="return deleteQuestion()" >Delete</button>
</fieldset>
</form>
So can anyone illustrate how the servlet is actually called. I mean what is the flow of control i.e. how the things works in this servlet.
And how could i read the param1 there in servlet.
ps: i don't want to post form with get method.
You should get the value of q in your doPost not in your doGet. Because you use method="post" then in the servlet the doPost is the one that called not the doGet. Remove the code in your doGet then insert it to doPost. And you doPost must be something like below code.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("q").equals("saveQuestion")){
saveQuestion(request);
}
}
Is this solved ?
I am facing same problem.
I tried
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
System.out.println((String)paramNames.nextElement());
}
and it's showing 0 elements, so form data is not being read by servlet.
I got the answer in other thread.
enctype=multipart/form-data was causing this. After removing it from form, was able to read data.
if you POST data to servlet.
doPost will get invoked.
Inside doPost() you can access request param like
request.getParameter("param1");
When you click the "submit" button on your form, the doPost method of your servlet will be called - this is dictated by the method that you put on the "form" in your HTML page. The URL parameters ( q=saveQuestion ) will still be available to your code in the doPost method. You seem to be under the impression that the URL parameters will be processed by the doGet method and the form parameters by the doPost method. That is not the case.
doPost() {
processRequest(request, response);
//to do
}
Remove/comment processRequest(request, response) and try it again. Now you should not get null values.
I know this is an old thread but could not find an answer to this when I searched so I am posting my solution for someone who may have the same issue with getting null from form parameters in the dopost function of their servlet.
I had a similar issue getting null values when using the request.getParameters("param1"); functions. After hours of playing around with it I realized that the param1 that I was using was the ID for the input tag I was requesting. That was wrong. I had to use the NAME attribute of the input tag to get the correct value of the input box. That was all it was. I just had to add a name and get the parameter using this name and that fixed the issue.
Hope this helps someone.
Vinit try the below code
request.getParameter("param1");

Categories