Search code examples
javaservletsservlet-3.0

Can't compile servlet file.


I was testing a demo servlet file But, the servlet doesn't seem to respond. I'm not able to understand the problem.

When I click submit on the HTML form the URL is localhost:8080/Beer-V1/SelectBeer.do

But, shouldn't it be /BeerSelect? Because of @WebServlet("/BeerSelect") ???

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" metadata-complete="false" 
version="3.0">

 <servlet>
<servlet-name>CH3 Beer</servlet-name>
<servlet-class>com.example.web.BeerSelect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CH3 Beer</servlet-name>
<url-pattern>/SelectBeer.do</url-pattern>
</servlet-mapping>
</web-app>

BeerSelect.java

package com.example.web;

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("/BeerSelect")
public class BeerSelect extends HttpServlet {
private static final long serialVersionUID = 1L;

public BeerSelect() {
    super();
}

@Override
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("Beer Selection Advice<br>");

    String c = request.getParameter("color");
    out.println("<br> Got Beer Color " + c);

}

}


Solution

  • When I click submit on the HTML form the URL is localhost:8080/Beer-V1/SelectBeer.do

    But, shouldn't it be /BeerSelect? Because of @WebServlet("/BeerSelect") ???

    1. web-container associates a "context-path" for each of the web-application deployed and in your case, I believe it is "Beer-V1".

    2. You have overridden the mapping in web.xml as below and hence you are seeing *.do

      <servlet-mapping>
        <servlet-name>CH3 Beer</servlet-name>
        <url-pattern>/SelectBeer.do</url-pattern>
      </servlet-mapping>
      

    The xml DD overrides the annotations.