Javaweb小案例:用户登录

用户登录案例需求:
1.编写login.html登录页面 username & password 两个输入框
2.使用Druid数据库连接池技术,操作mysql,创建数据库中user表
3.使用JdbcTemplate技术封装JDBC
4.登录成功跳转到SuccessServlet展示:登录成功!用户名,欢迎您
5.登录失败跳转到FailServlet展示:登录失败,用户名或密码错误

步骤:
1 现在数据库中创建username 和 password的关系表

CREATE DATABASE loginbase;
USE loginbase;

CREATE TABLE USER(

id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE NOT NULL,
PASSWORD VARCHAR(32) NOT NULL
);

并在表中插入数据
在这里插入图片描述


编写一个用户的实体类User

package domain;

public class User {
    private int id;
    private String username;
    private String 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;
    }
}


编写一个工具类JDBCUtils连接数据库(使用JdbcTemplate技术封装JDBC)


package util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;


/**
		 * JDBC工具类 使用Durid连接池
		 */
public class JDBCUtils {
    private static DataSource ds;

    static {
        try {
            //加载配置文件
            Properties pro = new Properties();
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);
            //初始化连接池对象
            ds = DruidDataSourceFactory.createDataSource(pro);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {

        }

    }

    /*
    获取连接池对象
     */
    public static DataSource getDataSource() {
        return ds;
    }

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


记得在 druid.properties 配置连接数据库的一些相关参数


编写一个UserDao类来操作数据库,提供login方

package dao;

import domain.User;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import util.JDBCUtils;

/*
操作数据库中User表
 */
public class UserDao {
    //声明JDBCTemplate对象共用
    private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());

public User Login(User loginUser){
    try {
        //编写sql
        String sql = "select * from user where username = ? and password = ?";
        //调用query方法
        User user = template.queryForObject(sql,
                new BeanPropertyRowMapper<User>(User.class),
                loginUser.getUsername(), loginUser.getPassword());

        return user;
    }catch (DataAccessException e){
        return null;
    }
}
}



编写LoginServlet

package servlet;

import dao.UserDao;
import domain.User;
import org.apache.commons.beanutils.BeanUtils;

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;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
    public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");//设置编码
//            //设置请求参数
//            String username = req.getParameter("username");
//            String password = req.getParameter("password");
//            //封装user对象
//            User loginuser = new User();
//            loginuser.setUsername(username);
//            loginuser.setPassword(password);
            //获取所有请求参数
        Map<String, String[]> map = req.getParameterMap();
        //创建user对象
        User loginUser = new User();
        //使用BeanUtils封装
        try {
            BeanUtils.populate(loginUser,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //调用UserDao的login方法
            UserDao dao = new UserDao();
            User user = dao.Login(loginUser);
            //判断User
            if(user==null){
                //登录失败
                req.getRequestDispatcher("/failServlet").forward(req,resp);
            }else{ //登录成功
                //存储数据
                req.setAttribute("user",user);
                //转发
                req.getRequestDispatcher("/successServlet").forward(req,resp);
            }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}



密码正确后跳转的SuccessServlet类

package servlet;

import domain.User;

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("/successServlet")
public class SuccessServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getAttribute("user");
        if (user!=null) {
            resp.setContentType("text/html;charset=utf-8");//设置编码
            resp.getWriter().write("登陆成功!" + user.getUsername() + "欢迎您");//输出
        }
    }
}


密码错误后跳转的FailServlet类

package 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("/failServlet")
public class FailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");//设置编码
        resp.getWriter().write("登录失败,用户名或密码错误");//输出

    }
}


最后写一个login.html登录页面


"en">

    "UTF-8">
    Title


        
"/LoginDemo_war_exploded/loginServlet" method="post"> 用户名:"text" name="username">
密码:"password" name="password">
"submit" value="登录">

总结:
在做这个Demo的时候,我经常会在一些类中出现一些路径错误的问题。

最大的一个bug就是在提交账户密码时候,不能跳转到LoginServlet,而是出现了500这个服务器错误:Javaweb小案例:用户登录_第1张图片
我仔细看好久自己的代码是否出行编写错误,并通过测试类测试出JDBCUtils 和 UserDao两个类是能够正确从数据库中提取数据的,包也按照教程给的全部导进去了,最后把教程原先给的包:
Javaweb小案例:用户登录_第2张图片
换成了下面
Javaweb小案例:用户登录_第3张图片
报错解决。

你可能感兴趣的:(JavaWeb,小项目,mysql,数据库,java,jdbc)