JSP实现用户登录样例

时间:2022-04-22
本文章向大家介绍JSP实现用户登录样例,主要内容包括业务描述、login.jsp代码、dologin.jsp处理代码、login_success.jsp用户登录成功界面、login_failure.jsp用户登录失败界面、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

  业务描述

  用户在login.jsp页面输入用户名密码登录:

  如果用户名为xingoo,密码为123,则跳转到成功界面login_success.jsp,并显示用户登录的名字;

  如果用户名密码错误,则跳转到失败界面login_failure.jsp,并提示返回登录界面。

  login.jsp代码

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>用户登录</title>
</head>
<body>
    <h1>用户登录</h1>
    <hr>
    <form name="regForm" action="doLogin.jsp" method="post">
        <table>
            <tr>
                <td>username</td>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <td>password</td>
                <td><input type="password" name="password"/></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="submit"/></td>
            </tr>
        </table>
    </form>
</body>
</html>

  dologin.jsp处理代码

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%
    String username = "";
    String password = "";
    
    request.setCharacterEncoding("utf-8");
    
    username = request.getParameter("username");
    password = request.getParameter("password");
    
    if("xingoo".equals(username)&&"123".equals(password)){
        session.setAttribute("loginUser",username);
        request.getRequestDispatcher("login_success.jsp").forward(request,response);
    }else{
        response.sendRedirect("login_failure.jsp");
    }
%>

  login_success.jsp用户登录成功界面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>用户登录</title>
</head>
<body>
    <h1>用户登录</h1>
    <hr>
    欢迎您!<%=session.getAttribute("loginUser") %>
</body>
</html>

  login_failure.jsp用户登录失败界面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>用户登录</title>
</head>
<body>
    <h1>用户登录</h1>
    <hr>
    登录失败!<a href="login.jsp">返回登录</a>
</body>
</html>