Servlet程序运行不正常

时间:2015-03-03 07:04:35

标签: java html servlets

我正在运行一个小的servlet程序,但它没有给出预期的输出。

Servletfile.java

public class Servletfile extends HttpServlet {
private static final long serialVersionUID = 1L;

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

    response.setContentType("text/ html");
    PrintWriter out= response.getWriter();
    String abc = request.getParameter("name");
    out.print("name="+abc);
}

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

}

}

的index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<Form action= "welcome" method="get">
Enter Name :<input type = "text" name="name"><br>
<input type = "Submit" value= "login">
</Form>
</body>
</html>

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"   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Practice</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>
<servlet>
<description></description>
<display-name>Servletfile</display-name>
<servlet-name>Servletfile</servlet-name>
<servlet-class>code.Servletfile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servletfile</servlet-name>
<url-pattern>/Servletfile</url-pattern>
</servlet-mapping>
</web-app>

在执行代码时,它显示index.html页面,但如果我输入任何名称作为输入,那么它会给出404-页面找不到错误。如果我单独运行servlet程序,它会将name = null作为输出。你能告诉我一件事吗。

2 个答案:

答案 0 :(得分:0)

使用<%=request.getContextPath()%>/Servletfile调用操作有时容器无法找到您的servlet,这就是他向您展示404的原因。

答案 1 :(得分:0)

您需要将index.html文件更改为以下内容:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<Form action= "Servletfile" method="get">
Enter Name :<input type = "text" name="name"><br>
<input type = "Submit" value= "login">
</Form>
</body>
</html>

现在表单将映射到您的Servletfile Servlet。您直接导航到null时看到http://localhost:8080/Servletfile的原因是您从未设置请求参数name