javaweb之servlet技术实现登录功能

一,需求分析

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

二,技术实现

项目目录结构:
javaweb之servlet技术实现登录功能_第1张图片
1,前端页面

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
    <title>Login</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

</head>
<body>

<form class="form-horizontal" action="/login_project/login" method="post">
    <div class="form-group">
        <label for="inputEmail3" class="col-sm-2 control-label">用户名:</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" name="username" id="inputEmail3" placeholder="请输入用户名">
        </div>
    </div>
    <div class="form-group">
        <label for="inputPassword3" class="col-sm-2 control-label">密码:</label>
        <div class="col-sm-10">
            <input type="password" class="form-control" name="password" id="inputPassword3" placeholder="请输入密码">
        </div>
    </div>

    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-default">登录</button>
        </div>
    </div>
</form>


<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="js/jquery-3.2.1.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>

2,servlet代码:

@WebServlet("/login")
public class login extends HttpServlet {
     
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     
        request.setCharacterEncoding("utf-8");
        /*
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        */

        User user = new User();
        Map<String, String[]> map = request.getParameterMap();
        try {
     
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException e) {
     
            e.printStackTrace();
        } catch (InvocationTargetException e) {
     
            e.printStackTrace();
        }
        System.out.println(user);
        //User{id=null, username='张三', password='123'}
        //密码错误:User{id=null, username='张三峰', password='852'}
        System.out.println("---------");

        UserDao ud = new UserDao();
        User user_login = ud.loginUser(user);
        System.out.println(user_login);
        //User{id=1, username='张三', password='123'}
        //密码错误,null


        if (user_login == null) {
     
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("用户名或者密码错误,登录失败!");
        } else {
     
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(user_login.getUsername() + "你好,登录成功!");
        }

    }

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

3,User代码:

package domain;

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

    public Integer getId() {
     
        return id;
    }

    public void setId(Integer 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 + '\'' +
                '}';
    }
}

4,UserDao代码:

public class UserDao {
     

    public User loginUser(User user){
     
        try {
     
            JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDatasource());
            String sql = "select * from user where username= ? and password= ? ";
            User user_login = template.queryForObject(sql,
                    new BeanPropertyRowMapper<>(User.class),
                    user.getUsername(),
                    user.getPassword());
            return user_login;
        }catch (Exception e){
     
            e.printStackTrace();
            return null;
        }

    }
}

5,JDBCUtils代码:

public class JDBCUtils {
     
    private static DataSource ds;
    static {
     
        Properties pro = new Properties();
        try {
     
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
     
            e.printStackTrace();
        } catch (Exception e) {
     
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
     
        return ds.getConnection();
    }

    public static void close(Statement sttm,Connection conn){
     
        if (sttm != null){
     
            try {
     
                sttm.close();
            } catch (SQLException e) {
     
                e.printStackTrace();
            }
        }
        if (conn != null){
     
            try {
     
                conn.close();
            } catch (SQLException e) {
     
                e.printStackTrace();
            }
        }

    }

    public static void close(ResultSet rs,Statement sttm, Connection conn){
     
        if (rs != null){
     
            try {
     
                rs.close();
            } catch (SQLException e) {
     
                e.printStackTrace();
            }
        }
        close(sttm,conn);

    }

    public static DataSource getDatasource(){
     
        return ds;
    }
}

6,TestLogin代码

public class TestLogin {
     

    @Test
    public void UserDao(){
     
        UserDao userDao = new UserDao();
        User user = new User();
        user.setUsername("chs");
        user.setPassword("321");
        User user1 = userDao.loginUser(user);
        System.out.println(user1);
    }

}

三,需注意技术细节

1,login.html中form表单的action路径的写法:
/虚拟目录/Servlet的资源路径

2,BeanUtils工具类:
简化数据封装,用于封装JavaBean的

JavaBean:标准的Java类
要求:
1,类必须被public修饰
2, 必须提供空参的构造器
3,成员变量必须使用private修饰
4,提供公共setter和getter方法
功能:封装数据

3,概念:
成员变量:成员方法外的变量;
属性:setter和getter方法截取后的产物
例如:getUsername() --> Username–> username

4,BeanUtils方法:
setProperty()
getProperty()
populate(Object obj , Map map):将map集合的键值对信息,封装到对应的JavaBean对象中。

5,jar包必须写在web目录下的WEB-INF下的lib文件夹中。

你可能感兴趣的:(java,jdbc,web,servlet,数据库)