This is the error I see when I try to compile my code — am I passing the URL incorectly? I wanted to learn from this sample code to display my servlet in the browser.
HTTP Status 404 - /Lesson41/
type Status report
message /Lesson41/
description The requested resource is not available.
Apache Tomcat/8.0.22
My servlet code is as follows:
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 Lesson41
*/
@WebServlet("/Lesson41")
public class Lesson41 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String usersName = request.getParameter("YourName");
String theLang = request.getParameter("Language");
int firstNum = Integer.parseInt(request.getParameter("Firstnum"));
int secondNum = Integer.parseInt(request.getParameter("secondnum"));
int sumONum = firstNum + secondNum;
response.setContentType("text/html");
PrintWriter output = response.getWriter();
output.println("<html><body><h3>Hello " + usersName);
output.println("</h3><br />" + firstNum + " + " + secondNum);
output.println(" = " + sumONum + "<br />Speaks " + theLang + "</body></html>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
This is my 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>HelloServers</display-name>
<servlet>
<servlet-name>Lesson41</servlet-name>
<servlet-class>HelloServelets-Lesson41</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Lesson41</servlet-name>
<url-pattern>http://localhost:8080/Lesson41/</url-pattern>
</servlet-mapping>
</web-app>
You have to take following steps:
1. Remove <Servlet> and <servlet-mapping> tags and anything in between them. Since you have used @WebServlet annotation. There is no need to declare those tags in web.XML.
In your form tag replace action attribute to: action="Lesson41"
Don't try to call the Servlet directly through the URL, you are posting some data with your request. First try to load your HTML page and then hit the submit button to call the Servlet's doPost() method.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments