Onedaynerd
Onedaynerd

Reputation: 49

How to map servlet java

currently reading Head First Servlet Jsp. I currently stuck in mapping servlet. This is probably a stupid question but how can I map a servlet url pattern properly? I am using eclipse mars and this is my first time with jsp/servlets. I always check the generate web xml when creating a dynamic web project

This is what in the default 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>HeadFirst</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>

It runs using this

http://localhost:8080/HeadFirst/Ch2Servlet

but when I add this just below the display name

<servlet>
    <servlet-name>Ch2Servlet</servlet-name>
    <servlet-class>com.test.hello</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Ch2Servlet</servlet-name>
    <url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>

it gives me a 404 error and this is the url

http://localhost:8080/HeadFirst/servlet/com.test.hello.Ch2Servlet

Here's my servlet class

@WebServlet("/Ch2Servlet")
public class Ch2Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        java.util.Date today = new java.util.Date();
        out.println("<h1>Hello World</h1>" + "<br>");
        out.println("Date today is " + today + "<br>");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
}

btw i have read this but still am confused Java Servlet URL Mapping Servlet Mapping using web.xml edit added my serlvet class

Upvotes: 0

Views: 1948

Answers (1)

Titus
Titus

Reputation: 22484

The url is not:

http://localhost:8080/HeadFirst/servlet/com.test.hello.Ch2Servlet

It will be:

http://localhost:8080/HeadFirst/HelloWorld

More specifically, it will be the value that you set as <url-pattern>...</url-pattern>

Upvotes: 3

Related Questions