javaweb重定向——登录页面跳转到首页

时间:2024-03-20 16:54:03

一、项目结构

login.html用户信息错误,进行请求转发,跳转到loginError.html。
用户信息正确,进行重定向,跳转到home.html。
javaweb重定向——登录页面跳转到首页

二、login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
</head>
<body>
    <h3>用户登录</h3>
    <form action="login" method="get">
        <p>用户名<input type="text" name="username"></p>
        <p>密 码<input type="text" name="password"></p>
        <input type="submit" value="登录">
    </form>
</body>
</html>

三、ServletLogin.java

package net.test.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "ServletLogin",urlPatterns = "/login")
public class ServletLogin extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //用户列表
        String user="user123";
        String pass="pass123";
        //获取客户端传来的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if(!user.equals(username)){
            /*用户名不存在*/
            //request携带数据到web资源
            request.setAttribute("errorMessage","用户名不存在");
            //请求转发
            request.getRequestDispatcher("/loginError.jsp").forward(request,response);
        }else if(!pass.equals(password)){
            /*密码错误*/
            //request携带数据到web资源
            request.setAttribute("errorMessage","密码错误");
            //请求转发
            request.getRequestDispatcher("/loginError.jsp").forward(request,response);
        }else{
       		 //必须加项目地址,这里加hello
            response.sendRedirect("/hello/home.html");
        }
    }
}

四、loginError.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/2/1
  Time: 1:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户登录错误</title>
</head>
<body>
    <h3>用户登录错误界面</h3>
    <%=request.getAttribute("errorMessage")%>
</body>
</html>

五、home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <h3>网站首页</h3>
</body>
</html>

六、部署和运行

部署项目
javaweb重定向——登录页面跳转到首页
访问login.html
javaweb重定向——登录页面跳转到首页

1、测试用例一(用户名错误)

javaweb重定向——登录页面跳转到首页
跳转到用户登录错误页面,提示“用户名不存在”
javaweb重定向——登录页面跳转到首页

2、测试用例二(密码错误)

javaweb重定向——登录页面跳转到首页
跳转到用户登录错误页面,提示“密码错误”
javaweb重定向——登录页面跳转到首页

3、测试用例二(账号信息正确)

javaweb重定向——登录页面跳转到首页
跳转到网站首页
javaweb重定向——登录页面跳转到首页