Servlet不工作?

时间:2016-03-28 15:18:31

标签: java servlets

rd1的代码

package requestdispatcher;
public class rd1 extends HttpServlet {
private static final long serialVersionUID = 1L;

public rd1() {
    super();

}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String password=request.getParameter("pwd");
    PrintWriter out = response.getWriter();  

    if(password.equals("servlet"))
            {  
        RequestDispatcher rd=request.getRequestDispatcher("servlet2");  
        rd.forward(request, response);  
    }  
    else{  
        out.print("Sorry UserName or Password Error!");  
        RequestDispatcher rd=request.getRequestDispatcher("index.html");  
        rd.include(request, response);
    }
}

}

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_3_0.xsd" version="3.0">
 <servlet>
  <servlet-name>rd1</servlet-name>
  <servlet-class>requestdispatcher.rd1</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>rd1</servlet-name>
  <url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
   <servlet-name>welcome</servlet-name>
  <servlet-class>requestdispatcher.welcome</servlet-class>
 </servlet>

 <servlet-mapping>  
  <servlet-name>welcome</servlet-name>  
  <url-pattern>/servlet2</url-pattern>  
 </servlet-mapping>  
</web-app>

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <form action="servlet1" method="post">
    Name:<input type="text" name=UName/><br/>
      password:<input type="password" name=pwd/><br/>
  <input type="submit" value="login"/>
 </form>
</body>
</html>

我刚刚开始在servlet中学习请求调度程序,但是在提交表单时我在行号上有空指针异常。 28,在 rd1 servlet中,我在if语句中比较了我在代码中提到过的密码...我还要提到我&#39;我得到了500系列的错误。你能告诉我我做错了什么吗?另请注意,最初我输入的密码(格式)不是&#34; servlet&#34;这样我就可以在&#34; else&#34;中运行代码&#34; rd1&#34;的一部分它将我发送到index.html页面。

1 个答案:

答案 0 :(得分:0)

index.htmlpwdUName附近的双引号)中进行更改:

<form action="servlet1" method="post">
    Name:<input type="text" name="UName"/><br/>
      password:<input type="password" name="pwd"/><br/>
  <input type="submit" value="login"/>
 </form>

if - 声明不是无效的。这个代码是28行吗? 在doPost中更改此内容:

String password=request.getParameter("pwd");
if (password!=null)
{
if(password.equals("servlet"))
    {  
        RequestDispatcher rd=request.getRequestDispatcher("servlet2");  
        rd.forward(request, response);  
    }  
    else
    {  
        errorHandling(request, response);
    }  
}
else
{
    errorHandling(request, response);
}

private void errorHandling(request, response)
{
out.print("Sorry UserName or Password Error!");  
            RequestDispatcher rd=request.getRequestDispatcher("index.html");  
            rd.include(request, response);

}