day10
一、response和request
服务器处理请求的流程
- 服务器每次收到请求时,都会为这个请求开辟一个新的线程
- 服务器会把客户端的请求数据封装到request对象中,request就是请求数据的载体
- 服务器还会创建response对象,这个对象与客户端连接在一起,他可以用来向客户
端发送响应。
1.response
案例:发送404
@WebServlet(name = "AServlet",urlPatterns = {"/AServlet"})
public class AServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendError(404,"哈哈哈哈");
}
}
setHeader(String name,String vlaue):适用于单值的响应头 ,例如:response.setHeader("aaa","AAA");
案例:
- 发送302,设置Location头,完成重定向
@WebServlet(name = "BServlet",urlPatterns = {"/BServlet"})
public class BServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("BServlet");
//重定向:
response.setHeader("Location","/day10/CServlet");//设置Location
response.setStatus(302);//发送302状态码
}
}
@WebServlet(name = "CServlet",urlPatterns = {"/CServlet"})
public class CServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("CServlet");
}
}
- 定时刷新,设置Refresh头
@WebServlet(name = "DServlet",urlPatterns = {"/DServlet"})
public class DServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter writer = response.getWriter();//发送响应体
writer.print("欢迎你,5秒后跳转主页");
response.setHeader("Refresh","5;URL=/day10/EServlet");
}
}
@WebServlet(name = "EServlet",urlPatterns = {"/EServlet"})
public class EServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().print("还是乱码");
}
}
- 禁用浏览器缓存:Cache-Control、pragma、expires
@WebServlet(name = "FServlet",urlPatterns = {"/FServlet"})
public class FServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Cache-Control","no-cache");
response.setHeader("pragam","no-cache");
response.setDateHeader("expires",-1);
response.getWriter().print("hello");
}
}
- 标签可以代替响应头: content="text/html;charset="UTF-8">
响应体:通常是html、也可以是图片
response的两个流:
ServletOutputStream:用来向客户端发送字节数据
PrintWriter:用来向客户端发送字符数据,需要设置编码
两个流不能同时使用
案例:
使用PrintWriter发送字符数据
String s = "hello output";
byte[] bytes = s.getBytes();
response.getOutputStream().write(bytes);
使用ServletOutputStream发送字节数据(图片)
String path = "C:\\a.jpg";
FileInputStream in = new FileInputStream(path);
byte[] bytes = toByteArray(in); //读取输入流内容的字节到字节数组中
response.getOutputStream().write(bytes);
重定向:设置302.设置Location;其中变化的只有Location,使用快捷方法。
response.sendRedirect("/day10/CServlet");
2.request
封装了客户端所有的请求数据
获取常用信息
- 获取客户端IP,案例:封IP:requset.getRemoteAddr();
String addr = request.getRemoteAddr();
System.out.println("ip:"+addr);
- 请求方式,request.getMethod(),可能是POST也可能是GET
System.out.println("请求方式:"+request.getMethod());
获取HTTP请求头:
- String getHeader(String name):适用于单值头
- int getInHeader(String name):适用于单值int类型的请求头
- long getDateHeader(String name):适用于单值毫秒类型的请求头
- Enumeration
getHeaders(String name):适用于多值请求头
案例:
- 通过User-Agent识别用户浏览器类型
String useragent = request.getHeader("User-Agent");
System.out.println(useragent);
//Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36
- 防盗链:如果请求不是通过本站的超链接发出的,发送的错误状态码404。Referer这个请求头,表示请求的来源
String referer = request.getHeader("Referer");
System.out.println(referer);
获取请求URL
response.getWriter().print(request.getScheme()+"
");//获取请求协议
response.getWriter().print(request.getServerName()+"
");//获取服务器名称
response.getWriter().print(request.getServerPort()+"
");//获取服务器端口号
response.getWriter().print(request.getContextPath()+"
");//获取项目名称
response.getWriter().print(request.getServletPath()+"
");//获取Servlet路径
response.getWriter().print(request.getQueryString()+"
");//获取参数部分
response.getWriter().print(request.getRequestURI()+"
");//获取请求URL
response.getWriter().print(request.getRequestURL()+"
");//获取请求URL
获取请求参数:请求参数是由客户端发送给服务器的,有可能是在请求体中(POST),也可能是在URL之后(GET)
演示request获取请求参数:
测试请求参数
点击这里
@WebServlet(name = "AServlet",urlPatterns = {"/AServlet"})
public class AServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String[] hobby = request.getParameterValues("hobby");
System.out.println(username+", "+password+", "+ Arrays.toString(hobby));
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("GET"+request.getParameter("xxx"));
System.out.println("GET"+request.getParameter("yyy"));
}
}
获取所有请求参数的名称
Enumeration names = request.getParameterNames();
while (names.hasMoreElements())
{
System.out.println(names.nextElement());
}
获取所有请求参数,封装到MAP中
Map map = request.getParameterMap();
for (String name:map.keySet()) {
String[] values = map.get(name);
System.out.println(name+"="+ Arrays.toString(values));
}
请求转发和请求包含
请求转发:rd.forward(request,response);
//OneServlet
@WebServlet(name = "OneServlet",urlPatterns = {"/OneServlet"})
public class OneServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("OneServlet...");
response.setHeader("aaa","AAA");//设置响应头
response.getWriter().print("hello OneServlet");//设置响应体
//等同于调用TwoServlet的service()方法
request.getRequestDispatcher("TwoServlet").forward(request,response);//请求转发
}
}
//TwoServlet
@WebServlet(name = "TwoServlet",urlPatterns = {"/TwoServlet"})
public class TwoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("TwoServlet...");
response.getWriter().print("hello TwoServlet");//设置响应体
}
}
//a.html
测试请求参数
点击这里
请求包含: rd.include(requset,response) ;
同一请求范围内使用request.setAttribute、request.getAttribute()来传值;前一个Servlet调用SetAttribute()保存值,后一个Servlet调用getAttribute()获取值
请求转发和重定向的区别:
二、编码
常见的字符编码:iso-8859-1(不支持中文)、gb2312、gbk、gb18030(系统默认编码,中国的国标码)、utf-8(万国码,支持全世界的编码,所以我们使用这个)
- 响应编码
- 请求编码
//演示2请求编码
This is my page.
GET
@WebServlet(name = "BServlet",urlPatterns = {"/BServlet"})
public class BServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1.先获取来使用iso的错误字符串
//2.(iso)回退,(使用utf-8)重编
String name = request.getParameter("username");
byte[] b = name.getBytes("iso-8859-1");
name = new String(b, "UTF-8");
System.out.println(name);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");//获取参数前调用request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");//使用request.getParameter("username");获取参数
System.out.println(username);
}
}
URL编码
路径
=====================================================================================================================================================================================================================
day11
一、JSP入门
1.JSP的作用
Servlet:
- 缺点:不适合设置html响应体,需要大量的response.getWriter().print("html>")
- 优点:动态资源,可以编程
html:
- 缺点:html是静态页面,不能包含动态信息
- 优点:不用为输出html标签而发愁
jsp(java server pages):
- 优点:在原有基础上添加java脚本,构成jsp页面
2.jsp和servlet的分工
JSP:
- 作为请求发起页面,例如显示表单、超链接
- 作为请求结束页面,例如显示数据
Servlet:
- 作为请求结束页面,例如显示数据
JSP访问流程图
3.JSP的组成
案例:演示 JSP中java脚本的使用
姓名
年龄
<%for(int i =0;i<10;i++){ %>
张三
29
<%}%>
JSP和Servlet分工演示
//form.jsp
//AServlet
@WebServlet(name = "AServlet",urlPatterns = {"/AServlet"})
public class AServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String s1 = request.getParameter("num1");//获取参数
String s2 = request.getParameter("num2");
int num1 = Integer.parseInt(s1);//转化成int类型
int num2 = Integer.parseInt(s2);
int sum = num1+num2;//运算
request.setAttribute("result",sum);//把结果保存到request域中
request.getRequestDispatcher("/jia/result.jsp").forward(request,response);//转化成result.jsp
}
//result..jsp
body>
<%
Integer result = (Integer)request.getAttribute("result");
%>
<%=result %>
4.JSP原理
5.JSP注释
<%-- --%>:当服务器把jsp文件编译成java文件时已经忽略了注释部分。
二、Cookie
1.Http协议与Cookie
2.Cookie的用途
- 服务器使用Cookie来跟踪客户端状态
- 保存购物车(购物车中的商品不能用request保存,因为他是一个用户想客户端发送的多个请求信息)
- 显示上次登陆名(也是一个用户多个请求)
3.JavaWeb中使用Cookie
- 使用response,addCookie()方法向浏览器保存Cookie
- 使用request.getCookies()方法获取浏览器归还的Cookie
案例:一个jsp保存cookie,另一个jsp获取浏览器归还的cookie
//a.jsp
保存Cookie
<%
Cookie cookie1 = new Cookie("aaa","AAA");
response.addCookie(cookie1);
Cookie cookie2 = new Cookie("bbb","BBB");
response.addCookie(cookie2);
%>
//b.jsp
获取Cookie
<%
Cookie[] cookies = request.getCookies();
if(cookies != null){
for (Cookie c:cookies) {
System.out.println(c.getName() + "="+c.getValue() + "
");
}
}
%>
4.Cookie详解
Cookie不只有name和value两个属性
Cookie的maxAge属性:Cookie的最大生命,即Cookie可保存的最大时长。以秒为单位。
maxAge>0:浏览器会把Cookie保存到客户机硬盘上,有效时长为maxAge的值决定
maxAge<0:Cookie只在浏览器内存中国存在,当用户关闭浏览器时,Cookie就死亡了
maxAge=0:浏览器会马上删除这个Cookie
Cookie的PATH
5.Cookie的domain(域)
三、HttpSession
1.HttpSession概述
- HttpSession是由JavaWeb提供的,用来会话跟踪的类。session是服务器端的对象,保存在服务器端。
- HttpSession是Servlet三大域对象之一(request、session、application(ServletContext)),所以他也有serAttribute()、getAttribute()、removeAttribute()方法。
- HttpSession底层依赖Cookie,或是URL重写。
2.HttpSession的作用
案例一:
//a.jsp
向session域保存数据
<%
session.setAttribute("aaa","AAA");
%>
//b.jsp
获取session中的数据
<%
String s = (String) session.getAttribute("aaa");
%>
<%=s %>
案例二:
//login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
登录
<%
/*
* 读取名为uanme的cookie
* 如果为空显示:" "
* 如果不为空显示:Cookie的值
* */
String uname = "";
Cookie[] cs = request.getCookies();//获取请求中所有的cookie
if(cs!=null){//如果存在cookie
for (Cookie c:cs) {//遍历所有的cookie
if("uname".equals(c.getName())){//查找名为uname的cookie
uname = c.getValue();//获取这个cookie的值,给uname这个变量
}
}
}
%>
<%
String message = "";
String msg = (String) request.getAttribute("msg");
if(msg!=null){
message = msg;
}
%>
<%=message %>
//succ1.jsp
succ1
<%
String username = (String) session.getAttribute("username");
if(username == null ){
//向request域中保存错误信息,转发到login.jsp
request.setAttribute("msg","您还没有登陆");
request.getRequestDispatcher("/session2/login.jsp").forward(request,response);
return;
}
%>
//succ2.jsp
succ2
<%
String username = (String) session.getAttribute("username");
if(username == null ){
//向request域中保存错误信息,转发到login.jsp
request.setAttribute("msg","您还没有登陆");
request.getRequestDispatcher("/session2/login.jsp").forward(request,response);
return;
}
%>
//LoginServlet
@WebServlet(name = "LoginServlet",urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1.获取表单数据
request.setCharacterEncoding("UTF-8");//处理中文问题
String username = request.getParameter("username");//获取表单信息
String password = request.getParameter("password");
//2.校验用户名和密码是否正确
if(!"itcast".equalsIgnoreCase(username)){//登录成功
//把用户名保存到cookie中,发送给客户端浏览器
//当再次打开login.jsp时2,login.jsp中会读取request中的cookie,把他显示到用户名文本框中
Cookie cookie = new Cookie("uname", username);//创建cookie
cookie.setMaxAge(60*60*24);//设置cookie命长为一天
response.addCookie(cookie);//保存cookie
//3.如果成功
//保存用户信息到session中
//重定向到succ1.jsp中
HttpSession session = request.getSession();//获取session
session.setAttribute("username",username);//向session域中保存用户名
response.sendRedirect("/day11_1/session2/succ1.jsp");
}
else{//登录失败
//4.如果失败
//保存错误信息到request域中
//转发到login.jsp中
request.setAttribute("msg","用户名或密码错误");
RequestDispatcher qr = request.getRequestDispatcher("/session2/login.jsp");//得到转发器
qr.forward(request,response);//转发
}
}
}
3..HttpSession的原理
4.HttpSession其他方法
5.web.xml中配置sesssion最大不活动时间
30