如何编写一个与jsp连接的servlet用于登录页面

时间:2015-02-27 10:37:23

标签: jsp servlets

我想将我的jsp登录页面与servlet连接以验证用户名和密码。

我的登录页面是login.jsp:

<html>
    <input type="text" name="username" id="name">Please Enter you username
    <input type="password" name="password id="pass">Please Enter you password
</html>

3 个答案:

答案 0 :(得分:1)

您的登录页面表单必须有一个表单操作,其中包含您的servlet路径,如下所示。

<form action="Servlet_Name_With_Path">

答案 1 :(得分:0)

非常粗略:

public class AuthenticationService{
    public boolean authenticate(Strign userName, String password){
        //plug in to some 'proper' authentication logic here
        return userName.equals("Alia") && password.equals("password");
    }
}

public class AuthenticationServlet extends HttpServlet{

    public void doPost(HttpServletRequest request, HttPServletResponse response){
        AuthenticationService service = new AuthenticationService();
        String userName = request.getParameter("username");
        String password = request.getParameter("password");

        if(service.authenticate(userName, password)){
            request.getRequestDispatcher("success.jsp").forward(request, response);
        }else{
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }
    }
}

答案 2 :(得分:0)

您的 login.jsp 应如下所示

<html>
<form action=login method=post>
<input type="text" name="username" id="name">Please Enter you username
<input type="password" name="password id="pass">Please Enter you password
<input type="submit" name="submit" value="submit">
</form>
</html>

您的 web.xml 应如下所示

    <servlet>
      <servlet-name>Login</servlet-name>
      <servlet-class>packagename.class name</servlet-class>
    </servlet>

    <servlet-mapping>
      <servlet-name>Login</servlet-name>
      <url-pattern>/login</url-pattern>
    <servlet-mapping>

比如说你的Servlet类名是LoginServlet,它是包com.test。那么它应该是<servlet-class>com.test.LoginServlet</servlet-class>。 Servlet代码必须如上所述@Alan Hay