0

我正在测试一个演示 servlet 文件但是,servlet 似乎没有响应。我无法理解这个问题。

当我在 HTML 表单上单击提交时,URL 是 localhost:8080/Beer-V1/SelectBeer.do

但是,不应该是 /BeerSelect 吗?因为@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);

}

}

4

1 回答 1

1

当我在 HTML 表单上单击提交时,URL 是 localhost:8080/Beer-V1/SelectBeer.do

但是,不应该是 /BeerSelect 吗?因为@WebServlet("/BeerSelect") ???

  1. web-container 为每个部署的 web 应用程序关联一个“上下文路径”,在您的情况下,我相信它是“Beer-V1”。

  2. 您已经覆盖了 web.xml 中的映射,如下所示,因此您看到 *.do

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

xml DD 会覆盖注释。

于 2012-09-12T00:17:27.853 回答