欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Servlet 实现登录页面,并在条件下跳转

程序员文章站 2022-05-08 16:04:04
...

Java代码 

package ServletDemo;

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

public class DealServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out=resp.getWriter();
        resp.setContentType("text/html;charset =utf-8");//防止乱码
        String username = req.getParameter("username");//获取登录名
        String passWd = req.getParameter("passwd");//获取密码
        System.out.println("登录名" + username);
        System.out.println("密码"+ passWd);
        if(username.equals("") || passWd.equals("")){//判断密码和用户名是否为null
            String str = "You code is Error!!!";
//            req.setAttribute("Alert",str);
            //跳转到密码错误页面
//          req.getRequestDispatcher("passwdError.jsp").forward(req,resp);
            System.out.println("执行到没输入密码");
            out.println(str);
        } else{
            if(username.equals(passWd)){//判断用户名是否等于密码
                String str = "welcome!!!";
//              req.getRequestDispatcher("welcome.jsp").forward(req,resp);
                out.println(str);
                System.out.println("执行到密码等于用户名");
            }
            else{
                String str = "code Error,back to welcome";
//              req.setAttribute("Alert",str);
//              req.getRequestDispatcher("index.jsp").forward(req,resp);
                out.println(str);
                System.out.println("执行到密码错误");
            }
        }
    }
}

html文件 


<%@ page contentType="text/html;charset=utf-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>用户登录示例</title>
</head>
<body>
<div style="margin: auto; text-align: center;">
    <form action="ServletDemo/DealServlet" method="post">
        用户名:<input type="text" name="username" />
        密 码:<input type="password" name="passwd" />
                <input type="submit" value="登 录" />
    </form>
</div>
</body>
</html>

Servlet 实现登录页面,并在条件下跳转

 Servlet 实现登录页面,并在条件下跳转

 Servlet 实现登录页面,并在条件下跳转

 Servlet 实现登录页面,并在条件下跳转

Servlet 实现登录页面,并在条件下跳转 

 Servlet 实现登录页面,并在条件下跳转