2.1、Http请求
在Java Web应用开发中,99.999%用到的都是Http请求
/**
* Servlet处理HTTP GET/POST请求
*/
public class HttpServletDemo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
...
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp {
...
}
}
HTTP存在GET/POST请求,Servlet是如何分辨的呢?
GET请求,请求的数据会附在URL之后(就是把数据放置在HTTP协议头中),以?分割URL和传输数据,多个参数用&连接
POST请求:把提交的数据放置在是HTTP包的Body中。
## GET和POST请求的区别
# GET请求
GET /books/?name=computer&num=1 HTTP/1.1
Host: www.wrox.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Connection: Keep-Alive
# 注意最后一行是空行
# POST请求
POST /books/add HTTP/1.1
Host: www.wrox.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 40
Connection: Keep-Alive
# 以下是POST请求Body
name=computer&num=1
HttpServlet类中的Service方法根据Http请求的类型GET/POST分别调用doGet或doPost
/**
* HttpServlet类Service方法
*/
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getMethod();
long lastModified;
if (method.equals("GET")) {
lastModified = this.getLastModified(req);
if (lastModified == -1L) {
this.doGet(req, resp);
} else {
long ifModifiedSince;
try {
ifModifiedSince = req.getDateHeader("If-Modified-Since");
} catch (IllegalArgumentException var9) {
ifModifiedSince = -1L;
}
if (ifModifiedSince < lastModified / 1000L * 1000L) {
this.maybeSetLastModified(resp, lastModified);
this.doGet(req, resp);
} else {
resp.setStatus(304);
}
}
} else if (method.equals("HEAD")) {
lastModified = this.getLastModified(req);
this.maybeSetLastModified(resp, lastModified);
this.doHead(req, resp);
} else if (method.equals("POST")) {
this.doPost(req, resp);
} else {
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[]{method};
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(501, errMsg);
}
}
对于Http Request请求,我们还需要理解幂等的概念:对同一个系统,使用同样的条件,一次请求和重复的多次请求对系统资源的影响是一致的。
根据以上定义,我们认为GET请求一般情况下是幂等的(GET请求不会引起服务资源的变更),而POST请求是非幂等的(POST请求会提交数据并造成数据更改,造成不可逆,比如多次POST提交订单数据)。
Servlet可以通过API获取到Http请求的相关数据
API 备注
request.getParameter("参数名") 根据参数名获取参数值(注意,只能获取一个值的参数)
request.getParameterValue("参数名“) 根据参数名获取参数值(可以获取多个值的参数)
request.getMethod 获取Http请求方式
request.getHeader("User-Agent") 获取用台浏览器信息
request.getCookies 获取与请求相关的Cookies
request.getSession 获取与用户相关的会话
... ...
2.2、Http响应
响应是为了向用户发送数据,Servlet需要处理的是封装成Http响应消息的HttpServletResponse对象。
Http响应一般返回给浏览器HTML页面,再由浏览器解析HTML呈现给用户。
在这里插入图片描述
但Http响应发送HTML页面并不是全部,比如用户需要通过网站下载某个文件,那Http响应需要返回字节流。
protected void doGet(HttpServletRequest req, HttpServletResponse resp){
// 这是一个字节流
resp.setContentType("application/octet-stream");
resp.setHeader("Content-disposition", "attachment;filename=" + filename);
InputStream fis = this.getClass().getResourceAsStream("download.xlsx");
OutputStream os = resp.getOutputStream();
byte[] bis = new byte[1024];
while (-1 != fis.read(bis)) {
os.write(bis);
}
}
Servlet设置Http响应头控制浏览器的行为
//设置refresh响应头控制浏览器每隔1秒钟刷新一次
response.setHeader("refresh", "1");
//可分别通过三种方式禁止缓存当前文档内容
response.setDateHeader("expries", -1);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache")
// 重定向:收到客户端请求后,通知客户端去访问另外一个web资源
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
// 通过sendRedirect方法实现请求重定向
resp.sendRedirect(req.getContextPath() + "/welcome.jsp");
}
// 请求分派
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
req.getRequestDispatcher("/result.jsp").forward(req,resp);
}
Servlet与HTTP 状态码
代码 消息 描述
200 OK 请求成功。
401 Unauthorized 所请求的页面需要授权
404 Not Found 服务器无法找到所请求的页面。
500 Internal Server Error 未完成的请求。服务器遇到了一个意外的情况
... ... ...
// 返回HTTP 500状态码
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
resp.sendError(500);
}
在这里插入图片描述
三、ServletConfig
在每个Servlet运行时,有可能需要一些初始化参数,比如,文件使用的编码,共享的资源信息等。
这些初始化参数可以在 web.xml 文件中使用一个或多个 <init-param> 元素进行描述配置。当 容器 初始化一个 Servlet 时,会将该 Servlet 的配置信息封装,并通过 init(ServletConfig)方法将 ServletConfig 对象的引用传递给 Servlet。
在这里插入图片描述
3.1 测试ServletConfig参数
在web.xml中进行如下配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>http-demo</servlet-name>
<servlet-class>demo.servlet.HttpServletDemo</servlet-class>
<!-- 设置该servlet的管理员邮箱地址 -->
<init-param>
<param-name>adminEmail</param-name>
<param-value>admin@163.com</param-value>
</init-param>
</servlet>
</web-app>
在servlet代码中进行如下调用:
public class HttpServletDemo extends HttpServlet {
// 重写Get请求方法,返回一个表单页面
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
resp.setContentType("text/html");
resp.setCharacterEncoding("GBK");
PrintWriter out =resp.getWriter();
out.println("<html><body>");
out.println("管理员邮箱:");
out.println(getServletConfig().getInitParameter("adminEmail"));
out.println("<br>");
out.println("</body></html>");
}
}
在这里插入图片描述
四、ServletContext
-web应用同样也需要一些初始化的参数,但 相对于每一个Servlet有一个ServletConfig来说,一个Web应用(确切的说是每个JVM)仅有一个ServletContext来存放这些参数,这个ServletContext对Web应用中的每个Servlet都可用。
在这里插入图片描述
4.1 测试ServletContext参数
在web.xml中进行如下配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 设置web应用的统一标题栏 -->
<context-param>
<param-name>title</param-name>
<param-value>My-App网站</param-value>
</context-param>
<servlet>
<servlet-name>http-demo</servlet-name>
<servlet-class>demo.servlet.HttpServletDemo</servlet-class>
<init-param>
<param-name>adminEmail</param-name>
<param-value>admin@163.com</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>http-demo</servlet-name>
<url-pattern>/http-demo</url-pattern>
</servlet-mapping>
</web-app>
在servlet代码中进行如下调用:
public class HttpServletDemo extends HttpServlet {
// 重写Get请求方法,返回一个表单页面
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
resp.setContentType("text/html");
resp.setCharacterEncoding("GBK");
PrintWriter out =resp.getWriter();
out.println("<html><body>");
out.println("<title>"+getServletContext().getInitParameter("title")+"</title>");
out.println("管理员邮箱:");
out.println(getServletConfig().getInitParameter("adminEmail"));
out.println("<br>");
out.println("</body></html>");
}
}
在这里插入图片描述
注意点:
// 在web应用中,以下两句代码等价
getServletContext().getInitParameter("title");
getServletConfig().getServletContext().getInitParameter("title");
4.2、ServletContext属性
通过编程的方式,可以给ServletContext绑定属性,使得web应用中的Servlet对象可以使用该全局属性。
// 重写Post请求方法,提交表单上的数据,并返回结果页面
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
Integer age = Integer.parseInt(req.getParameter("age"));
if (name != null && age != null) {
User user = new User(name, age);
req.setAttribute("name", name);
req.setAttribute("age", age);
// 设置提交成功次数属性,并同步加锁,防止多线程并发异常
synchronized (getServletContext()) {
if (user.checkName()) {
Long postCount = getServletContext().getAttribute("postCount") == null ? 1L
: Long.parseLong(getServletContext().getAttribute("postCount").toString()) + 1L;
getServletContext().setAttribute("postCount", postCount);
req.setAttribute("result", "登记成功" + "! 总共已有" + postCount + "人数登记!!");
} else {
req.setAttribute("result", "登记失败:名称中包含非法字符");
}
}
RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
view.forward(req, resp);
}
}
在这里插入图片描述
在这里插入图片描述
属性与参数的区别
属性 参数
设置方法 setAttribute(String name,Object value) 只能在web.xml中设置
返回类型 Object String
获取方法 getAttribute(String name). getInitParameter(String s)
五、属性的作用域
除了ServletContext可以设置属性外,HttpSession会话、HttpServletRequest请求都可以设置和使用属性。但这三者的作用域是不同的,可参见下表:
属性作用域 备注
ServletContext web应用存活期间都可以设置并使用属性;应用关闭上下文撤消后相应属性也会消失 各个Servlet都可以使用,但线程不安全,一般适在于常量属性等,比如数据库连接
HttpSession HttpSession应用存活期间都可以设置并使用属性;会话超时或被人为撤消后相应属性也会消失 与会话相关的都可以使用,比如电商网站的购物车属性
HttpServletRequest 每次请求生成时可设置或使用属性,直到这个请求在service方法中消失 请求中属性是线程安全的,类似于局部变量
六、HttpSession
Session就是为了让服务器有能力分辨出不同的用户。
客户端在第一次请求时没有携带任何sessionId,服务端Servlet容器就会给客户端创建一个HttpSession对象 存储在服务器端,然后给这个对象创建一个sessionID 作为唯一标识。同时
这个sessionID还会放在一个cookie里,通过response返回客户端。
客户端第二次发出请求,cookie中会携带sessionId,servlet容器拿着这个sessionID在服务器端查找对应的HttpSession对象,找到后就直接拿出来使用。
Servlet会为不同的客户端创建不同的sessionId及session对象,代表不同的状态。
在这里插入图片描述
6.1 HttpSession的关键方法
关键方法
方法 描述
getSession() 获取Session 对象
setAttribute() 在Session 对象中设置属性
getAttribute() 在Session 对象中获取属性
removeAttribute() 在Session 对象中删除属性
invalidate() 使Session 对象失效
setMaxInactiveInterval() 设置Session 对象最大间隔时间(在这段时间内,客户端未对这个会话有新的请求操作,该会话就会撤消)
6.2 简易的购物车使用HttpSession
网站后台通过会话保存用户的购物车状态,用户在退出网站后在会话的有效时间段内重新进入网站,购物车状态不消失。
web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>title</param-name>
<param-value>购物网站</param-value>
</context-param>
<!-- 网站session失效时间为30分钟 -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- 登录servlet -->
<servlet>
<servlet-name>http-demo</servlet-name>
<servlet-class>demo.servlet.HttpServletDemo</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>http-demo</servlet-name>
<url-pattern>/http-demo</url-pattern>
</servlet-mapping>
<!-- 购物车servlet -->
<servlet>
<servlet-name>cart</servlet-name>
<servlet-class>demo.servlet.CartServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cart</servlet-name>
<url-pattern>/cart</url-pattern>
</servlet-mapping>
</web-app>
购物网站登录页面Servlet:
/**
* 购物网站登录页面
*
* @author zhuhuix
* @date 2020-08-28
*/
public class HttpServletDemo extends HttpServlet {
//static int i=0 ;
// 重写Get请求方法,返回登录表单页面
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
req.setAttribute("title", getServletContext().getInitParameter("title"));
req.getRequestDispatcher("/form.jsp").forward(req, resp);
}
// 重写Post请求方法,进行登录,登录成功后跳车购物车页面
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
Integer password = Integer.parseInt(req.getParameter("password"));
if (name != null && password != null) {
req.getSession().setAttribute("name",name);
RequestDispatcher view = req.getRequestDispatcher("/cart.jsp");
view.forward(req, resp);
}
}
}
购物网站登录页面视图:
<!--表单页面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
<title>${title}用户登录</title>
</head>
<body>
<div class="container">
<form role="form" method="post" action="http-demo" class="form-horizontal">
<div class="form-group">
<h4 class="col-sm-3 col-sm-offset-3">用户登录</h4>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">用户名</label>
<div class="col-sm-3">
<input name="name" type="text" class="form-control" placeholder="请输入用户名">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">密码</label>
<div class="col-sm-3">
<input name="password" type="password" class="form-control" placeholder="请输入密码">
</div>
</div>
<div class="form-group">
<div class="col-sm-3 col-sm-offset-3">
<button class="btn btn-primary">点击登录</button>
</div>
</div>
</form>
</div>
</body>
</html>
在这里插入图片描述
购物车页面视图:
<!--表单页面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
<title>${title}购物车</title>
</head>
<body>
<div class="container">
<form role="form" method="post" action="cart" class="form-horizontal">
<div class="form-group">
<h4 class="col-sm-3 col-sm-offset-1">${name}的购物车</h4>
</div>
<table class="table table-bordered table-condensed" style="width: 30%">
<thead>
<tr>
<td>货物</td>
<td>数量</td>
</tr>
</thead>
<tbody>
<tr>
<td>手机</td>
<td><input type="number" name="phoneNumber" value=${phoneNumber}> </td>
</tr>
<tr>
<td>电脑</td>
<td><input type="number" name="pcNumber" value=${pcNumber}> </td>
</tr>
<tr>
<td>书本</td>
<td><input type="number" name="bookNumber" value=${bookNumber}> </td>
</tr>
</tbody>
</table>
<div class="form-group">
<div class="col-sm-1 col-sm-offset-1">
<button class="btn btn-primary">点击提交</button>
</div>
</div>
</form>
</div>
</body>
</html>
在这里插入图片描述
购物车的Servlet:
/**
* 购物车Servlet
*
* @author zhuhuix
* @date 2020-08-29
*/
public class CartServlet extends javax.servlet.http.HttpServlet {
// 重写Post请求方法,提交购物车的数据,并返回结果页面
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 查找页面上的购物数量,并放入session中
req.getSession().setAttribute("phoneNumber", req.getParameter("phoneNumber"));
req.getSession().setAttribute("pcNumber", req.getParameter("pcNumber"));
req.getSession().setAttribute("bookNumber", req.getParameter("bookNumber"));
RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
view.forward(req, resp);
}
}
购物结果视图页面:
<!--结果页面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
<title>${title}购物结果</title>
</head>
<body>
<div class="container">
<div class="row">
<h3 class="col-sm-3 col-sm-offset-1">${name}的购物结果</h3>
</div>
<table class="table table-bordered table-condensed" style="width: 30%">
<thead>
<tr>
<td>已购货物</td>
<td>已购数量</td>
</tr>
</thead>
<tbody>
<tr>
<td>手机</td>
<td>${phoneNumber} </td>
</tr>
<tr>
<td>电脑</td>
<td>${pcNumber}</td>
</tr>
<tr>
<td>书本</td>
<td>${bookNumber} </td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
深圳网站优化www.zg886.cn