2015-11-29 28 views
0

我正在嘗試一些基本的Servlet編程。我創建了一個基本的Html表單並提交它,想要調用一個打印用戶輸入的名稱的servlet。我張貼下面的代碼。Servlet不是用html表格映射的

HTML: (它是在rootfolder - web應用\的HelloWorld \ hello.html的)

<html> 
<body> 
<form action="./hello" method="get"> 
Name: <input type="text" name="P1"> 
<input type="submit" value="Submit"> 
</form> 
</body> 
</html> 

>的web.xml (位置:web應用\的HelloWorld \ WEB_INF \ web.xml)

<?xml version="1.0" encoding="UTF-8"?> 
<web-app> 
    <servlet> 
     <servlet-name>hs</servlet-name> 
     <servlet-class>HelloWorld</servlet-class> 
    </servlet> 
    <servlet-mapping> 
     <servlet-name>hs</servlet-name> 
     <url-pattern>/hello</url-pattern> 
    </servlet-mapping> 
</web-app> 

> servlet類 (地點:的webapps \ HelloWorld的\ WEB_INF \ \班的HelloWorld.class

import javax.servlet.*; 
import java.io.*; 
public class HelloWorld implements Servlet{ 
    public void init(ServletConfig sc)throws ServletException{ 
     //initialization code 
    } 
    public ServletConfig getServletConfig(){ 
     return null; 
    } 
    public void service(ServletRequest request, ServletResponse response)throws ServletException,IOException{ 
     String name=request.getParameter("P1"); 
     PrintWriter out = response.getWriter(); 
     out.println("Hello: "+name);   
    } 
    public String getServletInfo(){ 
     return null; 
    } 
    public void destroy(){ 

    } 
} 

所以每當我鍵入一個名稱,然後點擊提交,我得到 'HTTP狀態404' 錯誤。你能告訴我我做錯了什麼!任何幫助將非常感激。謝謝!

回答

0

在你的HTML表單,你必須給表單動作你的servlet「HelloWorld」 specifically.Because form action是誰出現在路徑數據

<html> 
<body> 
<form action="/HelloWorld" method="get"> 
Name: <input type="text" name="P1"> 
<input type="submit" value="Submit"> 
</form> 
</body> 
</html> 

HTTP的一個404種找不到錯誤方法您嘗試訪問的網頁無法在服務器上找到

或嘗試這個servlet代碼:

public class HelloWorld extends HttpServlet { 
    public void doGet(HttpServletRequest request, 
        HttpServletResponse response) 
     throws ServletException, IOException { 
    response.setContentType("text/html"); 
    PrintWriter out = response.getWriter(); 
    String title = "Reading Request Parameters"; 

    out.println(
       "<HTML>\n" + 
       "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n"+ 
       "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" + 
       "<UL>\n" + 
       " <LI><B>P1</B>: " 
       + request.getParameter("P1") + "\n" +"</BODY></HTML>"); 
    } 
} 
+0

嘿謝謝你的回覆!我確實進行了您所建議的更改,但仍然收到相同的錯誤。 –

+0

然後添加「/HelloWorld.class」 – AVI

+0

你的問題是你保存的目錄或你引導你的數據的方式,就像我說的。這就是404錯誤發生的原因 – AVI