Wrong response from controller JSP - java

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);
}

Related

How to print out variable values in servlets on HTML pages?

I would like to print out my current variable value on my HTML page. I cannot seem to figure it out. On my HTML page, I want to print out the current Exchange rate.
This is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Calculator</title>
</head>
<body>
<form action="Converter" method="get" name="frm">
Amount:
<input name="amount" type="text" />
Rate:
<input name="conversionRate" type="text" />
<input type="submit" value="Convert!" />
<br>Current Rate:
</form>
</body>
</html>
My Java Code
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Converter
*/
#WebServlet("/Converter")
public class Converter extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Converter() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
String n2 = "1.0";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String n1 = request.getParameter("amount");
String tempStr;
tempStr = request.getParameter("conversionRate");
if(!tempStr.isBlank()) {
n2 = tempStr;
}
if(n2.equals("tempStr")){
out.println((Integer.parseInt(n1) / Double.parseDouble(n2)));
}
else if(n2.equals(n2)){
out.println("test");
out.println((Integer.parseInt(n1) / Double.parseDouble(n2)));
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
How can I print out the current rate. Which in this case is n2 on my HTML page? I want it to update on each load of the website. But I cannot figure out how to print out the variable value through the HTML page.
You can use your PrintWriter instance to print the whole HTML into the response object, example:
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Bla</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>");
out.println("Your current rate is: ");
//Your Java code here
String n1 = request.getParameter("amount");
String tempStr;
tempStr = request.getParameter("conversionRate");
if(!tempStr.isBlank()) {
n2 = tempStr;
}
out.println(n2);
out.println("</h1>");
out.println("</body>");
out.println("</html>");
}
Hope that helps.

GetParts() returning null in servlet

Hello guys i'm facing a problem with my code, i have a jsp form that send a file into a servlet, and when i try to extract the file using request.getParts() it return null value wheni try to print it to the console, can anyone help me please. here is my code.
my jsp:
<!DOCTYPE html>
<html lang="en">
<head>
<title>File Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="POST" action="/PartsServlet" enctype="multipart/form-data" >
File:
<input type="file" name="file" id="file" /> <br/>
Destination:
<input type="text" value="/tmp" name="destination"/>
</br>
<input type="submit" value="Upload" name="upload" id="upload" />
</form>
</body>
</html>
My servlet:
package Servv;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class PartsServlet
*/
#WebServlet("/PartsServlet")
public class PartsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public PartsServlet() {
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());
System.out.println("Get Parts "+request.getPart("file"));
System.out.println("Get Parts "+request.getPart("destination"));
}
/**
* #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);
}
}
Add #MultipartConfig annotation.
Always parse your request body only once and store it in a list.
so that one part cannot consume it.
List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collectors.toList());
for (Part part : fileParts) {
}
File uploads = new File("/path/to/uploads");
File file = File.createTempFile("somefilename-", ".ext", uploads);
try (InputStream input = part.getInputStream()) {
Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

Why am I getting null value while using "sendReditect" in servlet as per below

Why am I getting null value while using "sendReditect" in servlet as per below
my code as per below : I am getting fname value null even in both FirstServlet and SecondServlet
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="FirstServlet" method="get">
username<input type="text" name="fname"></br> <input type="submit"
value="SUBMIT">
</form>
</body>
</html>
FirstServlet:
package com.naveen;
import java.io.IOException;
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;
/**
* Servlet implementation class FirstServlet
*/
#WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
String s3=request.getParameter("fname");
// TODO Auto-generated method stub
/*String s1=request.getParameter("t1");*/
/*RequestDispatcher rd=request.getRequestDispatcher("SecondServlet");
rd.forward(request, response);*/
res.sendRedirect("SecondServlet");
System.out.println("your output as per" +s3);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
SecondServlet:
package com.naveen;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SecondServlet
*/
#WebServlet("/SecondServlet")
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String s3=request.getParameter("fname");
out.print("hi i am siddharth");
out.println(s3);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
why i am getting null value while using "sendReditect" in servlet as
per below my code as per below : i am getting fname value null even in
both FirstServlet and SecondServlet,
Because you're not setting any values to your request. You need to set the value to the request like this:
#WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
String s3=request.getParameter("fname"); //get the value you set in your jsp/html/url
request.setAttribute("fname", s3); // set the s3 value to the request
res.sendRedirect("SecondServlet");
System.out.println("your output as per" +s3);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
I'm assuming here you have sent the fname value via a form or something. If you call FirstServlet by just typing it in the url, you will get null.
But not if you set something, try it like this if you are not submitting a form:
/FirstServlet?fname=helloworld
EDIT:
just noticed in your form you're not actually setting fname with any value. You need to give it a value:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="FirstServlet" method="get">
username<input type="text" name="fname" value="helloworld"></br> //add value to your input!!
<input type="submit" value="SUBMIT">
</form>
</body>
</html>

Java Servlet response doesn't seem to finish

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);
}
}

posting values to textbox using java servlet in Eclipse

I am creating a java servlet which should get a number from a textbox (created using using HTML) calculate its factorial and when i will press submit button (also created using HTML) it should calculate and display the factorial in another textbox which i have created.
Problem I have successfully retrieved the number from the first textbox (using request.getParameter) and calculated it factorial. Now the problem is that i am unable to post the calculated factorial in that 2nd textbox.
Plz help me what should i do?
Thank in advance!
Here is the code:
servlet:
package factorial;
import java.io.*;
import javax.servlet.Servlet;
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 org.apache.jasper.tagplugins.jstl.core.Out;
/**
* Servlet implementation class fact
*/
#WebServlet("/fact")
public class fact extends HttpServlet implements Servlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public fact() {
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
PrintWriter out = response.getWriter();
long number = Long.parseLong((request.getParameter("num")));
long fact=1;
while(number>1){
fact=fact*number;
number--;
}
//request.setAttribute("factorial", fact); //***this is not working***
//out.println(fact);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Factorial</title>
</head>
<body>
<form action="fact" method="get">
Enter a number: <input type="text" name="num">
<input type="submit"/>
Factorial <input type="text" id="factorial" name="factorial"/>
</form>
</body>
</html>
store the value in request or session attributes as request.setAttribute("name",value) or session.setAttribute("name", value). and in JSP, retrieve them using request.getAttribute("name") or session.getAttribute("name")

Categories