First of all, please have mercy for this noobie question. I’m currently working on a web application project and stumbled across this basic problem I can’t figure out to fix.
Basically, I have the following:
index.html sending a POST request to servlet1.
servlet1 sending a redirect to the browser to servlet2.
servlet2 to return content.
I do see the content returned from servlet2 in my browser, but when I look into IE Developer Tools (F12), I see that the GET request to servlet2 never finishes (STATUS PENDING). There must be something very basic that I’m missing…
In below screen shot, "Ausstehend" translates to "pending".
IE Screenshot:
index.html:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="servlet1" method="post">
<input type="text" name="test" placeholder="some data">
<button type="submit"><b>send</b></button>
</form>
</body>
</html>
servlet1:
public class servlet1 extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("servlet2");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
servlet2:
public class servlet2 extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet servlet2</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>HELLO</h1>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
Related
I am trying to do a JSP tutorial using Controller and models, is a simple form that receives some data, make one calculation and returns a text. The tutorial is n this youtube video:
enter link description here
But I tried to do the same instead in Netbeans in Eclipse. When I send the date I get this:
But I expected down the form to get the response of the data. This is my Code of controller:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html;charset=UTF-8");
Calcular obj = new Calcular();
obj.setNombre(request.getParameter("usuario"));
obj.setDireccion(request.getParameter("direccion"));
obj.setNumDiasTrabajados(Integer.parseInt(request.getParameter("dias")));
obj.setValorDia(Double.parseDouble(request.getParameter("valor")));
obj.Salario();
request.setAttribute("ObjetoJava", obj);
try (PrintWriter out = response.getWriter()){
//out.println("Controlador");
RequestDispatcher a=request.getRequestDispatcher("index.jsp");
a.forward(request, response);
}
}
This is the code in the index.jsp:
<%
Calcular obj = new Calcular();
obj = (Calcular)request.getAttribute("ObjetoJava");
if(obj != null){
out.println(obj.getNombre());
out.println(obj.getDireccion());
out.println(obj.getNumDiasTrabajados());
out.println(obj.getValorDia());
out.println(obj.getSalario());
}
%>
And this is the code that sends in Controlador.java:
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
What I did make wrong?
Controlador.java:
package ctr;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelo.Calcular;
/**
* Servlet implementation class Controlador
*/
#WebServlet("/Controlador")
public class Controlador extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html;charset=UTF-8");
Calcular obj = new Calcular();
obj.setNombre(request.getParameter("usuario"));
obj.setDireccion(request.getParameter("direccion"));
obj.setNumDiasTrabajados(Integer.parseInt(request.getParameter("dias")));
obj.setValorDia(Double.parseDouble(request.getParameter("valor")));
obj.Salario();
request.setAttribute("ObjetoJava", obj);
try (PrintWriter out = response.getWriter()){
//out.println("Controlador");
RequestDispatcher a=request.getRequestDispatcher("index.jsp");
a.forward(request, response);
}
}
/*
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Controlador() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
index.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="modelo.Calcular" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action = "Controlador" method = "POST">
<table>
<tr>
<td>Nombre</td><td><input type="text" placeholder="Nombre" name="usuario"/></td>
</tr>
<tr>
<td>Direccion</td><td><input type="text" placeholder="Direccion" name="direccion"/></td>
</tr>
<tr>
<td># Dias Trabajados</td><td><input type="text" placeholder="# Dias Trabajados" name="dias"/></td>
</tr>
<tr>
<td>Valor dias</td><td><input type="text" placeholder="Valor dia" name="valor"/></td>
</tr>
<tr>
<td><button type ="submit">Calcular</button></td>
</tr>
</table>
<%
Calcular obj = new Calcular();
obj = (Calcular)request.getAttribute("ObjetoJava");
if(obj != null){
out.println(obj.getNombre());
out.println(obj.getDireccion());
out.println(obj.getNumDiasTrabajados());
out.println(obj.getValorDia());
out.println(obj.getSalario());
}
%>
</form>
</body>
</html>
Your form method calls doPost:
When you click on submit it goes to '/Controlador' where it looks for doPost and in doPost the body call the doGet instead of calling doGet, You should call : processRequest
Try This:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html;charset=UTF-8");
Calcular obj = new Calcular();
obj.setNombre(request.getParameter("usuario"));
obj.setDireccion(request.getParameter("direccion"));
obj.setNumDiasTrabajados(Integer.parseInt(request.getParameter("dias")));
obj.setValorDia(Double.parseDouble(request.getParameter("valor")));
obj.Salario();
request.setAttribute("ObjetoJava", obj);
try (PrintWriter out = response.getWriter()){
//out.println("Controlador");
RequestDispatcher a=request.getRequestDispatcher("index.jsp");
a.forward(request, response);
}
}
/*
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Controlador() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
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>
Index.jsp
<form method="post" action="serv">
Enter Latest Reading <input type="text" name="t1"> <br>
Enter Previous Reading <input type="text" name="t2"> <br>
<input type="submit" value="SEND">
</form>
LoginServlet.java
#WebServlet("/serv")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("<u>Following are your Bill Particulars</u><br><br>");
req.setAttribute("unitRate", new Double(8.75));
req.getRequestDispatcher("/Test").include(req, res);
out.println("<br><br>Please pay the bill amount before 5th of every month to avoid penalty and disconnection");
out.close();
}
}
IncludeServlet.java
#WebServlet("/Test")
public class IncludeServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
int latestReading = Integer.parseInt(req.getParameter("t1"));
int previousReading = Integer.parseInt(req.getParameter("t2"));
Object obj = req.getAttribute("unitRate");
Double d1 = (Double) obj;
double rate = d1.doubleValue();
int noOfUnits = latestReading-previousReading;
double amountPayable = noOfUnits * rate;
out.println("Previous reading: " + previousReading); out.println("<br>Current reading: " + latestReading);
out.println("<br>Bill Amount Rs." + amountPayable);
}
}
When I run the above project, only the response of LoginServlet is displayed in a browser, I'm unable to include the response of IncludeServlet.java.
All System.out.println("") of LoginServlet is being display is console only, non from IncludeServlet.
I also use debugger, but this is not going into IncludeServlet.java page.
In your IncludeServlet instead of overriding doGet method override doPost , Since Post request is coming from HTML
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// do Whatever you want to do .
}
Update: Also write res.setContentType("text/html"); in both servlet so that your html written in out.print executes otherwise your output will look like <br><br>Please pay the bill amount before 5th of every month to avoid penalty and disconnection.
I want when my page such as index.jsp loading(calling get method) send data for index.jsp page such as title. I checked this question but this question solution(How to call servlet on jsp page load) has error in my web application.
This my index.jsp page code(I want send title from changeTitle.java class):
<title><c:import url="/sysAdmin/changeTitle.java" />
<c:out value="${message }"></c:out></title>
This my changeTitle.java class get method:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("message", "hello");
}
And I don't know how addressing to class in index.jsp of my project and bellow is my project directories:
Try setting the response, not the request
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setAttribute("message", "hello");
}
Try using this code:
<c:out value="<%=request.getAttribute('message')%>">
I hope you can help handle problem with endless loop in servlet. Such problems usually causes wrong servlet-mapping (usualy it's "/*"). But in my case, it has specific value - name of conrete jsp file.
Servlet:
public class TrainsListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
EmployeeService employeeService = new EmployeeServiceImpl();
List<Train> trains = (List<Train>) employeeService.getTrains();
request.setAttribute("trains", trains);
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher("/getTrainsList.jsp");
dispatcher.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);
}
}
web.xml:
...
<servlet>
<servlet-name>TrainsList</servlet-name>
<display-name>TrainsList</display-name>
<description></description>
<servlet-class>ru.tsystems.jsproject.sbb.Servlets.TrainsListServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TrainsList</servlet-name>
<url-pattern>/getTrainsList.jsp</url-pattern>
</servlet-mapping>
...
getTrainsList.jsp:
...
<c:forEach var="train" items="${trains}">
<tr>
<td><c:out value="${train.getNumber()}" /></td>
<td><c:out value="${train.getSeatsCount()}" /></td>
<td><c:out value="${train.getFrequence()}" /></td>
</tr>
</c:forEach>
...
it's all causes endless loop in processRequest method. Please help,
tell me what I am doing wrong?
Map it with html file
<servlet-name>TrainsList</servlet-name>
<url-pattern>/getTrainsList.html</url-pattern>
And follow http://localhost:8080/.../getTrainsList.html and you will get as response from Servlet getTrainsList.jsp