使用jsp简单实现用户登录

首页

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>学生管理系统——首页</title>
</head>
<body>
</h1>学生管理系统
<h1/>
<!--提供首页跳转的超链,因为需要在一个类内进行跳转,所以提前约定好信号量action,用于识别方法名称-->
<a href="st.do?action=loginput">登录</a>
<a href="st.do?action=add">注册</a>
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--用于跳转学生类-->
    <servlet>
        <servlet-name>StudentServlet</servlet-name>
        <servlet-class>com.student.StudentServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>StudentServlet</servlet-name>
        <url-pattern>/st.do</url-pattern>
    </servlet-mapping>

    <!--跳转验证码-->
    <servlet>
        <servlet-name>PicServlet</servlet-name>
        <servlet-class>com.student.PicServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>PicServlet</servlet-name>
        <url-pattern>/pic.do</url-pattern>
    </servlet-mapping>


</web-app>

依赖

 	<dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>jsp-api</artifactId>
            <version>6.0.53</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>
package com.student;

import com.utill.StringUtil;

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.lang.reflect.Method;

public abstract class BeanServlet extends HttpServlet {
    //将所有的get请求转交给post处理
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    //所有的请求必定首先执行的方法
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //将编码字符集设置为utf8
        response.setContentType("text/html;charset=utf-8");
        //提前约定好的,所有的页面请求都必须提供一个字符串参数action,用于判断执行哪一个方法
        String action =request.getParameter("action");
        if(StringUtil.isBlank(action)){
            //如果为空,
            action="show";
        }
        try {
            //获取当前对象的类
            Class clz =this.getClass();
            //寻找该类中,方法名称为action,参数类型为HttpServletRequest.class,HttpServletResponse.class的方法
            Method method =clz.getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
            //执行找到的方法,参数依次为类名称,被调用的方法的参数
            method.invoke(this,request,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public abstract void show(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ;

}

package com.student;

import com.utill.StringUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Enumeration;

public class StudentServlet extends BeanServlet {
    //执行该方法会跳转到提前写好的jsp页面
    public void loginput(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("login.jsp").forward(request,response);
    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接受页面传回的数据
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String checkcode=request.getParameter("checkcode");
        //首先判断验证码是否为空,验证码为空则不做其他判断
        if(StringUtil.isBlank(checkcode)){
            request.setAttribute("checkcode","验证码不能为空");
        }else {
            //获取服务器本身的数据,验证码会发给客户端,服务器本身也要存,否则无法比较
            HttpSession session=request.getSession();
            Object obj=session.getAttribute("checkcode");
            if(checkcode.equals(obj)){
                if(StringUtil.isBlank(username)){
                    request.setAttribute("username","用户名不能为空");
                }else {
                    if(StringUtil.isBlank(password)){
                        request.setAttribute("password","密码不能为空");
                    }else {
                        //连接数据库查询

                    }
                }
            }else {
                request.setAttribute("checkcode","验证码错误");
            }

        }
        Enumeration<String> names= request.getAttributeNames();
        if(names.hasMoreElements()){
            request.getRequestDispatcher("login.jsp").forward(request,response);
            return;
        }


    }

    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("add.jsp").forward(request,response);
    }

    @Override
    public void show(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }


}

package com.student;

import com.utill.StringUtil;

import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class PicServlet extends HttpServlet {
    //图片的宽和高
    private int height = 0, width = 0;
    //生成验证码的字符池
    private String source = "qwertyuiopasdfghjklzxcvbnm1234567890";

    //初始化图片参数
    public void init() throws ServletException {
        //初始化高和宽
        String str = this.getServletConfig().getInitParameter("height");
        try {
            height = Integer.valueOf(str);
        } catch (Exception e) {
            height = 40;
        }
        str=this.getServletConfig().getInitParameter("width");
        try {
            width=Integer.valueOf(str);
        }catch (Exception e){
            width=130;
        }
        //初始化其中可能出现字符str
        str=this.getServletConfig().getInitParameter("source");
        if(StringUtil.isNotBlank(str)){
            source=str;
        }

    }

    //随机选中字符组成图片中的内容
    private String getString(int len){
        Random ran =new Random();
        StringBuilder sb =new StringBuilder();
        for (int a =0;a<len;a++){
            sb.append(source.charAt(ran.nextInt(source.length())));
        }
        return  sb.toString();

    }

    //生成并写出图片
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedImage bufferedImage=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //获取验证码内容
        String checkcode=this.getString(6);
        //将验证码存储在session中
        HttpSession session=request.getSession();
        session.setAttribute("checkcode",checkcode);

        Graphics graphics=bufferedImage.getGraphics();
        graphics.setColor(Color.red);
        graphics.setFont(new Font("宋体",Font.BOLD,28));
        graphics.drawString(checkcode,10,height-10);
        graphics.dispose();

        response.setContentType("image/jpeg");
        response.setHeader("Pragma","no-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires",0);
        ServletOutputStream sos=response.getOutputStream();
        ImageIO.write(bufferedImage,"jpg",sos);
        sos.flush();
        sos.close();

    }



}

package com.utill;

public final class StringUtil {
    private StringUtil(){}
    //判断是否为空
    public static boolean isBlank(String str){
        return str==null || str.trim().length()==0;
    }

    public static boolean isNotBlank(String str){
        return !isBlank(str);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值