目录
1.Request
1.1Request执行流程
1.2request对象和response对象的原理
1.3 request对象继承体系结构
1.4request功能:
1.3.1获取请求消息数据
1.获取请求行数据
2.获取请求头
3.获取请求体数据
4.其他功能
4.1获取请求参数通用方式:不论get还是post请求方式都可以使用下列方法来获取请求参数
4.2请求转发:一种在服务器内部的资源跳转方式
4.3共享数据
4.4获取ServletContext:
2.综合案例-登录
1.Request
1.1Request执行流程
1.2request对象和response对象的原理
1.request和response对象是由服务器创建的。我们来使用它们
2.request对象是来获取请求消息,response对象是来设置响应消息request对象继承体系结构:
1.3 request对象继承体系结构
ServletRequest ----接口
「继承
HttpServletRequest ----接口
丨实现
org.apache.catalina.connector.RequestFacade(tomcat)
1.4request功能:
1.3.1获取请求消息数据
1.获取请求行数据
GET /day14/demo1?name=zhangsan HTTP/1.1
*方法:
1,获取请求方式:GET
(*)string getMethod()
2.获取虚拟目录:/day14
string getcontextPath()
3.获取Servlet路径:/demo1
string getservletpath()
4,获取get方式请求参数:name=zhangsan
string getQuerystring()
5,获取请求URI:/day14/demo1
(*)string getRequestURI():
/day14/demo1
stringBuffer getRequestURL()
http://localhost/day14/demo1
6,获取协议及版本:HTTP/1,1
string getprotocol()
7,获取客户机的IP地址:
string getRemoteAddr()
2.获取请求头
*方法:
(*)String getHeader(String name):通过请求头的名称获取请求头的值
Enumeration<String>getHeaderNames():获取所有的请求头名称
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
//演示获取请求头数据
//1.获取所有请求头的名称
Enumeration<String> headerNames = request.getHeaderNames();
//2.遍历
while (headerNames.hasMoreElements()){
String name = headerNames.nextElement();
//根据名称获取请求头的值
String value = request.getHeader(name);
System.out.println(name+"---"+value);
}
}
演示获取请求头数据 user-agent
//演示获取请求头数据:user-agent
String agent = request.getHeader("user-agent");
if (agent.contains("Chrom")){
System.out.println("谷歌来了...");
}else if(agent.contains("Edge")){
System.out.println("Edge");
}else {
System.out.println("不知名浏览器");
}
}
演示获取请求头数据 referer
防盗链
package com.hzw.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;
import java.util.Enumeration;
@WebServlet("/demo7")
public class RequestDemo4 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
//演示获取请求头数据 refer
String referer = request.getHeader("referer");
System.out.println(referer); //http://localhost:8080/day14/login.html
//防盗链
if (referer!=null){
if (referer.contains("/day14")){
//正常访问
System.out.println("播放电视剧");
}else {
System.out.println("想看电影吗?来腾讯");
}
}
}
}
3.获取请求体数据
请求体:只有P0ST请求方式,才有请求体,在请求体中封装了P0ST请求的请求参数
*步骤:
1,获取流对象
,BufferedReader getReader():获取字符输入流,只能操作字符数据
ServletInputstream getInputstream():获取字节输入流,可以操作所有类型数据
在文件上传知识点后讲解
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求体 --请求参数
//1.获取字节流
BufferedReader br = request.getReader();
//2.读取数据
String line=null;
while ((line=br.readLine())!=null){
System.out.println(line);
}
}
4.其他功能
4.1获取请求参数通用方式:不论get还是post请求方式都可以使用下列方法来获取请求参数
1.String getparameter(String name):根据参数名称获取参数值usernamea=zs&password=l23
2.string[] getParametervalues(String name):根据参数名称获取参数值的数组hobby=study&hobby=game
3.Enumeration<string>getParameterNames():获取所有请求的参数名称
4,Map<String,String【】>getParameterMap():获取P所有奇数的map集合
常中文乱码问题:
*get方式:tomcat8已经将get方式乱码问题解决了
post方式:会码
*解决:在获取参数前,设置requesti的编码request,setcharacterEncoding("utf-8");
代码实现
package com.hzw.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.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;
@WebServlet("/requestDemo6")
public class RequestDemo6 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//post获取请求参数
//根据参数名称获取参数值
String username = request.getParameter("username");
// System.out.println("post");
// System.out.println(username);
//根据参数名称获取参数值
String[] hobbies = request.getParameterValues("hobby");
// for (String hobby : hobbies) {
// System.out.println(hobby);
// }
//根据所有请求的参数名称 keys
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()){
String name = parameterNames.nextElement();
System.out.println(name);
String value = request.getParameter(name);
System.out.println(value);
System.out.println("-----------");
}
//获取所有参数的map集合
Map<String, String[]> parameterMap = request.getParameterMap();
//遍历
Set<String> keySet = parameterMap.keySet();
for (String name : keySet) {
//通过键获取值
String[] values = parameterMap.get(name);
System.out.println(name);
for (String value : values) {
System.out.println(value);
}
System.out.println("--------");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get 获取请求参数
//根据参数名称获取参数值
// String username = request.getParameter("username");
// System.out.println("get");
// System.out.println(username);
this.doPost(request,response);
}
}
register2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/requestDemo6" method="post">
<input type="text" name="username" placeholder="请输入名字"><br/>
<input type="text" name="password" placeholder="请输入密码"><br/>
<input type="checkbox" name="hobby" value="game">游戏
<input type="checkbox" name="hobby" value="study">学习<br/>
<input type="submit" value="注册">
</form>
</body>
</html>
4.2请求转发:一种在服务器内部的资源跳转方式
1.步骡:
1.1通过request对象获取请求转发器对象:RequestDispatcher getRequestDispatcher(string path)
1.2使用RequestDispatcher对象来进行转发:forward(ServletRequest request,ServletResponse response)
2.特点:
2.1浏览器地址栏路径不发生变化
2.2,只能转发到当前服务器内部资源中。
2.3,转发是一次请求
4.3共享数据
域对象:一个有作用范围的对象,可以在范围共享数据
request域:代表一次请求的范围,一般用于请求转发的多个资源共享数据
方法:
1.void setAttribute(String name,object obj):存储数据
2.object getAttitude(string name):通过键获取值
3.void removeAttribute(String name):通过键移除键值对
4.4获取ServletContext:
*ServletContext getservletcontext()
2.综合案例-登录
代码实现
导入相应jar包
记得lib 放入模块
1.建表user
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE NOT NULL,
PASSWORD VARCHAR(32) NOT NULL
);
INSERT INTO USER(username,PASSWORD) VALUES('hzw','123')
2.User实体类
package com.hzw.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 + '\'' +
'}';
}
}
3.UserDao 实现登录
package com.hzw.dao;
import com.hzw.domain.User;
import com.hzw.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
/**
* 操作数据库中User表中类
*/
public class UserDao {
//声明JDBCTemplate对象共用
private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
/**
* 登录方法
* @param loginUser 用户名和密码
* @return 用户全部数据 没有查询到返回null
*/
public User login(User loginUser) {
try {
//1.编写sql
String sql = "select * from user where username=? and password=?";
//2.调用query方法
User users = template.queryForObject(sql,
new BeanPropertyRowMapper<User>(User.class),
loginUser.getUsername(), loginUser.getPassword());
return users;
} catch (DataAccessException e) {
e.printStackTrace();
return null;
}
}
}
4.jdbc连接代码
druid.properties
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/javaweb?userSSL=true&serverTimezone=Asia/Shanghai
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200
jdbcUtils
package com.hzw.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工具类
*/
public class JDBCUtils {
private static DataSource ds;
static {
//1加载配置文件
Properties properties = new Properties();
try {
//使用ClassLoader加载配置文件,获取字节输入流
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(is);
//2.初始化连接池对象
ds=DruidDataSourceFactory.createDataSource(properties);
}catch (IOException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接池对象
*/
public static DataSource getDataSource(){
return ds;
}
/**
* 获取连接池对象
* @return
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
Servlet
loginServlet 如果登录成功跳转到SuccessServlet 失败跳转FailServlet
package com.hzw.web.servlet;
import com.hzw.dao.UserDao;
import com.hzw.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("/login1")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
@Override
protected void doPost(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 userDao = new UserDao();
User user = userDao.login(loginUser);
//5.判断user
if (user ==null){
//登录失败
request.getRequestDispatcher("/failServlet").forward(request,response);
}else {
//登录成功
//存储数据
request.setAttribute("user",user);
//转发
request.getRequestDispatcher("/successServlet").forward(request,response);
}
}
}
package com.hzw.web.servlet;
import com.hzw.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 {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取request域中共享对象
User user = (User)request.getAttribute("user");
if (user!=null){
//设置编码
response.setContentType("text/html;charset=utf-8");
//输出响应
response.getWriter().write("登录成功,"+user.getUsername()+"欢迎您大佬");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
package com.hzw.web.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 {
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 {
this.doPost(request,response);
}
}
设置虚拟路径
登录html
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/hzw/login1" method="post">
用户名:<input type="text" name="username" placeholder="请输入用户名"> <br>
密码:<input type="password" name="password" placeholder="请输入密码"> <br>
<input type="submit" value="登录">
</form>
</body>
</html>
运行截图:登陆成功 跳转SuccessServlet 响应数据
使用BeanUtils封装数据
导入对应jar包
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.设置编码
request.setCharacterEncoding("utf-8");
//2.获取所有请求参数
Map<String, String[]> map = request.getParameterMap();
//3.创建user对象
User loginUser = new User();
//3,1使用BeanUtils封装
try {
BeanUtils.populate(loginUser,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//4.调用UserDao的login
UserDao userDao = new UserDao();
User user = userDao.login(loginUser);
//5.判断user
if (user ==null){
//登录失败
request.getRequestDispatcher("/failServlet").forward(request,response);
}else {
//登录成功
//存储数据
request.setAttribute("user",user);
//转发
request.getRequestDispatcher("/successServlet").forward(request,response);
}
}
BeanUtils.工具类,简化数据封装
*用于封装JavaBean的
1,]avaBean:标准的Java类
1,要求:
1,类必须被public修饰
2,必须提供空参的构造器
3,成员变量必须使用private修饰
4.提供公共setter和getter方法
2,功能:封装数据
2,概念:
成员变量:
属性:setter和getter方法截取后的产物
例如:getusername()-->Username-->username
3,方法:
1.setProperty()
2.getProperty()
3.populate(Object obj ,Map map) 将map集合的键值对信息,封装到对应的JavaBean对象中。