Servlet not displaying anything while called - java

I am just writing the code after a while for servlet/jsp.
When I am calling servlet it is giving me blank browser and even not an error.
My Jsp :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="HelloServlet" method="POST">
Please enter a color <br>
<input type="text" name="color"size="20px">
<input type="submit" value="submit">
</form>
</body>
</html>
My Servlet :
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 HelloServlet
*/
#WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HelloServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#service(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Servlet called...");
String color = request.getParameter("color");
PrintWriter out = response.getWriter();
/*
* out.println(
*
* "<html> \n" + "<head> \n" +
* "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"> \n"
* + "<title> My first jsp </title> \n" + "</head> \n" + "<body> \n" +
* "<font size=\"12px\" color=\"" + color + "\">" + "Hello World" +
* "</font> \n" + "</body> \n" + "</html>");
*/
out.println("Aman.............");
}
/**
* #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);
}
}
And web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
<display-name>TestApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
Please help me out in this.
Thanks,
Aman

Add super to the following function and everything will work
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
**super(request, response) // add this**
}
The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers).
You have overrided the function which is responsible for calling doget and post.
Hope this solves your query

The mistake you made is you are using both annotation as well as registering the servlet through deployment descriptor (web.xml).
If you use annotation,registering the servlet through deployment descriptor is not required. But you should have tomcat7 as it will not run in the previous versions of tomcat. #WebServlet annotation is used to map the servlet with the specified name.
Moreover I assume that you are not using any package because in the url-mapping you dint specify one. But in case you are using some package named mypackage and your servlet class is inside it then change the url-mapping to something like this
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>mypackage.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>

The protected service method checks the type of request, if request type is get, it calls doGet method, if request type is post, it calls doPost method, so on
try to remove this method,and your servlet should work
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
or rewrite your service method using this :
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String method = request.getMethod();
if(method.equals("GET"))
doGet(request, response);
else
doPost(request, response);
}
You don't write anything in service method so that it will never call either doPost or doGet

Related

Servlet error : HTTP Status 405 - HTTP method GET is not supported by this URL [duplicate]

This question already has answers here:
HTTP Status 405 - HTTP method is not supported by this URL
(2 answers)
HTTP Status 405 - HTTP method POST is not supported by this URL java servlet [duplicate]
(5 answers)
Closed 2 years ago.
When i try to run the code in eclipse it won't pass the arguments.
please check the below images url.
But when i individually run the html code it passes the values.
I don't know why this work like this.
My Servlet code is
package com.example;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AddServelet extends HttpServlet
{
public void services(HttpServletRequest req, HttpServletResponse resp) {
int i = Integer.parseInt(req.getParameter("num1"));
int j = Integer.parseInt(req.getParameter("num2"));
int k = i+j;
System.out.println(k);
}
}
and my web.xml code is
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>com.example.AddServelet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
</web-app>
my html code
<html>
<body>
<form action="add">
Number 1: <input type="number" name="num1"><br>
Number 2: <input type="number" name="num2"><br>
<input type="submit">
</form>
</body>
</html>
Can anyone please help me with this.
Thank you in advance.
You need to override the doPost method because you are submitting the form and it's a post request.
public class AddServelet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public AddServelet() {
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
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
int i = Integer.parseInt(req.getParameter("num1"));
int j = Integer.parseInt(req.getParameter("num2"));
int k = i+j;
System.out.println(k);
}
}
override the HttpServlet protected void doGet(HttpServletRequest req, HttpServletResponse resp) method if you want to handle a GET request

Can send data but request.getParameter always == null

There are my code from java eclipse keplero, my project was a servlet(server) that communicate with extension of chrome(client) via XMLRequest. I have used GET and POST and servlet can comunicate the string in between case but request.getParameter was in every case null.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>XMLFinal</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method = "get" action = "main">
Data: <input type="text" name="data">
<input type="submit" value = "send">
</form>
</body>
</html>
main.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
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 netscape.javascript.JSObject;
/**
* Servlet implementation class main
*/
#WebServlet("/main")
public class main extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public main() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
//server funziona in invio, il segnale in ricezione non funziona ancora
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//guardare file index.html
System.out.println(request.getParameter("data"));
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
//
response.getWriter().write("GET");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//guardare file index.html
System.out.println(request.getParameter("data"));
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
//invio segnale funzionante
response.getWriter().write("POST2");
}
private void getHeadersInfo() {
// TODO Auto-generated method stub
}
}
I have improve in login page to create a simple form and that run perfectly but i need data from js client :
loadXMLRequest();
function loadXMLRequest()
{
var xmlhttp;
//da testare su Chrome Firefox Opera IE 7 o superiore
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
//arrivo del segnale
xmlhttp.open("GET","http://localhost:8080/XMLFinal/main?ciao",true);
xmlhttp.setRequestHeader("Content-Type","text/plain");
alert("questi sono i dati da inviare : ciao"");
xmlhttp.send();
alert("Message sent");
//apertura pagina web risposta giunta ed in elaborazione
//window.open(xmlhttp.responseText);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==0)
{
alert("request not initialized");
}
if (xmlhttp.readyState==1)
{
alert("server connection established");
}
if (xmlhttp.readyState==2)
{
alert("request received");
}
if (xmlhttp.readyState==3)
{
alert("processing request");
}
if (xmlhttp.readyState==4)
{
alert("request finished and response is ready");
alert(xmlhttp.responseText);
//nessun dato ricevuto possibile shutdown del server
if(xmlhttp.responseText=="")
{
}
else
{
//windows.open(xmlhttp.responseText);
}
}
if (xmlhttp.readyState==200)
{
alert("OK");
alert(xmlhttp.responseText);
}
if (xmlhttp.readyState==404)
{
alert("Page not found");
}
}
}
else
{
//per IE 6 o inferiore
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
alert("Microsoft alert");
}
}
The Name is the Key
Your code says
System.out.println(request.getParameter("http"));
and your form says
<input type="text" name="data">
Change the first to
System.out.println(request.getParameter("data"));
or the second to
<input type="text" name="http">
You are making a Get call i.e.,
xmlhttp.open("GET","http://localhost:8080/XMLFinal/main?ciao",true);
So from servlet it will call doGet(-,-) method, but under doGet(-,-) method you have written
System.out.println(request.getParameter("http"));
which should be replaced like
System.out.println(request.getParameter("data"));
Which you have correctly written in doPost(-,-) method.
But i always prefer not to write redundant code. in both doGet() & doPost(), instead you can write code in a common method and call the same method from both the do*** methods. i.e.,
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Hope this will helps you.

