jsp 实现登录和查询所有的用户信息

数据库

create table users(
	id bigint primary key auto_increment,
    username varchar(20) ,
    password varchar(20),
    sex boolean default 1,
    age bigint,
    birth date,
    salary double(10,2)
)engine=innodb default charset utf8;

insert into users values
(10010,"zhangsan","123456789",0,20,"1999-10-30",1234.12),
(10011,"lisi",	  "123456789",1,22,"1998-01-11",0.0),
(10012,"wangwu",  "123456789",1,20,"2000-02-10",2222.12),
(10013,"zhaoliu", "123456789",1,24,"1997-01-30",4444.4),
(10014,"tianti",  "123456789",0,28,"1992-10-30",5432.1),
(null,"nengneng","123456789",0,24,"1999-03-21",3333.2);

首页

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>用户管理系统</title>
</head>
<body>
<h1>用户登录及注册
</h1>
<br/>
<a href="us.do?action=logindo">用户登录</a>
<a href="us.do?action=adddo">用户注册</a>
<a href="us.do?action=selectAll">查询所有用户信息</a>
</body>
</html>

工具类

package com.example.utill;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
public class JdbcUtil {
    private JdbcUtil(){}

    private  static  final  JdbcUtil jdnc =new JdbcUtil();

    public static JdbcUtil getInstance(){
        return jdnc;
    }

    private  static final Vector<Connection> pool = new Vector<>();
    private final static  String  DRIVER_CLASS_NAME="com.mysql.cj.jdbc.Driver";
    private final  static  String URL="jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
    private final static  String USERNAME="root";
    private final static String PASSWORD="123456789";
    private static final int MAX_SIZE=10;

