Servlet—Request案例:用户登录

  • 项目源码已上传GitHub:源码链接

用户登录案例需求

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

登录案例逻辑分析

Servlet—Request案例:用户登录_第1张图片

开发步骤

  1. 创建项目,导入html页面,配置文件,jar包
  2. 创建数据库的环境
create database duing;
use duing;
create table user(
	id int primary key auto_increment,
    username varchar(32) unique not null,
    password varchar(32) not null
);

Servlet—Request案例:用户登录_第2张图片
3. 创建包duing.domain,创建User类

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
  1. 创建包ding.util,编写工具类JDBCUtils
/**
 * JDBC工具类 使用的是Durid连接池
 */
public class JDBCUtils {
    private static DataSource ds;

    static{
        //1.加载配置文件
        try {
        Properties pro = new Properties();
        //使用ClassLoader加载配置文件,获取字节输入流
        InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
        pro.load(is);
        //2.初始化连接池对象
        ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

    /**
     * 获取连接Connection对象
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
}
  1. 创建包duing.dao,创建类UserDao,提供login方法
public class UserDao {
    //声明JDBCTemplate对象共用
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSouce());
    /**
     * 登录方法
     * @param loginUser 只有用户名和密码
     * @return User 包含用户全部数据
     */
    public User login(User loginUser){
        try{
            //1.编写sql语句
            String sql = "select * from user where username = ? and password = ?";
            //2.调用query方法
            User user = template.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),loginUser.getUsername(),loginUser.getPassword());

            return user;
        }catch (DataAccessException e){
            e.printStackTrace();
            return null;
        }
    }
}
  1. 单元测试,测试数据库登录链接是否可行
public class UserDaoTest {
    @Test
    public void testLogin(){
        User loginuser = new User();
        loginuser.setUsername("zhangsan");
        loginuser.setPassword("123");

        UserDao dao = new UserDao();
        User user = dao.login(loginuser);

        System.out.println(user);
    }
}
  • 测试结果:
    Servlet—Request案例:用户登录_第3张图片
  1. 编写duing.web.servlet.LoginServlet类
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");
        //2.获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //3.封装User对象
        User loginUser = new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);
        //4.调用UserDao的login方法
        UserDao dao = new UserDao();
        User user = dao.login(loginUser);
        //5.判断user
        if(null==user){
            //登陆失败
            request.getRequestDispatcher("/failServlet").forward(request,response);
        }else{
            //登陆成功
            //存储数据
            request.setAttribute("user",user);
            //转发
            request.getRequestDispatcher("/successServlet").forward(request,response);
        }
    }
}
@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 {
        doPost(request,response);
    }
}

@WebServlet("/successServlet")
public class SuccessServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取requ域中共享的user对象
        User user = (User) request.getAttribute("user");
        if(null != user){
            //给页面写一句话
            //设置页面的编码
            response.setContentType("text/html;charset=utf-8");
            //输出
            response.getWriter().write("登录成功!"+user.getUsername()+",欢迎您");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
  1. login.html中form表单的action路径的写法
  • 虚拟目录+Servlet的资源路径

  • 项目测试:
    在这里插入图片描述
    Servlet—Request案例:用户登录_第4张图片
    在这里插入图片描述
    Servlet—Request案例:用户登录_第5张图片
    在这里插入图片描述

你可能感兴趣的:(Servlet,request,java)