How can I process data that is transferred in the body of a GET-request using a servlet?
I use a small, hosted vServer (netcup), running Ubuntu 18.04 Server as OS and Tomcat 9.
To simulate the http requests I use Postman. In the code example below(its only the doGET-method) i realized a little program, that processes the incoming data "value1" from the query-string of the incoming GET-request. When i try to transmit the same parameter in the body of the message, i get the following error:
HTTP Status 500 ? Internal Server Error
Type: Exception Report, Message: null
Description: The server encountered an unexpected condition that prevented
it from fulfilling it from fulfilling the request
java.lang.NumberFormatException: null
java.lang.Integer.parseInt(Integer.java:542)
java.lang.Integer.parseInt(Integer.java:615)
myServlet1.doGet(myServlet1.java:25)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
How do I have to modify the code to allow transmission via the GET-body? If i transmit the data with the querystring (for example) "http://localhost:8080...?value1=10" then it works fine.
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;
#WebServlet("/myServlet1")
public class myServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
public myServlet1() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
String value1s= request.getParameter("value1");
int a=Integer.parseInt(value1s); //
a=a+10;
writer.println("<html>");
writer.println("<head><title>Hello World Servlet</title></head>");
writer.println("<body>");
writer.println(" <h1>Hello value from a Servlet!</h1>");
writer.println("<h1>transmitted value: " + a + "</h1>");
writer.println("<body>");
writer.println("</html>");
writer.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
I am very grateful for every tip and hint!
Related
In NetBeans / Java - exception breakpoint (for Throwable) does not catch exceptions (RuntimeException in code of library for servlet). If you search tediously, you can find a purple stop line but without looking into the state of variables, etc. VS.NET does not have such ailments - it stops where you need it and everything is clear.
Is this a NetBeans problem or Java? How to get rid of breakpoint problems?
In here example would give you basic understanding of Exception Handling in Servlet
Actually putting a break point you can not catch a servlet exception because of it is happening before reaching the end point then you have to do something like this
When a servlet generates an error developers can handle those exceptions in various ways
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;
#WebServlet("/SampleExceptionHandler")
public class SampleExceptionHandler extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
exceptionProcessor(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
exceptionProcessor(request, response);
}
private void exceptionProcessor(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// Analyze the servlet exception
Throwable throwable = (Throwable) request
.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
String servletName = (String) request
.getAttribute("javax.servlet.error.servlet_name");
if (servletName == null) {
servletName = "Unknown";
}
String requestUri = (String) request
.getAttribute("javax.servlet.error.request_uri");
if (requestUri == null) {
requestUri = "Unknown";
}
}
}
I'm running Apache Tomcat 8 on Eclipse Mars on Windows 7, and here's my piece of 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;
#WebServlet("/Main")
public class Main extends HttpServlet {
private static final long serialVersionUID = 1L;
public Main() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("");
pw.println("");
pw.println("");
pw.println("<h1>Example 0</h1>");
pw.println("");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
It starts tomcat, ok, and "Example 0" can be seen when I access localhost. BUT, if I change the string in the response to "Example 1", it takes around 10 min to change it. I'm a beginner in Servlet / Tomcat development, and I'm failing to grasp the reason why the delay occurs. Why that happens??
Not an answer, but I recommend you code web stuffs with Netbeans, there is no doubt Eclipse is the king, but Netbeans does web stuffs better.
I am currently trying to complete a login system using jsp and servlets.I have my register and login validation working.
I wish to link to a welcome page following login to display the user profile information.
I had, just for testing purposes, a response.sendRedirect(welcome.jsp) which redirected following a successful login by the login servlet.
Now, to display the profile info on this welcome page I was going to use a servlet to gather the info from the database and render it to the the browser using a printwriter.
How do I call this servlet successfully from the loginservlet to run the doPost() method?
Or is there a better way of doing it?
Thank you for your time.
(For simplicity, I was just trying to get a basic webpage to appear first to make sure this was working I will have no problem with the database side of things once I get this going)
LOGIN SERVLET:
package logon;
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;
import javax.servlet.http.HttpSession;
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
System.out.println("In the Login Servlet");
User user = new User();
user.setEmail(request.getParameter("email"));
user.setPassword(request.getParameter("password"));
LoginDAO.login(user);
if(user.isValid())
{
HttpSession session = request.getSession(true);
session.setAttribute("currentSessionUser",user);
session.setAttribute("currentSessionUserEmail", user.getEmail());
response.sendRedirect("WelcomeServlet");
}else
response.sendRedirect("LoginFailure.html");
} catch (Throwable exc)
{
System.out.println(exc);
}
}
}
WELCOME SERVLET:
package logon;
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;
#WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public WelcomeServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.print("<html>"+"<head>"+"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">");
out.print("<title>Welcome</title>");
out.print("</head>"+"<body>");
out.print("Welcome to the welcome page!!!");
out.print("</body>"+"</html>");
}
}
You can't redirect using POST, only using GET. Since you're just displaying HTML in WelcomeServlet move the code from doPost to doGet, or make the one call the other, which simply makes them both do the same thing.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
Also, it would be better to use a JSP than to out.print a bunch of HTML inside a servlet. See the info page for servlets.
Plus, obviously your welcome page needs to read the attribute currentSessionUser from the session and make sure its not null to see if the user is really logged in or not. Otherwise if a user knows the address of the welcome page they can just bypass your login check as you have it now.
Your problem is that you have currently implemented your Servlet to respond to the wrong HTTP verb.
You'll notice that the servlet has as doPost and a doGet method. As you might expect these map onto HTTP GET and HTTP POST requests. Your current problem stems from the fact that you have implemented the doPost method in your WelcomeServlet therefore expecting a POST request, when it will actually be serving a GET request.
Speaking very crudely, you can think of GET requests as read operations and POST requests as write operations. So when you submit a form to save some data, this is typically handled a POST request. You are basically asking to write data to a database or session. When you load a web page, this is typically handled as a GET request. You are simply asking to read the data.
Again simplifying, but re-directs are typically GET requests. Therefore your Servlet will need to implement the doGet() method to respond to the browsers GET request after it is re-directed.
I like to run a servlet on a tomcat server but it gives the error as above.Also when i put ajax request on the servlet it did not working through index.jsp.Please help me friends.
also explain briefly because I am at the starting level of servlet.
import java.sql.Connection;
java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.Driver;
import java.util.Arrays;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySQLAccess extends HttpServlet
{
public void getRows(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException
{
String a="";
PrintWriter out = response.getWriter();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sankar?" + "user=root");
Statement statement = connection.createStatement();
ResultSet resultSet = statement
.executeQuery("SELECT * FROM sankar.datas");
a=resultSet.getString("name");
}
catch (Exception e)
{
e.printStackTrace();
}
out.println(a);
}
}
In order to accept the GET request, you need to override the doGet method in your MySQLAccess servlet class. Considering the code, you may just have to replace the name of your getRows method to doGet. From javadocs
HttpServlet class provides an abstract class to be subclassed to
create an HTTP servlet suitable for a Web site. A subclass of
HttpServlet must override at least one method, usually one of these:
doGet, if the servlet supports HTTP GET requests
doPost, for HTTP POST requests
doPut, for HTTP PUT requests
doDelete, for HTTP DELETE requests
You need the doGet-Method like so:
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// your code
}
This method is called from the server (tomcat container more specifically) when a GET request is sent to the servlet.
If you wish to use POST you need to implement the doPost(...)method, btw.
I just starting learning about servlets yersterday so I'm a newbie. I read a tutorial and made the following program to track the use of a link:
package red;
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;
#WebServlet("/Redirection")
public class Redirection extends HttpServlet {
private static final long serialVersionUID = 1L;
private String referrer;
private String target;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
getURLs(request);
}
catch(Exception e)
{
response.sendError(500, "Target parameter not specified");
return;
}
response.sendRedirect(target);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
public void getURLs(HttpServletRequest request)
{
referrer = request.getParameter("referrer");
if(referrer == null || 0 == referrer.length())
{
referrer = new String("");
}
target = request.getParameter("target");
if(target == null || target.equals(""))
{
throw new IllegalArgumentException();
}
}
}
But when I teste it(Eclipse with Tomcat) i get this:
HTTP Status 500 - Target parameter not specified
How do I specify a target parameter in eclipse so I can run this program ?
Sorry for the beginner question.
Well you don't really know what's going on here. Maybe you're getting a different exception - you're giving that error message whatever goes wrong. You should log exactly what's being thrown. You also shouldn't generally catch Exception yourself - catch more specific exceptions.
Anyway, normally to include that sort of parameter, you'd just put it in the URL:
/Redirect?target=x&referrer=y