登录案例login

该博客展示了如何实现一个简单的Java Web登录系统,包括User类、UserDao操作数据库、登录页面、JdbcUtils工具类以及Servlet处理登录请求。通过Druid数据源连接MySQL数据库,当登录成功时重定向到successServlet,失败则重定向到failServlet。此外,还提出使用BeanUtils简化了Servlet中参数封装到User对象的过程。
摘要由CSDN通过智能技术生成

题目与分析

在这里插入图片描述
a

实现

User类

public class User {
    private int id;
    private String username;
    private String password;

    public User() {
    }

    public User(int id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int 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;
    }

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

UserDao 操作数据库

/**
 * 操作数据库中user表的类
 */
public class UserDao {
    private JdbcTemplate template=new JdbcTemplate(JdbcUtils.getDataSource());
    /**
     * 登录方法
     * @param loginUser 只有用户名和密码
     * @return user包含用户的全部信息
     */
    public User login(User loginUser){
        try{
            String sql="select * from user where username=? and password=?";
            User user = template.queryForObject(sql,
                    new BeanPropertyRowMapper<User>(User.class),
                    loginUser.getUsername(), loginUser.getPassword());

            return user;
        }catch (EmptyResultDataAccessException e){
            e.printStackTrace();
            return null;
        }
    }
}

登陆页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<form action="Servlet" method="post">
    <label>用户名</label><input name="username" type="text" placeholder="请输入用户名"><br>
    <label>密码</label><input name="password" type="text" placeholder="请输入密码"><br>
    <input type="submit" value="登录">
</form>
</body>
</html>

JdbcUtils工具类

/**
 * Jdbc的工具类
 */
public class JdbcUtils {
    private static DataSource ds;
    static {
        try {
            //1.加载配置文件
            Properties pro=new Properties();
            pro.load(JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //2.初始化对象
            ds = DruidDataSourceFactory.createDataSource(pro);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取连接池对象
     */

    public static DataSource getDataSource(){
        return ds;
    }
    /**
     * 获取连接对象
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
}

Servlet


@WebServlet("/Servlet")
public class Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");
        //2.获取参数
        String username = request.getParameter("username");
        String password=request.getParameter("password");
        User loginUser=new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);
        //3.存储

        UserDao dao=new UserDao();
        User user=dao.login(loginUser);
        request.setAttribute("User",user);
        //4.转发
        if (user!=null){
            request.getRequestDispatcher("/successServlet").forward(request,response);
        }else {
            request.getRequestDispatcher("/failServlet").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

successServlet

@WebServlet("/successServlet")
public class successServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8");

        User user = (User) request.getAttribute("User");

        response.getWriter().write("登录成功!"+user.getUsername()+"欢迎您");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

failServlet

@WebServlet("/failServlet")
public class failServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8");
        response.getWriter().write("登录失败!请重新登录!");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

druid.properties

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///day14
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000

注意

  1. web注释,括号里面需要/
  2. xml里的form表单的action属性里不要/
  3. web目录下有WEB-INF(里面有lib),xml
  4. response设置编码:response.setContentType(“text/html; charset=UTF-8”);

效果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

改进

使用BeanUils,简化数据的封装。Servlet里获取参数封装到loginUser对象中:

 Map<String, String[]> map = request.getParameterMap();
        User loginUser=new User();
        try {
            BeanUtils.populate(loginUser,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值