Java 之 request 案例——用户登录

用户登录案例需求:

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

  

分析示意图:

Java 之 request 案例——用户登录_第1张图片

开发步骤:

1、创建 JavaEE项目,创建 login.html 页面,创建durid.properties配置文件,导入 jar包

2、创建数据库环境

1 CREATE DATABASE db1;
2 USE db1;
3 CREATE TABLE USER(
4         
5   id INT PRIMARY KEY AUTO_INCREMENT,
6   username VARCHAR(32) UNIQUE NOT NULL,
7   PASSWORD VARCHAR(32) NOT NULL
8);

 

3、创建 JavaBean,User类

 1 /*
 2 javaBean 类
 3  */
 4 public class User {
 5 
 6     private int id;
 7     private String username;
 8     private String password;
 9 
10     public User() {
11     }
12 
13     public User(int id, String username, String password) {
14         this.id = id;
15         this.username = username;
16         this.password = password;
17     }
18 
19     @Override
20     public String toString() {
21         return "User{" +
22                 "id=" + id +
23                 ", username='" + username + '\'' +
24                 ", password='" + password + '\'' +
25                 '}';
26     }
27 
28     public int getId() {
29         return id;
30     }
31 
32     public void setId(int id) {
33         this.id = id;
34     }
35 
36     public String getUsername() {
37         return username;
38     }
39 
40     public void setUsername(String username) {
41         this.username = username;
42     }
43 
44     public String getPassword() {
45         return password;
46     }
47 
48     public void setPassword(String password) {
49         this.password = password;
50     }
51 }
View Code

 

4、创建数据库连接池工具类 JDBCUtils

 1 import com.alibaba.druid.pool.DruidDataSourceFactory;
 2 
 3 import javax.sql.DataSource;
 4 import java.io.IOException;
 5 import java.io.InputStream;
 6 import java.sql.Connection;
 7 import java.sql.SQLException;
 8 import java.util.Properties;
 9 
10 public class JDBCUtils {
11 
12     private static DataSource ds;
13 
14     static {
15         try {
16             // 加载配置文件
17             Properties prop = new Properties();
18 
19             //使用classloader 加载配置文件进内存
20             InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
21 
22             prop.load(is);
23 
24             // 初始化连接池对象
25             ds = DruidDataSourceFactory.createDataSource(prop);
26         } catch (IOException e) {
27             e.printStackTrace();
28         } catch (Exception e) {
29             e.printStackTrace();
30         }
31     }
32 
33     /*
34         获取连接池对象
35      */
36     public static DataSource getDataSource() {
37         return ds;
38     }
39 
40     /*
41         获取连接connection对象
42      */
43     public static Connection getConnection() throws SQLException {
44         return ds.getConnection();
45     }
46 }
View Code

 

5、创建 UserDao类,提供 login 方法

 1 import org.springframework.dao.DataAccessException;
 2 import org.springframework.jdbc.core.BeanPropertyRowMapper;
 3 import org.springframework.jdbc.core.JdbcTemplate;
 4 
 5 public class UserDao {
 6     //声明 JDBCTemplate 对象共用
 7     private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
 8 
 9     /**
10      * 登录方法
11      * @param loginUser 只有用户名和密码
12      * @return user 包含用户的全部数据没有查询到返回 null
13      */
14    public User login(User loginUser) {
15 
16        try {
17            // 编写 SQL
18            String sql = "select * from user where username = ? and password = ?";
19 
20            // 调用query 方法
21            User user = template.queryForObject(sql,
22                     new BeanPropertyRowMapper(User.class),
23                    loginUser.getUsername(),loginUser.getPassword());
24 
25            return user;
26        } catch (DataAccessException e) {
27            e.printStackTrace();
28            return null;
29        }
30 
31 
32 
33    }
34 }
View Code

 

6、测试 login 方法

 1 import org.junit.Test;
 2 
 3 public class LoginTest {
 4 
 5     @Test
 6     public void test() {
 7         User loginuser = new User();
 8         loginuser.setUsername("admin");
 9         loginuser.setPassword("admin");
10         UserDao dao = new UserDao();
11 
12         User user = dao.login(loginuser);
13         System.out.println(user);
14 
15     }
16 }
View Code

 

7、编写  loginServlet 类

 1 import org.apache.commons.beanutils.BeanUtils;
 2 
 3 import javax.servlet.ServletException;
 4 import javax.servlet.annotation.WebServlet;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import java.io.IOException;
 9 import java.lang.reflect.InvocationTargetException;
10 import java.util.Map;
11 
12 @WebServlet("/loginservlet")
13 public class LoginServlet extends HttpServlet {
14     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
15         // 1.设置编码
16         request.setCharacterEncoding("utf-8");
17 
18        // 2 获取请求参数
19          String username = request.getParameter("username");
20         String password = request.getParameter("password");
21 
22         // 3 封装 user 对象
23        User loginUser = new User();
24 
25         loginUser.setUsername(username);
26         loginUser.setPassword(password);
27 
28        
29         // 4.调用 userdao 的 login方法
30         UserDao dao = new UserDao();
31         User user = dao.login(loginUser);
32 
33         //5. 判断
34         if(user == null) {
35             request.getRequestDispatcher("/failServlet").forward(request,response);
36         } else {
37             request.setAttribute("user",user);
38             request.getRequestDispatcher("/successServlet").forward(request,response);
39         }
40     }
41 
42     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
43         this.doPost(request,response);
44     }
45 }
View Code

 

8、编写 FailServlet 类和 SuccessServlet 类

  FailServlet 类

 1 import javax.servlet.ServletException;
 2 import javax.servlet.annotation.WebServlet;
 3 import javax.servlet.http.HttpServlet;
 4 import javax.servlet.http.HttpServletRequest;
 5 import javax.servlet.http.HttpServletResponse;
 6 import java.io.IOException;
 7 
 8 @WebServlet("/failServlet")
 9 public class FailServlet extends HttpServlet {
10     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
11         response.setContentType("text/html;charset=utf-8");
12 
13         response.getWriter().write("登录失败");
14     }
15 
16     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
17 
18     }
19 }
View Code

 

  SuccessServlet 类

 1 import javax.servlet.ServletException;
 2 import javax.servlet.annotation.WebServlet;
 3 import javax.servlet.http.HttpServlet;
 4 import javax.servlet.http.HttpServletRequest;
 5 import javax.servlet.http.HttpServletResponse;
 6 import java.io.IOException;
 7 
 8 @WebServlet("/successServlet")
 9 public class SuccessServlet extends HttpServlet {
10     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
11         User user = (User) request.getAttribute("user");
12 
13         if(user!=null) {
14             // 设置编码
15             request.setCharacterEncoding("utf-8");
16             response.setContentType("text/html;charset=utf-8");
17 
18             response.getWriter().write("登录成功"+user.getUsername()+"欢迎您");
19         }
20     }
21 
22     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
23 
24     }
25 }
View Code

 

9、login.html中form表单的action路径的写法

action="虚拟目录+Servlet的资源路径"

  

转载于:https://www.cnblogs.com/niujifei/p/11620609.html

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