用户登录

需求

  1. 编写login.html登录页面,username&password两个输入框

  2. 使用Druid数据库连接池技术,操作mysql,db2数据库中的user表

  3. 使用JdbcTemplate技术封装JDBC

    4.登录成功跳转到SuccessServlet展示:登录成功 用户名,欢迎您

  4. 登录失败跳转到FailServlet展示:登录失败,用户名或密码错误

演示

login.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>

<form method="post" action="/loginservlet">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>

</body>
</html>

druid.properties

1
2
3
4
5
6
7
8
9
10
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db3?useSSL=false&serverTimezone=GMT%2B8
username=root
password=root
#初始化连接数量
initialSize=5
#最大连接数
maxActive=10
#最大等待时间
maxWait=3000

这两个是最基本的文件,jar包我直接使用maven导入了,不多说

  • 步骤:

    1. 创建项目,导入html页面,配置文件,jar包

    2. 配置数据库环境

    3. 创建包cn.itcast.domain,创建类User

    4. 创建包cn.itcast.dao,创建类UserDao,提供login方法

    5. 创建cn.itcast.web.servlet.LoginServlet类

    6. login.html中form表单的action路径是虚拟路径

用户实体类User

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package cn.itcast.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;
}

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

JDBC工具类JDBCUtil

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package cn.itcast.until;

import com.alibaba.druid.pool.DruidDataSourceFactory;

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

/**
* JDBC工具类 使用Druid连接池
*/

public class JDBCUtil {
private static DataSource ds;

static {
try {
//1.加载配置文件
Properties pro=new Properties();
//使用ClassLoader加载配置文件,获取字节输入流
InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("src/main/resources/druid.properties");
pro.load(is);

//2.初始化连接池对象
ds=DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}


}

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

//2.获取Connection对象

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

}

操作类UserDao

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package cn.itcast.dao;

import cn.itcast.domain.User;
import cn.itcast.until.JDBCUtil;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

/**
* 操作数据库中User表的类
*/


public class UserDao {

//声明JDBCTemplate对象公用
private JdbcTemplate template=new JdbcTemplate(JDBCUtil.getDataSource());



/**
* 登陆方法
* @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;
}

}
}

创建LoginServlet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package cn.itcast.web.servlet;

import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}

@Override
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 (user==null){
//登录失败
request.getRequestDispatcher("/failServlet").forward(request, response);
}else{
//登录成功
//存储数据
request.setAttribute("user",user);
//转发
request.getRequestDispatcher("/successServlet").forward(request, response);
}
}
}

failServlet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package cn.itcast.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class FailServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//给页面写一句话

//设置编码
response.setContentType("text/html;charset=utf-8");
//输出
response.getWriter().write("登录失败,用户名或密码错误");
}

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

successServlet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package cn.itcast.web.servlet;

import cn.itcast.domain.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SuccessServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取request域中共享的user对象
User user = (User) request.getAttribute("user");

if (user!=null){
//给页面写一句话

//设置编码
response.setContentType("text/html;charset=utf-8");
//输出
response.getWriter().write("登录成功"+user.getUsername()+"欢迎您");
}

}

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

BeanUtils工具类

BeanUtils实际上就是帮助封装的工具类

先将LoginServlet中的封装过程注释掉,并使用BeanUtils

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package cn.itcast.web.servlet;

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

import javax.servlet.ServletException;
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;

public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}

@Override
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);
//2.获取所有请求参数
Map<String, String[]> map = request.getParameterMap();
//3.创建User对象
User loginUser = new User();
try {
//3.1使用BeanUtils封装
BeanUtils.populate(loginUser,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}

//4.调用UserDao的login方法
UserDao dao=new UserDao();
User user = dao.login(loginUser);

//5.判断user
if (user==null){
//登录失败
request.getRequestDispatcher("/failServlet").forward(request, response);
}else{
//登录成功
//存储数据
request.setAttribute("user",user);
//转发
request.getRequestDispatcher("/successServlet").forward(request, response);
}
}
}

介绍

用于封装JavaBean的

  1. JavaBean:标准的Java类

    1. 要求

      1. 类必须被public修饰

      2. 必须提供空参的构造器

      3. 成员变量必须使用private修饰

      4. 提供公共的setter和getter方法

    2. 功能:封装数据

  2. 方法:

    1. setProperty()

    2. getProperty()

    3. populate(Object obj,Map map):将map集合的键值对信息,封装到对应的JavaBean对象中

Response

功能

设置响应消息

  1. 设置响应行

    1. 格式:HTTP/1.1 200 OK

    2. 设置状态码:setStatus(int sc)

  2. 设置响应头:setHeader(String name,String value)

  3. 设置响应体

    • 使用步骤:

      1. 获取输出流

        • 字符输出流:PrintWriter getWriter()

        • 字节输出流:ServletOutputStream getOutputStream()

      2. 使用输出流,将数据输出到客户端浏览器

案例

  1. 完成重定向

  2. 服务器输出字符数据到浏览器

  3. 服务器输出字节数据到浏览器

  4. 验证码

重定向

demo1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package cn.itcast.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* 重定向
*/



public class demo1 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

System.out.println("demo1被访问了");


// //访问/response1 会自动跳转到/response2资源
// //1.设置访问码为302
// response.setStatus(302);
// //2.设置响应头location
// response.setHeader("location","/response/response2");

// //简单的重定向方法
//// response.sendRedirect("/response/response2");
response.sendRedirect("http://www.51nd0re1.cn");

}

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

demo2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package cn.itcast.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class demo2 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("demo2被访问了");
}

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

运行结果

1
2
demo1被访问了
demo2被访问了

特点

  • 转发的特点:

    1. 转发地址栏路径不变

    2. 转发只能访问当前服务器下的资源

    3. 转发是一次请求,可以使用request对象共享数据

  • 重定向的特点

    1. 地址栏发生变化

    2. 重定向可以访问其他站点(服务器)的资源

    3. 重定向是两次请求,不能使用request对象来共享数据

服务器输出字符数据到浏览器

  • 步骤:

    1. 获取字符输出流

    2. 输出数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package cn.itcast.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class demo3 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取字符输出流
PrintWriter pw = response.getWriter();
//2.输出数据
pw.write("hello response");
}

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

运行结果在浏览器上输出

1
hello response

中文乱码

乱码原因:编解码使用的字符集不一致

例如知道服务器用的是GBK编码,那就改为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package cn.itcast.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class demo3 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取流对象之前,设置流的编码
response.setCharacterEncoding("GBK");


//1.获取字符输出流
PrintWriter pw = response.getWriter();
//2.输出数据
// pw.write("hello response");
pw.write("你好 response");
}

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

就可以正常显示了

但是往往会有兼容性问题,如果服务器为UTF-8,而我们又不知道,还是会出现乱码问题

所以我们可以告诉浏览器,我们采用何种编码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package cn.itcast.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class demo3 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取流对象之前,设置流的编码
response.setCharacterEncoding("utf-8");

//告诉浏览器,服务器发送的消息体数据的编码,建议浏览器使用该编码解码
//response.setHeader("content-type","text/html;charset=utf-8");

//简单的形式来设置编码
response.setContentType("text/html;charset=utf-8");

//1.获取字符输出流
PrintWriter pw = response.getWriter();
//2.输出数据
// pw.write("hello response");
pw.write("你好 response");
}

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

设置流的编码也可以不写,setHeader就可以了