    static {
        try{
            Class.forName(DRIVER_CLASS_NAME);
            for (int a =0;a<5;a++){
                Connection cono= DriverManager.getConnection(URL,USERNAME,PASSWORD);
                pool.add(cono);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public Connection getConnection() throws Exception{
        Connection cono=null;
        if(pool!=null&&pool.size()>0){
            cono=pool.remove(pool.size()-1);
        }else {
            cono=DriverManager.getConnection(URL,USERNAME,PASSWORD);
        }
        return cono;
    }

    public void colse(ResultSet re , PreparedStatement ps, Connection co)throws Exception{
        try{
            if(re!=null){
                re.close();
            }
            if(ps!=null){
                ps.close();
            }
        }finally {
            if(co!=null){
                if(pool.size()<MAX_SIZE){
                    pool.add(co);
                }else {
                    co.close();
                }
            }
        }
    }

    public PreparedStatement createPreparedStatement(Connection co ,String sql,Object...params)throws Exception{
        PreparedStatement ps =null;
        if(co!=null){
            ps=co.prepareStatement(sql);
            if(params!=null&&params.length>0){
                for (int a =0;a<params.length;a++){
                    ps.setObject(a+1,params[a]);
                }
            }
        }
        return ps;
    }

    public ResultSet executeQuery(Connection co , String sql ,Object ... params)throws Exception{
        ResultSet re =null;
        if(co!=null){
            PreparedStatement ps =createPreparedStatement(co,sql,params);
            re=ps.executeQuery();
        }
        return  re;
    }

    public int executeUpdate(Connection co , String sql ,Object ... params)throws Exception{
        int res =0;
        if(co!=null){
            PreparedStatement ps =createPreparedStatement(co,sql,params);
            res=ps.executeUpdate();
        }
        return  res;
    }

}

package com.example.utill;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class RequestUtil {
    public static String ERROR_KEY="error";
    private RequestUtil(){}

    public static String getParmater(HttpServletRequest request,String key)throws Exception{
        if(request==null&&key==null){
            throw new Exception();
        }
        String str =request.getParameter(key);
        if(str!=null){
            return  "";
        }else {
            return str;
        }
    }

    public static String getError(HttpServletRequest request,String key)throws Exception{
        if (request==null&&key==null){
            throw new Exception();
        }
        Object obj =request.getAttribute(ERROR_KEY);
        String str="";
        if(obj!=null&&obj instanceof Map){
            Map<String,String> map=(Map<String, String>) obj;
            if(map.containsKey(key)){
                str=map.get(key);
            }
        }
        return str;
    }
}

package com.example.utill;

public final class StringUtil {
    private StringUtil(){}
    public static boolean isBank(String str){
        return  str==null||str.length()==0;
    }
    public static  boolean isNotBank(String str){
        return !isBank(str);
    }
}

工厂类

package com.example.format;

import com.example.dao.UserBin;

public class Format {
    public static UserBin getUserBin(){
        return new UserBin();
    }
}

数据库连接

package com.example.dao;

import com.example.bean.User;

import java.util.List;

public interface UserDao {
    public Boolean login(User user)throws Exception;
    public List<User> selectAll()throws Exception;
}

package com.example.dao;

import com.example.bean.User;
import com.example.utill.JdbcUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UserBin implements UserDao{

    private JdbcUtil jd =JdbcUtil.getInstance();
    public Boolean login(User user) throws Exception {
        String username=user.getUsername();
        String password =user.getPassword();
        Connection co =null;
        ResultSet re =null;
        boolean bb =false;
        try {
            co=jd.getConnection();
            String sql="select * from users where username =? and password =? ";
            re =jd.executeQuery(co,sql,username,password);
            if(re.next()){
                bb=true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jd.colse(re,null,co);
        }
        return bb;
    }

    //查询所有用户信息
    public List<User> selectAll() throws Exception {
        List<User> list =new ArrayList<>();
        Connection co =null;
        ResultSet re =null;
        try{
            co=jd.getConnection();
            String sql ="select * from users";
            re=jd.executeQuery(co,sql,null);
            while (re.next()){
                User us =getUser(re);
                list.add(us);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jd.colse(re,null,co);
        }
        return list;
    }

    // id    | username | password  | sex  | age  | birth      | salary  |
    //+-------+----------+-----------+------+------+------------+---------+
    //| 10010 | zhangsan | 123456789 |    0 |   20 | 1999-10-30 | 1234.12 |
    public User getUser(ResultSet re)throws Exception{
        User us =new User();
        us.setId(re.getLong("id"));
        us.setUsername(re.getString("username"));
        us.setPassword(re.getString("password"));
        us.setSex(re.getBoolean("sex"));
        us.setAge(re.getLong("age"));
        us.setBirth(re.getDate("birth"));
        us.setSalary(re.getDouble("salary"));
        return us;
    }
}

值并

package com.example.bean;

import java.util.Date;

public class User {
    // id    | username | password  | sex  | age  | birth      | salary  |
    //+-------+----------+-----------+------+------+------------+---------+
    //| 10010 | zhangsan | 123456789 |    0 |   20 | 1999-10-30 | 1234.12 |
    private Long id;
    private String username;
    private String password;
    private Boolean sex;
    private Long age;
    private Date birth;
    private Number salary;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Boolean getSex() {
        return sex;
    }

    public void setSex(Boolean sex) {
        this.sex = sex;
    }

    public Long getAge() {
        return age;
    }

    public void setAge(Long age) {
        this.age = age;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Number getSalary() {
        return salary;
    }

    public void setSalary(Number salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", sex=" + sex +
                ", age=" + age +
                ", birth=" + birth +
                ", salary=" + salary +
                '}';
    }
}

用户登录

package com.example.login;

import com.example.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 BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String action = req.getParameter("action");
        if(StringUtil.isBank(action)){
            action="show";
        }
        try{
            Class clz =this.getClass();
            Method method=clz.getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(this,req,resp);
        }catch (Exception e){
            show(req,resp);
        }

    }

    public abstract void show(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ;
}

package com.example.login;

import com.example.bean.User;
import com.example.dao.UserBin;
import com.example.format.Format;
import com.example.utill.RequestUtil;
import com.example.utill.StringUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServlet extends BaseServlet {

    public void logindo(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");
        Map<String,String> errors=new HashMap<>();
        if(StringUtil.isBank(username)){
            errors.put("username","用户名不能为空");
        }
        if (StringUtil.isBank(password)){
            errors.put("password","用户密码不能为空");
        }
        if(errors!=null&&errors.size()>0){
            request.setAttribute(RequestUtil.ERROR_KEY,errors);
            request.getRequestDispatcher("login.jsp").forward(request,response);
            return;
        }
        //连接数据库
        User us =new User();
        us.setUsername(username);
        us.setPassword(password);
        UserBin  ub= Format.getUserBin();
        Boolean bb =null;
        try {
            bb=ub.login(us);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(bb){
            response.sendRedirect("us.do");
        }else {
            request.setAttribute("msg","登录失败");
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }

    }

    public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserBin us =Format.getUserBin();
        try {
            List<User> li = us.selectAll();
            request.setAttribute("userList",li);
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.getRequestDispatcher("selectAll.jsp").forward(request,response);
    }

    public void select(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    public void adddo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }



    @Override
    public void show(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

图片

package com.yan.action;

import com.yan.util.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 width=0,height=0;
    private String source="abcdefghijklmnopqrstuvwxyz";

    @Override
    public void init() throws ServletException {
        String ss=this.getServletConfig().getInitParameter("width");
        try{
            width=Integer.parseInt(ss);
        }catch (Exception e){
            width=120;
        }
        ss=this.getServletConfig().getInitParameter("height");
        try{
            height=Integer.parseInt(ss);
        }catch (Exception e){
            height=120;
        }
        ss=this.getServletConfig().getInitParameter("source");
        if(StringUtil.isNotBlank(ss))
            this.source=ss;
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedImage bufferedImage=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        String checkcode=this.generateCode(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();

    }

    private String generateCode(int len) {
        Random r=new Random();
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<len;i++){
            int pos=r.nextInt(source.length());
            sb.append(source.charAt(pos));
        }
        return sb.toString();
    }

}

依赖

 <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>

jsp页面

<%@ page import="com.example.utill.RequestUtil" %><%--
  Created by IntelliJ IDEA.
  User: Shinelon
  Date: 2021/4/12
  Time: 22:16
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户登录</title>
    <style>
        .error {
            color: crimson;
        }
    </style>
    <script>
        document.getElementById("im1").src = "p"
    </script>
</head>
<body>

<form method="post" action="us.do?action=login">
    <table>
        <tr>
            <td>用户名称</td>
            <td>
                <input name="username" value='<%=request.getParameter("username")
                    ==null?"":request.getParameter("username")%>'>
                <span class="error">
                    <%=RequestUtil.getError(request,"username")%>
                </span>
            </td>
        </tr>

        <tr>
            <td>用户密码</td>
            <td>
                <input name="password" type="password">
                <span class="error">
                    <%=RequestUtil.getError(request,"username")%>
                </span>
            </td>
        </tr>

        <tr>
            <td colspan="2">
                <input type="checkbox"  name="checkbox">记住密码
            </td>
        </tr>

        <tr>
            <td colspan="2">
                <input type="submit" value="提交数据">
                <input type="reset" value="重置数据" >
            </td>
        </tr>

        <caption><%=request.getAttribute("msg")==null?"":request.getAttribute("msg")%></caption>
    </table>

</form>


</body>
</html>

<%@ page import="java.util.List" %>
<%@ page import="com.example.bean.User" %><%--
  Created by IntelliJ IDEA.
  User: Shinelon
  Date: 2021/4/12
  Time: 23:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>所有用户信息</title>
</head>
<body>

<table border="2px">
    <thead>
    <td>用户编号</td>
    <td>用户账户</td>
    <td>用户密码</td>
    <td>用户年龄</td>
    <td>用户生日</td>
    <td>用户性别</td>
    <td>用户收入</td>
    </thead>
    <tbody>
    <%
        Object obj = request.getAttribute("userList");
        if (obj != null && obj instanceof List) {
            List<User> list = (List<User>) obj;
            for (User us : list) {
    %>
    <tr>
        <td><%=us.getId() %>
        </td>
        <td><%=us.getUsername() %>
        </td>
        <td><%=us.getPassword() %>
        </td>
        <td><%=us.getAge() %>
        </td>
        <td><%=us.getBirth() %>
        </td>
        <td><%=us.getSex() %>
        </td>
        <td><%=us.getSalary() %>
        </td>
            <%
                    }
                }else{
                %>
    <tr>
        <td colspan="7">没有任何用户信息</td>
    </tr>

    <%
        }
    %>
    </tbody>
</table>


</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值