" Head First Servlet和JSP"例子不起作用

时间:2014-10-04 03:49:31

标签: java jsp servlets

大家好,我正在阅读一本jsp书" Head First Servlet和JSP"而下一个例子不起作用......

HTML代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="windows-1255">
<title>Insert title here</title>
</head>
<body>

<h1 style="text-align: center;">Beer Selection Page</h1>
<br><br>

<form method = "POST" action="SelectBeer.do">
  Select beer characteristics<p>
  Color:
<select name ="color" size="1">
  <option value="light">light</option>
  <option value="amber">amber</option>
  <option value="brown">brown</option>
  <option value="dark">dark</option>
</select>
<br><br>

<div style="text-align:center">
<input type = "SUBMIT">
</div>
</form>

</body>
</html>

Web.xml中:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <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>

Servlet代码:

package com.example.web;

import javax.servlet.*; 
import javax.servlet.http.*;
import java.io.*; 


public class BeerSelect extends HttpServlet {

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);
}

}

当我运行它时,我得到...&#34; HTTP状态405 - HTTP方法GET不受此URL支持&#34; ...而且我急需帮助。 在此先感谢您的帮助!!

2 个答案:

答案 0 :(得分:1)

您可以通过添加&#34; doGet&#34;来解决此问题。 servlet的方法。使用与doPost相同的方法签名:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws     ServletException, IOException

您编码的内容仅包含doPost方法。因此servlet只响应HTTP POST请求。 HTTP 405响应代码是servlet引擎告诉客户端不支持HTTP GET的方法。

答案 1 :(得分:0)

你可以编写所有内容,但是在servlet代码中你需要进行更改:

Servlet代码:

package com.example.web;

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 BeerSelect extends HttpServlet {
private static final long serialVersionUID = 1L;

public BeerSelect() {
    super();
 }

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);
}

}