How to process href parameters jsp

I have little test page, but I can't get request parameters an don't understand why.
Test page have "href" links like this:
Show smth
Simple controller:
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Controller extends HttpServlet {
#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);
}
protected void processRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
StringBuilder sb = new StringBuilder("Do SMTH<br>");
sb.append("Other will be later...<br>");
String s = sb.toString();
request.setAttribute("result", s);
RequestDispatcher view = request.getRequestDispatcher("test.jsp");
view.forward(request,response);
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<welcome-file-list>
<welcome-file>main.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>/main.jspc</url-pattern>
</servlet-mapping>
</web-app>
and test page, where i want to show some obtained parameters:
test.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<%
out.print("<br>" + "Parameter: ");
request.getParameter("param");
out.print("<br>"+ "URL:");
request.getRequestURL();
out.print("<br>" + "Result:");
request.getParameter("result");
%>
</body>
</html>
But test page showing empty parameters, I don't understand why.
The use of scriptlets (those <% %> things) in JSP is old one and discouraged since the birth of taglibs(JSTL) and EL(Expression Language, those ${} things).
Use below code access your parameter :
Parameter : ${params} <br>
Result : ${result} <br>
URL : ${pageContext.request.requestURI}

How to run servlet in Eclipse?

Installation Details:
First I install the jdk then add a environment variable
variable name = "path"
variable value ="C:\Program Files\Java\jdk1.7.0_45\bin"(directory of java)
Then Extract the eclipse and tomcat
After extracting, I edit the catalina.bat from apache-tomcat-7.0.23\bin and add this:
"set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_45"
Then I made my first Servlet by creating new dynamic web project
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test Form</title>
</head>
<body>
<h1>JAVA TEST</h1>
<form action ="work.html" method ="get">
<input type="submit" value="login">
</form>
</body>
</html>
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 work
*/
#WebServlet("/work.html")
public class work extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public work() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<html>");
out.print("<head>");
out.print("<title>Login Authentication Result</title>");
out.print("<h2>Welcome to servlet</h2>");
out.print("<p> powered by" + getServletContext().getServerInfo()+ "</p>");
out.print("</body>");
out.print("</hmtl>");
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Test3</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
I'm new to servlet. I don't know why it is always have this error when clicking the button in the index.html
I think I have the same problem
Just configure Tomcat in eclipse!

Java Servlet JSP does not print out attribute

I'm trying to write a servlet using generated HTML code, rather then printing out static HTMLs.
I'm using Eclipse-EE Europa and Tomcat 6.
I tried to use the flowing tips from HERE
But instead of printing the desired attribute It seems that the jsp ignoring the attribute or the attribute is empty.
Here is the servlet:
package com.serv.pac;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* Servlet implementation class for Servlet: testServlet
*
*/
public class testServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#HttpServlet()
*/
public testServlet() {
super();
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "doGet response";
request.setAttribute("message", message);
request.getRequestDispatcher("/testServlet/WEB-INF/index1.jsp").forward(request, response);
PrintWriter out = response.getWriter();
out.println("the servlet");
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("first servlet");
}
}
Here is the JSP
<!doctype html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
And the following is the :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>servlet1_test</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
<welcome-file>index1.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>testServlet</display-name>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.serv.pac.testServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/testServlet</url-pattern>
</servlet-mapping>
</web-app>
And that is what I'm getting in the browser:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: </p>
</body>
</html>
As one may see there is nothing after the "Message" in the html body, as if the message attribute is empty.
Thank You
The only way I can see this happenning is you aren't actually accessing your Servlet.
You've declared a <welcome-file>
<welcome-file>index1.jsp</welcome-file>
So if you try to hit
localhost:8080/YourContextPath
the default Servlet will render and send you that jsp with a missing message attribute.
If you want to hit your actual Servlet, you need to use
localhost:8080/YourContextPath/testServlet
Note that you need to change
request.getRequestDispatcher("/testServlet/WEB-INF/index1.jsp").forward(request, response);
to
request.getRequestDispatcher("/WEB-INF/index1.jsp").forward(request, response);
and move your file under WEB-INF.

Categories