This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 3 years ago.
I am trying to create a servlet in java, using Eclipse IDE and Tomcat7 server. When I run the HelloForm in server it shows the form but after entering numbers and clicking submit it shows:
HTTP Status 404 - /Test2/HelloWorld
type Status report
message /Test2/HelloWorld
description The requested resource is not available.
Apache Tomcat/7.0.47
Code for HelloForm.html
<!DOCTYPE html>
<html>
<body>
<form action="HelloWorld" method="post">
Enter 1st number : <input type="text" name="num1"> <br>
Enter 2st number : <input type="text" name="num2"> <br> <input
type="submit">
</form>
</body>
</html>
Code for HelloWorld.java
package mypkg;
public class HelloWorld extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
int sum = num1 + num2;
System.out.println(sum);
PrintWriter out = response.getWriter();
out.println("Addition : " + sum);
}
}
Code for 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" xsi: schemaLocation ="http: //java.sun.com/ xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>mypkg.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/sayhello</url-pattern>
</servlet-mapping>
</web-app>
You have missed #WebServlet("/HelloWorld"). Given below is the completed code:
package mypkg;
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("/sayhello")
public class HelloWorld extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
int sum = num1 + num2;
System.out.println(sum);
PrintWriter out = response.getWriter();
out.println("Addition : " + sum);
}
}
Make sure you have the following root declaration of your web.xml otherwise it will not be interpreted as Servlet 3.0 which supports #WebServlet annotation.
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
Update:
I can see that you have now added the content of your web.xml in the question. As per this update, your HTML form action should be as follows:
<form action="sayhello" method="post">
Related
Am trying to access the url from JBOss server.. i have an error
javax.servlet.ServletException: Error instantiating servlet class com.tg.simReplacementApi.ReplaceSim
org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930)
java.lang.Thread.run(Thread.java:701)
root cause
java.lang.ClassNotFoundException: com.tg.simReplacementApi.ReplaceSim from [Module "deployment.ReplacementSim.war:main" from Service Module Loader]
org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190)
org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468)
org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456)
org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120)
org.jboss.as.web.deployment.WebInjectionContainer.newInstance(WebInjectionContainer.java:72)
org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930)
java.lang.Thread.run(Thread.java:701)
and my web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Web Application</display-name>
<servlet>
<servlet-name>ReplaceSim</servlet-name>
<display-name>ReplaceSim</display-name>
<description></description>
<servlet-class>com.tg.simReplacementApi.ReplaceSim</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ReplaceSim</servlet-name>
<url-pattern>/ReplaceSim</url-pattern>
</servlet-mapping>
</web-app>
and servlet is ReplaceSim.java
package com.tg.simReplacementApi;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ReplaceSim
*/
public class ReplaceSim extends HttpServlet {
private static final long serialVersionUID = 1L;
public ReplaceSim(){
}
/**
* #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());
Member member = new Member();
member.setPhoneNo(request.getParameter("phone"));
member.setSimSerial(request.getParameter("simSerial"));
WebServiceCaller call = new WebServiceCaller();
String resp = call.getReplacementSim(member);
System.out.println(resp);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
and successfully deployed into jboss7.1.1 server. When accessing the url this error is occurring. in localhost the application is working fine.
can anybody know why it causing error.. thanks in advance
When I have cookies enabled and I do a requestDispatcher.forward(req,resp) from loggedIn to ShoppingCart , the 'session id' and 'username' is carried forward/saved.
But when the cookies are disabled, a new 'session id' is created and the 'username' is null.
My question is how should i maintain the session when cookies are disabled.
login form
<html>
<body>
<form method="POST" action="login.do">
username:<input type="text" name="username" />
<input type="submit" value="login"/>
</form>
</body>
</html>
loggedIn.jsp
<html>
<body>
Session Id : <%out.print(session.getId());%><br>
Logged In User: <%out.print(session.getAttribute("username"));%><br>
<form action="shopping.do" method="POST">
<input type="submit" value="start shopping"/>
</form>
</body>
</html>
shoppingCart.jsp
<html>
<body>
Session Id : <%out.print(session.getId());%><br>
Logged In User: <%out.print(session.getAttribute("username"));%><br>
<h1>Shopping Cart</h1>
</body>
</html>
web.xml
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<!-- LOGIN CONTROLLER -->
<servlet>
<servlet-name>LoginController</servlet-name>
<servlet-class>com.example.controller.LoginController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginController</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
<!-- SHOPPING CONTROLLER -->
<servlet>
<servlet-name>ShoppingController</servlet-name>
<servlet-class>com.example.controller.ShoppingController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShoppingController</servlet-name>
<url-pattern>/shopping.do</url-pattern>
</servlet-mapping>
</web-app>
LoginController
package com.example.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginController extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
HttpSession session = req.getSession();
if(req.getParameter("username")!=null && !req.getParameter("username").isEmpty()){
session.setAttribute("username",req.getParameter("username"));
}
String URL = ("loggedIn.jsp");
String encodedURL=resp.encodeRedirectURL(URL);
System.out.println(encodedURL);
RequestDispatcher view =req.getRequestDispatcher(encodedURL);
view.forward(req,resp);
}
}
ShoppingController
package com.example.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ShoppingController extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
String URL = ("shoppingCart.jsp");
RequestDispatcher view =req.getRequestDispatcher(URL);
view.forward(req,resp);
}
}
For normal urls on the page, you would use response.encodeURL(). For redirects you should use response.encodeRedirectURL()
Additional information regarding the difference between the two can be found on this SO post
I am using Eclipse IDE, a simple HelloServlet.java file and a simple index.jsp file. When I run the local server, the program starts but the following code does not execute:
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
System.out.println("Init Firing: ");
}
I have the Console tab open, and the last statement I receive is: INFO: Server startup in 1442 ms. What might I do to get the init method to fire?
The container will only call the init() method of the servlet when it's called, not on the container startup.
If you want to start things on container startup, you can use the ContextListener as suggested here call method on server startup
This code works for me
package mine;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySL extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
System.out.println("xyz="+config.getInitParameter("xyz"));
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
}
}
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"
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>jsp</display-name>
<servlet>
<servlet-name>mySL</servlet-name>
<servlet-class>mine.MySL</servlet-class>
<init-param>
<param-name>xyz</param-name>
<param-value>123</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mySL</servlet-name>
<url-pattern>/MySL</url-pattern>
</servlet-mapping>
</web-app>
When the server starts, nothing happens, because the init() method is called when the servlet is called.
On the first servlet call (e.g. opening in your browser something like http://myserver.mydomain:8080/myapp/MySL), you'll get
xyz=123
doGet
On the second servlet call, you'll get
doGet
Please notice that this is the "old way" of declaring things. Nowadays, Servlets configuration can be made using annotations. Careful to not mix annotations with XML declarations for the same servlet.
Servlets with annotations look like this
package mine;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(urlPatterns = { "/OtherSL" }, initParams = { #WebInitParam(name = "abc", value = "456", description = "some parameter") })
public class OtherSL extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
System.out.println("abc=" + config.getInitParameter("abc"));
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
}
}
I have the following class...
package org.me.test
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("/servlet")
public class TestServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
resp.setContentType("text/plain");
resp.getWriter().write("Test Servlet");
super.doGet(req, resp);
}
}
and the following Web.xml...
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<display-name>srv</display-name>
<servlet-name>srv</servlet-name>
<servlet-class>
org.me.test.TestServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>srv</servlet-name>
<url-pattern>/srv/*</url-pattern>
</servlet-mapping>
</web-app>
but I get...
Error 405: HTTP method GET is not supported by this URL
You are getting the 405 error because you are calling super.doGet() at the end of your doGet(). Try removing that line.
The default implementation of doGet() in the base class HttpServlet returns that 405 error. To support the GET operation, you must override doGet() without calling the parent implementation, otherwise it returns the same error intended to be displayed when there is no override.
In Myeclipse I created a web project called web1,and added a servlet called servlet1,the web.xml is as followed:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet1</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
but when I typed the address:http://localhost:8080/web/test in the browser,it didn't work.I tried many times but have no answer.what's the problem?thanks a lot!
Here is the code:
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 servlet1 extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -6214906967399177511L;
/**
* Constructor of the object.
*/
public servlet1() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* #param request the request send by the client to the server
* #param response the response send by the server to the client
* #throws ServletException if an error occurred
* #throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* #param request the request send by the client to the server
* #param response the response send by the server to the client
* #throws ServletException if an error occurred
* #throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* #throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
Well as usual, you forgot to say super.init(config);
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
You're servlet never got initialized, because you overrode method, and forgot to call parents' init.
That's why, if you do not know the internals, do NOT override anything, except if you're sure what are you doing.