JavaEE(Java Enterprise Edition):Java企业版,早期叫J2EE(J2EE的版本从1.0到1.4结束);现在Java版本从JavaEE 5开始
JavaEE规范是很多Java开发技术的总称
HTTP(Hyper Text Transfer Protocol):超文本传输协议
HTTP协议是基于TCP/IP协议的
超文本:比普通文本更加强大
传输协议:客户端和服务端的通信规则(握手规则)
名称 | 说明 |
---|---|
Accept | 客户端浏览器所支持的MIME类型 |
Accept-Encoding | 客户端浏览器所支持的压缩编码格式,最常用的就是gzip压缩 |
Accept-Language | 客户端浏览器所支持的语言,一般都是zh_CN或en_US等 |
Referer | 告知服务器当前请求来源 |
Content-Type | 请求正文所支持MIME类型 |
Content-Length | 请求正文的长度 |
User-Agent | 浏览器相关信息 |
Connection | 连接状态,Keep-Alive保持连接 |
If-Modified-Since | 客户端浏览器缓存文件的最后修改时间 |
Cookie | 会话管理相关 |
状态码 | 说明 |
---|---|
200 | 一切ok |
302/307 | 请求重定向,两次请求,地址栏发生改变 |
304 | 请求资源未发生改变,使用缓存 |
404 | 请求资源未找到 |
500 | 服务器错误 |
名称 | 说明 |
---|---|
Location | 请求重定向地址,常与302,307配合使用 |
Server | 服务器相关信息 |
Content-Type | 响应正文的MIME类型 |
Content-Length | 响应正文的长度 |
Content-Disposition | 告知客户端浏览器,以下载的方式打开响应正文 |
Refresh | 定时刷新 |
Last-Modified | 服务器资源的最后修改时间 |
Set-Cookie | 会话管理相关 |
Expires:-1 | 服务器资源到客户端浏览器后的缓存数据 |
Catch-Control:no-catch | 不要缓存 |
<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">
<welcome-file-list>
<welcome-file>/demo/index.jspwelcome-file>
welcome-file-list>
web-app>
<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">
<welcome-file-list>
<welcome-file>/demo/index.jspwelcome-file>
welcome-file-list>
<servlet>
<servlet-name>servletNameservlet-name>
<servlet-class>cn.cdw.demo.Demo1servlet-class>
servlet>
<servlet-mapping>
<servlet-name>servletNameservlet-name>
<url-pattern>/servletDemourl-pattern>
servlet-mapping>
web-app>
@WebServlet("访问映射路径")
package cn.cdw.demo;
import javax.servlet.*;
import java.io.IOException;
/**
* DW-CHEN
* Servlet
*
* 如果实现Servlet接口报cannot resolve symbol 'servlet'异常,那么需要手动都如servlet-api.jar包
*/
public class Demo1 implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("service方法执行了,测试通过....");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
package cn.cdw.demo;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
/**
* @author DW-CHEN
* GenericServlet
*/
@WebServlet("/servletDemo2")
public class Demo2 extends GenericServlet {
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("继承GenericServlet实现类的重写service方法执行了,测试通过....");
}
}
package cn.cdw.demo;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author DW-CHEN
* HttpServlet
*/
@WebServlet("/servletDemo3")
public class Demo3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("测试通过....");
}
}
对象的生命周期,就是对象从出生到死亡的过程,官方的说法就是对象的创建到销毁的过程
出生:请求第一次到达Servlet时,对象就创建出来,并且初始化成功,只出生一次,将对象放到内存中
活着:服务提供服务的整个过程中,该对象一直存在,每次都是执行service方法
死亡:当服务停止时或者服务器宕机时,对象死亡
Servlet对象只会创建一次,销毁一次,所有Servlet对象只有一个实例,如果一个对象实例在应用中时唯一存在,我们可以称为单例模式
package cn.cdw.demo;
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;
/**
* @author DW-CHEN
* Servlet生命周期
*/
@WebServlet("/servletDemo4")
public class Demo4 extends HttpServlet {
//初始化
@Override
public void init() throws ServletException {
System.out.println("初始化了....");
}
//服务
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("服务过程.....");
}
//销毁
@Override
public void destroy() {
System.out.println("销毁了....");
}
}
由于Servlet采用的是单例模式,也就是整个应用中只有一个实例对象(Servlet是线程不安全的)
Servlet线程不安全问题展示
package cn.cdw.demo;
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.io.PrintWriter;
/**
* @author DW-CHEN
* Servlet线程安全问题
*
* 使用两个浏览器同时访问同一个请求,出现线程安全问题
*
* 例如
* 浏览器一访问:http://localhost:8080/servletDemo5?testName=aaa
* 浏览器二访问:http://localhost:8080/servletDemo5?testName=bbb
*
* 出现:浏览器1和浏览器2页面显示都是bbb
*
*
*/
@WebServlet("/servletDemo5")
public class Demo5 extends HttpServlet {
private String value;//定义接收请求值的属性
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
value = req.getParameter("testName");//获取请求testName属性的值
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
PrintWriter writer = resp.getWriter();
writer.write("value:" + value);//把请求参数值响应到页面
writer.close();
}
}
解决Servlet线程安全问题:把成员变量定义到局部变量
package cn.cdw.demo;
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.io.PrintWriter;
/**
* @author DW-CHEN
* 解决Servlet线程安全问题:把成员变量定义到局部变量
*/
@WebServlet("/servletDemo6")
public class Demo6 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String value = null;
value = req.getParameter("testName");//获取请求testName属性的值
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
PrintWriter writer = resp.getWriter();
writer.write("value:" + value);//把请求参数值响应到页面
writer.close();
}
}
使用同步代码块解决Servlet线程安全问题
package cn.cdw.demo;
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.io.PrintWriter;
/**
* @author DW-CHEN
* 使用同步代码块解决Servlet线程安全问题
*/
@WebServlet("/servletDemo7")
public class Demo7 extends HttpServlet {
private String value;
private Object lock = new Object();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
synchronized (lock) {
value = req.getParameter("testName");//获取请求testName属性的值
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
PrintWriter writer = resp.getWriter();
writer.write("value:" + value);//把请求参数值响应到页面
writer.close();
}
}
注意:优先级问题,越是具体的优先级越高,也是模糊通用的优先级越低
通过多映射配置,在不同的访问路径在同一个方法里实现不同的功能逻辑
package cn.cdw.demo;
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.io.PrintWriter;
/**
* @author DW-CHEN
* 通过多映射配置,在不同的访问路径在同一个方法里实现不同的功能逻辑
*
* 例如:访问路径结尾为vip的购物优惠八折,为svip的购物优惠五折,普通不优惠
*/
@WebServlet("/servletDemo8/*")
public class Demo8 extends HttpServlet {
private Integer money = 10000;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
StringBuffer requestURL = req.getRequestURL();
String url = requestURL.substring(requestURL.lastIndexOf("/"));//获取最后一个路径字符串
PrintWriter writer = resp.getWriter();
if ("/vip".equals(url)) {
System.out.println("价钱:"+money + " 优惠后八折后为:"+(money) * 0.8);
writer.write(String.valueOf((money) * 0.8));
}else if ("/svip".equals(url)) {
System.out.println("价钱:"+money + " 优惠后八折后为:"+(money) * 0.5);
writer.write(String.valueOf((money) * 0.5));
}else {
System.out.println("价钱:" + money + " 没有优惠");
writer.write(String.valueOf((money)));
}
}
}
注解配置的方式
package cn.cdw.demo;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
/**
* @author DW-CHEN
*
* 配置Servlet在服务器启动的时候就创建初始化
*/
@WebServlet(value = "/servletDemo9",loadOnStartup = 1)
public class Demo9 extends HttpServlet {
@Override
public void init() throws ServletException {
System.out.println("Servlet初始化了...");
}
}
web.xml配置
<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">
<welcome-file-list>
<welcome-file>/demo/index.jspwelcome-file>
welcome-file-list>
<servlet>
<servlet-name>servletName10servlet-name>
<servlet-class>cn.cdw.demo.Demo10servlet-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>descparam-name>
<param-value>this is ServletConfigparam-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>servletName10servlet-name>
<url-pattern>/servletDemo10url-pattern>
servlet-mapping>
web-app>
方法名 | 说明 |
---|---|
String getInitParameter(String var1) | 根据参数名获取参数值 |
Enumeration |
获取所有参数名称的枚举 |
String getServletName() | 获取Servlet的名称 |
ServletContext getServletContext() | 获取ServletContext对象 |
package cn.cdw.demo;
import javax.servlet.ServletConfig;
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.io.PrintWriter;
import java.util.Enumeration;
/**
* @author DW-CHEN
* ServletConfig常用的方法
*/
public class Demo10 extends HttpServlet {
private ServletConfig servletConfig;
@Override
public void init(ServletConfig config) throws ServletException {
this.servletConfig = config;//在init方法对ServletConfig进行赋值
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
System.out.println("=========================根据参数key获取到值============================");
String encoding = servletConfig.getInitParameter("encoding");
System.out.println(encoding);
writer.write(encoding);
System.out.println();
System.out.println("=========================获取Servlet初始化配置所有数据============================");
Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();
while (initParameterNames.hasMoreElements()) {
String key = initParameterNames.nextElement();
System.out.println(key + " : "+ servletConfig.getInitParameter(key));
writer.write("\r\n"+key + " : " + servletConfig.getInitParameter(key));
}
System.out.println();
System.out.println("=========================获取配置的Servlet名============================");
String servletName = servletConfig.getServletName();
System.out.println(servletName);
writer.write("\r\n"+servletName);
System.out.println();
System.out.println("=========================获取配置的ServletContext对象============================");
System.out.println(servletConfig.getServletContext());
writer.write("\r\n"+servletConfig.getServletContext().toString());
}
}
<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">
<welcome-file-list>
<welcome-file>/demo/index.jspwelcome-file>
welcome-file-list>
<context-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
context-param>
<context-param>
<param-name>globalDescparam-name>
<param-value>this is ServletContextparam-value>
context-param>
web-app>
方法名 | 说明 |
---|---|
String getInitParameter(String var1) | 根据名称获取全局配置的参数 |
String getContextPath() | 获取当前应用的访问虚拟目录 |
String getRealPath(String var1) | 根据虚拟目录获取应用部署的磁盘绝对路径 |
void setAttribute(String var1, Object var2) | 向应用域对象中存储数据 |
Object getAttribute(String var1) | 通过名称获取应用域对象中的数据 |
void removeAttribute(String var1) | 通过名称移除应用域对象中的数据 |
package cn.cdw.demo;
import javax.servlet.ServletContext;
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.io.PrintWriter;
import java.util.Enumeration;
/**
* @author DW-CHEN
* ServletContext
*/
@WebServlet("/servletDemo11")
public class Demo11 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = getServletContext();//获取ServletContext对象
PrintWriter writer = resp.getWriter();
System.out.println("=======================根据name获取ServletContext配置数据========================");
String globalEncoding = servletContext.getInitParameter("globalEncoding");
System.out.println(globalEncoding);
writer.write(globalEncoding);
writer.write("\r\n");
System.out.println();
System.out.println("=======================获取ServletContext所有配置数据========================");
Enumeration<String> initParameterNames = servletContext.getInitParameterNames();
while (initParameterNames.hasMoreElements()) {
String s = initParameterNames.nextElement();
System.out.println(s + " : " + servletContext.getInitParameter(s));
writer.write(s + " : " + servletContext.getInitParameter(s)+"\r\n");
}
System.out.println();
System.out.println("=======================获取当前应用访问的虚拟目录========================");
String contextPath = servletContext.getContextPath();
System.out.println(contextPath);
writer.write(contextPath);
writer.write("\r\n");
System.out.println();
System.out.println("=======================根据虚拟目录获取应用部署在磁盘的绝对路径========================");
String realPath = servletContext.getRealPath("/");
System.out.println(realPath);
writer.write(realPath);
writer.write("\r\n");
writer.close();
/*
getRealPath(String var1)一般用于获取磁盘中文件的绝对路径
例如:
在src目录下创建a.txt
web目录下创建b.txt
WEB-INF目录下创建c.txt
然后获取到它们各个在应用部署目录的绝对路径
*/
System.out.println();
System.out.println("===================================================");
System.out.println(servletContext.getRealPath("/web/classes/a.txt"));
System.out.println(servletContext.getRealPath("/web/b.txt"));
System.out.println(servletContext.getRealPath("/c.txt"));
}
}
ServletContext域对象设置共享数据
package cn.cdw.demo;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author DW-CHEN
* ServletContext数据共享
*/
@WebServlet("/servletDemo12")
public class Demo12 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = getServletContext();
servletContext.setAttribute("data", "this is data data.....");//共享数据
//servletContext.removeAttribute("data");//删除共享数据
}
}
获取ServletContext域对象数据
package cn.cdw.demo;
import javax.servlet.ServletContext;
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;
/**
* @author DW-CHEN
* ServletContext数据共享
*/
@WebServlet("/servletDemo13")
public class Demo13 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = getServletContext();
String data = (String)servletContext.getAttribute("data");//获取共享数据
System.out.println(data);
resp.getWriter().write(data);
}
}
package cn.cdw.demo;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author DW-CHEN
* 手动创建servlet容器
*
* 注意:需要在src下创建META-INF包,然后在这个包下创建services包,然后在这个包下创建javax.servlet.ServletContainerInitializer文件,然后在这个文件里写注册配置servlet的类的全类名
*/
public class Demo15 extends HttpServlet {
@Override
public void init() throws ServletException {
System.out.println("手动创建容器初始化...");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("手动创建容器测试通过...");
resp.getWriter().write("TEST SUCCESS....");
}
}
package cn.cdw.demo;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import java.util.Set;
/**
* @author DW-CHEN
* 注册配置Servlet的功能类
*/
public class MyRegister implements ServletContainerInitializer {
@Override
public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
Demo15 demo15 = new Demo15();
ServletRegistration.Dynamic servletDynamic = servletContext.addServlet("servletDemo15", demo15);//在ServletContext对象中添加Servlet,得到Servlet动态配置对象
servletDynamic.addMapping("/servletDemo15");//设置映射访问资源路径
servletDynamic.setLoadOnStartup(1);//设置servlet加载时机,启动时加载
}
}
cn.cdw.demo.MyRegister
方法名 | 说明 |
---|---|
String getContextPath() | 获取虚拟目录名称 |
String getServletPath() | 获取Servlet映射路径 |
String getRemoteAddr() | 获取访问者ip地址 |
String getQueryString() | 获取请求的消息数据 |
String getRequestURI() | 获取统一资源标识符 |
StringBuffer getRequestURL() | 获取统一资源定位符 |
package cn.cdw.demo;
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.io.PrintWriter;
/**
* @author DW-CHEN
*
* request常用方法-获取各种路径
*/
@WebServlet("/servletDemo17")
public class Demo17 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
System.out.println("========================获取虚拟路径===========================");
String contextPath = req.getContextPath();
System.out.println(contextPath);
writer.write(contextPath);
writer.write("\r\n");
System.out.println();
System.out.println("========================获取请求映射路径===========================");
String servletPath = req.getServletPath();
System.out.println(servletPath);
writer.write(servletPath);
writer.write("\r\n");
System.out.println();
System.out.println("========================获取请求数据===========================");
String queryString = req.getQueryString();
System.out.println(queryString);
writer.write(queryString);
writer.write("\r\n");
System.out.println();
System.out.println("========================获取请求ip===========================");
String remoteAddr = req.getRemoteAddr();
System.out.println(remoteAddr);
writer.write(remoteAddr);
writer.write("\r\n");
System.out.println();
System.out.println("========================获取请求标识路径===========================");
String requestURI = req.getRequestURI();
System.out.println(requestURI);
writer.write(requestURI);
writer.write("\r\n");
writer.close();
System.out.println();
System.out.println("========================获取请求定位符路径===========================");
StringBuffer requestURL = req.getRequestURL();
System.out.println(requestURL);
writer.write(new String(requestURL));
writer.write("\r\n");
writer.close();
}
}
方法名 | 说明 |
---|---|
String getHeader(String name) | 根据请求头名称获取对应的值 |
Enumeration |
根据请求头名称获取多个值 |
Enumeration |
获取所有请求头名称 |
package cn.cdw.demo;
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.io.PrintWriter;
import java.util.Enumeration;
/**
* @author DW-CHEN
* request常用获取请求头信息方法
*/
@WebServlet("/servletDemo18")
public class Demo18 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
System.out.println("==========================获取所有请求头信息=============================");
Enumeration<String> headerNames = req.getHeaderNames();
while (headerNames.hasMoreElements()){
String name = headerNames.nextElement();
System.out.println("header: " + name + " values: " + req.getHeader(name));
writer.write("header: " + name + " values: " + req.getHeader(name));
writer.write("\r\n");
}
System.out.println();
System.out.println("=====================根据请求头获取对应的请求信息的值==========================");
String connection = req.getHeader("connection");
System.out.println(connection);
writer.write(connection);
writer.write("\r\n");
System.out.println();
System.out.println("============================根据请求头获取它所有的请求信息的值======================================");
Enumeration<String> headerValues = req.getHeaders("accept-encoding");
while (headerValues.hasMoreElements()) {
String value = headerValues.nextElement();
System.out.println(value);
writer.write(value);
writer.write("\r\n");
}
writer.close();
}
}
方法名 | 说明 |
---|---|
String getParameter(String name) | 根据名称获取数据 |
String[] getParameterValues(String name) | 根据名称获取所有的数据 |
Enumeration |
获取所有的名称 |
Map |
获取所有参数键值对 |
html测试页面
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册title>
<style>
.div1{
width: 1200px;
height: 800px;
border: solid 1px red;
}
.div2{
width: 600px;
height: 50%;
margin-left: 500px;
margin-top: 20px;
}
style>
head>
<body>
<div class="div1">
<div class="div2">
<form action="/request/servletDemo19" method="get" autocomplete="off">
姓名:<input type="text" name="name"><br/><br/>
密码:<input type="password" name="password"><br/><br/>
喜好:<input type="checkbox" name="hobby" value="play">玩游戏
<input type="checkbox" name="hobby" value="sleep">睡觉<br/><br/>
<button type="submit">注册button>
form>
div>
div>
body>
html>
Java代码
package cn.cdw.demo;
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.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;
/**
* @author DW-CHEN
* request获取请求参数常用方法
* 注意:这里并未处理中文乱码问题
*/
@WebServlet("/servletDemo19")
public class Demo19 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
System.out.println("======================获取请求参数属性获取请求参数数据=======================");
String name = req.getParameter("name");
System.out.println(name);
writer.write(name+"\r\n");
System.out.println();
System.out.println("===================根据请求属性名获取它对应的所有值=====================");
String[] hobbies = req.getParameterValues("hobby");
System.out.println(Arrays.toString(hobbies));
writer.write(Arrays.toString(hobbies)+"\r\n");
System.out.println();
System.out.println("=======================获取所有请求参数数据======================================");
Enumeration<String> parameterNames = req.getParameterNames();
while (parameterNames.hasMoreElements()){
String getName = parameterNames.nextElement();
System.out.println(getName + " : " + Arrays.toString(req.getParameterValues(getName)));
writer.write(getName + " : " + Arrays.toString(req.getParameterValues(getName))+"\r\n");
}
System.out.println();
System.out.println("===================获取所有的请求参数数据以键值对方式=======================");
Map<String, String[]> parameterMap = req.getParameterMap();
Set<String> keySet = parameterMap.keySet();
for (String key : keySet) {
System.out.println(key + " :" + Arrays.toString(req.getParameterValues(key)));
writer.write(key + " :" + Arrays.toString(req.getParameterValues(key))+"\r\n");
}
writer.close();
}
}
html测试页面
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册title>
<style>
.div1{
width: 1200px;
height: 800px;
border: solid 1px red;
}
.div2{
width: 600px;
height: 50%;
margin-left: 500px;
margin-top: 20px;
}
style>
head>
<body>
<div class="div1">
<div class="div2">
<form action="/request/servletDemo20" method="get" autocomplete="off">
姓名:<input type="text" name="name"><br/><br/>
密码:<input type="password" name="password"><br/><br/>
喜好:<input type="checkbox" name="hobby" value="play">玩游戏
<input type="checkbox" name="hobby" value="sleep">睡觉<br/><br/>
<button type="submit">注册button>
form>
div>
div>
body>
html>
Servlet
package cn.cdw.demo;
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.io.PrintWriter;
import java.util.Arrays;
/**
* @author DW-CHEN
* 手动将获取的请求数据封装到对象中
*/
@WebServlet("/servletDemo20")
public class Demo20 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
String name = req.getParameter("name");
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobby");
Student student = new Student(name, password, hobbies);//封装到学生对象中
System.out.println(student);
writer.write(String.valueOf(student));
writer.close();
}
}
//学生对象
class Student{
private String name;
private String password;
private String[] hobby;
public Student() {
}
public Student(String name, String password, String[] hobby) {
this.name = name;
this.password = password;
this.hobby = hobby;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", password='" + password + '\'' +
", hobby=" + Arrays.toString(hobby) +
'}';
}
}
html测试页面
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册title>
<style>
.div1{
width: 1200px;
height: 800px;
border: solid 1px red;
}
.div2{
width: 600px;
height: 50%;
margin-left: 500px;
margin-top: 20px;
}
style>
head>
<body>
<div class="div1">
<div class="div2">
<form action="/request/servletDemo21" method="get" autocomplete="off">
姓名:<input type="text" name="name"><br/><br/>
密码:<input type="password" name="password"><br/><br/>
喜好:<input type="checkbox" name="hobby" value="play">玩游戏
<input type="checkbox" name="hobby" value="sleep">睡觉<br/><br/>
<button type="submit">注册button>
form>
div>
div>
body>
html>
Servlet
package cn.cdw.demo;
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.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
/**
* @author DW-CHEN
* 通过反射的方式将获取到的请求数据封装到对象中
*/
@WebServlet("/servletDemo21")
public class Demo21 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
Student1 student = new Student1();
Map<String, String[]> parameterMap = req.getParameterMap();//获取到所有的请求参数值,以键值对的方式
Set<String> keySet = parameterMap.keySet();
for (String name : keySet) {
String[] parameterValues = req.getParameterValues(name);//根据键获取对应的所有值
try {
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, student.getClass());//获取学生对象的属性描述器
Method writeMethod = propertyDescriptor.getWriteMethod();//通过属性描述器获取学生对象对应的setXXX方法
if (parameterValues.length > 1) {
//判断根据键获取到的值是否时多个,如果是,则将它强转一下
writeMethod.invoke(student, (Object)parameterValues);
}else {
writeMethod.invoke(student, parameterValues);
}
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
System.out.println(student);
writer.write(student.toString());
writer.close();
}
}
//学生对象
class Student1{
private String name;
private String password;
private String[] hobby;
public Student1() {
}
public Student1(String name, String password, String[] hobby) {
this.name = name;
this.password = password;
this.hobby = hobby;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", password='" + password + '\'' +
", hobby=" + Arrays.toString(hobby) +
'}';
}
}
使用工具类需要到入commons-beanutils-1.9.2.jar/commons-logging-1.1.1.jar包,下载地址:https://download.csdn.net/download/qq_42795277/12805872
html测试页面
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册title>
<style>
.div1{
width: 1200px;
height: 800px;
border: solid 1px red;
}
.div2{
width: 600px;
height: 50%;
margin-left: 500px;
margin-top: 20px;
}
style>
head>
<body>
<div class="div1">
<div class="div2">
<form action="/request/servletDemo22" method="get" autocomplete="off">
姓名:<input type="text" name="name"><br/><br/>
密码:<input type="password" name="password"><br/><br/>
喜好:<input type="checkbox" name="hobby" value="play">玩游戏
<input type="checkbox" name="hobby" value="sleep">睡觉<br/><br/>
<button type="submit">注册button>
form>
div>
div>
body>
html>
学生类
package cn.cdw.demo;
import java.util.Arrays;
public class Student2{
private String name;
private String password;
private String[] hobby;
public Student2() {
}
public Student2(String name, String password, String[] hobby) {
this.name = name;
this.password = password;
this.hobby = hobby;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", password='" + password + '\'' +
", hobby=" + Arrays.toString(hobby) +
'}';
}
}
Servlet
package cn.cdw.demo;
import org.apache.commons.beanutils.BeanUtils;
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.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Map;
/**
* @author DW-CHEN
* 通过工具类将请求数据封装到对象中
* 注意:需要在web目录下导入commons-beanutils-1.9.2.jar/commons-logging-1.1.1.jar包
*/
@WebServlet("/servletDemo22")
public class Demo22 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Student2 student = new Student2();
Map<String, String[]> parameterMap = req.getParameterMap();
try {
BeanUtils.populate(student,parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(student);
resp.getWriter().write(student.toString());
}
}
方法名 | 说明 |
---|---|
BufferedReader getReader | 获取字符输入流 |
ServletInputStream getInputStream() | 获取字节输入流 |
html测试页面
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册title>
<style>
.div1{
width: 1200px;
height: 800px;
border: solid 1px red;
}
.div2{
width: 600px;
height: 50%;
margin-left: 500px;
margin-top: 20px;
}
style>
head>
<body>
<div class="div1">
<div class="div2">
<form action="/request/servletDemo23" method="get" autocomplete="off">
姓名:<input type="text" name="name"><br/><br/>
密码:<input type="password" name="password"><br/><br/>
喜好:<input type="checkbox" name="hobby" value="play">玩游戏
<input type="checkbox" name="hobby" value="sleep">睡觉<br/><br/>
<button type="submit">注册button>
form>
div>
div>
body>
html>
通过字符对象获取请求数据,注意:请求方式必须为post方式
package cn.cdw.demo;
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;
/**
* @author DW-CHEN
* 通过流对象获取请求数据
*
* 通过字符对象获取请求数据,注意:请求方式必须为post方式
*/
@WebServlet("/servletDemo23")
public class Demo23 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BufferedReader bufferedReader = req.getReader();
String data;
while ((data = bufferedReader.readLine()) != null) {
System.out.println(data);
resp.getWriter().write(data);
}
}
}
通过字节流对象获取请求数据,注意:请求方式必须为post方式
package cn.cdw.demo;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author DW-CHEN
* 通过流对象获取请求数据
*
* 通过字节流对象获取请求数据,注意:请求方式必须为post方式
*/
@WebServlet("/servletDemo24")
public class Demo24 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletInputStream inputStream = req.getInputStream();
byte[] bytes = new byte[1024];
int len;
while ((len = inputStream.read(bytes)) != -1){
System.out.println(new String(bytes,0,len));
resp.getWriter().write(new String(bytes,0,len));
}
}
}
req.setCharacterEncoding("UTF-8");//指定编码
方法名 | 说明 |
---|---|
void setAttribute(String name,Object value) | 向请求域对象中存储数据 |
Object getAttribute(String name) | 通过名称获取请求域对象中的数据 |
void removeAttribute(String name) | 通过名称移请求域对象中的数据 |
就是客户端的一次请求到达后,发现需要借助其他的Servlet来实现功能
特点:
方法名 | 说明 |
---|---|
RequestDispatcher getRequestDispatcher(String name) | 获取请求调度对象 |
void forward(ServletRequest req,ServletResponse resq) | 实现转发 |
package cn.cdw.demo;
import javax.servlet.RequestDispatcher;
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;
/**
* @author DW-CHEN
*
* 请求域/请求转发
*/
@WebServlet("/servletDemo26")
public class Demo26 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("data","我是request域的共享数据");
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/servletDemo27");//设置转发到 /request/servletDemo27
requestDispatcher.forward(req, resp);
}
}
package cn.cdw.demo;
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;
/**
* @author DW-CHEN
*
* 请求转发到这个类进行处理
*/
@WebServlet("/servletDemo27")
public class Demo27 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object data = req.getAttribute("data");//根据名称获取request域的共享数据
System.out.println("Demo27类方法执行了,收到的request域的共享数据为:"+data);
resp.getWriter().write("TEST SUCCESS.....");
}
}
方法名 | 说明 |
---|---|
RequestDispatcher getRequestDispatcher(String name) | 获取请求调度对象 |
void include(ServletRequest req,ServletResponse resq) | 实现包含 |
package cn.cdw.demo;
import javax.servlet.RequestDispatcher;
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;
/**
* @author DW-CHEN
* 请求包含
*/
@WebServlet("/servletDemo28")
public class Demo28 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("我自己...");
resp.getWriter().write("mySelf...."+"\r\n");
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/servletDemo29");//设置请求包含的地址
requestDispatcher.include(req, resp);
}
}
package cn.cdw.demo;
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;
/**
* @author DW-CHEN
* 请求包含
*/
@WebServlet("/servletDemo29")
public class Demo29 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("我是另一个功能了....");
resp.getWriter().write("other....");
}
}
状态码 | 说明 |
---|---|
200 | 成功 |
302 | 重定向 |
304 | 请求资源未改变,使用缓存 |
400 | 请求错误,常见于请求参数错误 |
404 | 请求资源未找到 |
405 | 请求方式不支持 |
500 | 服务器错误 |
方法名 | 说明 |
---|---|
ServletOutputStream getOutputStream() | 获取响应字节输出流对象 |
PrintWriter getWriter() | 获取响应字符输出流对象 |
void setContentType(“text/html;charset=UTF-8”) | 设置响应内容类型,解决中文乱码问题 |
response 字节流方式响应消息
package cn.cdw.demo;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author DW-CHEN
*
* 乱码问题
*
* response 字节流方式响应消息
*/
@WebServlet("/servletDemo30")
public class Demo30 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");//统一设置编码
String str = "我是响应消息";
ServletOutputStream outputStream = resp.getOutputStream();
outputStream.write(str.getBytes("UTF-8"));
}
}
response 字符流方式响应消息
package cn.cdw.demo;
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.io.PrintWriter;
/**
* @author DW-CHEN
*
* 乱码问题
*
* response 字符流方式响应消息
*/
@WebServlet("/servletDemo31")
public class Demo31 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
String str = "我是字符流方式的响应消息";
PrintWriter writer = resp.getWriter();
writer.write(str);
}
}
response字节流方式响应图片
package cn.cdw.demo;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
/**
* @author DW-CHEN
*
* response字节流方式响应图片
*/
@WebServlet("/servletDemo32")
public class Demo32 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = req.getServletContext();
String realPath = servletContext.getRealPath("/img/1.jpg");//需要根据ServletContext对象获取到资源的绝对路径,不然读取不到资源
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(realPath));//读取资源文件
ServletOutputStream outputStream = resp.getOutputStream();//获取响应字节流
byte[] bytes = new byte[1024];
int len;
while ((len = bufferedInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
bufferedInputStream.close();
}
}
方法名 | 说明 |
---|---|
void setDataHeader(String name,long time) | 设置消息头添加缓存 |
package cn.cdw.demo;
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;
/**
* @author DW-CHEN
*
* 设置缓存时间
*/
@WebServlet("/servletDemo33")
public class Demo33 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
String str = "我要作为缓存的数据....";
resp.setDateHeader("Expires",System.currentTimeMillis() + 1000*1*60*10);//缓存10分钟,设置缓存时间为当前访问时间加上10分钟
resp.getWriter().write(str);
}
}
方法名 | 说明 |
---|---|
void setHeader(String name,Stirng value) | 设置消息头刷新 |
package cn.cdw.demo;
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;
/**
* @author DW-CHEN
* response 定时刷新
*/
@WebServlet("/servletDemo34")
public class Demo34 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
String str = "3秒后自动跳回注册页面";
resp.getWriter().write(str);
resp.setHeader("Refresh","3;URL=/response/html/register.html");//注意:跳转路径需要加访问虚拟路径
}
}
就是客户端的一次请求到达后,发现需要借助其它的Servlet来实现功能
特点:
resp.setStatus(302);
resp.setHeader("location","/request/servletDemo")
方法名 | 说明 |
---|---|
void sendRedirect(String name) | 设置重定向 |
package cn.cdw.demo;
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.io.PrintWriter;
/**
* @author DW-CHEN
* 请求重定向
*
* 注意:它的请求域是不可以共享数据的
*/
@WebServlet("/servletDemo35")
public class Demo35 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter writer = resp.getWriter();
req.setAttribute("data","我是共享数据...........");
System.out.println("我自己执行了....");
//重定向
resp.sendRedirect(req.getContextPath()+"/servletDemo36");//需要动态获取虚拟路径拼接上映射路径
}
}
package cn.cdw.demo;
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.io.PrintWriter;
/**
* @author DW-CHEN
* 请求重定向
*
* 注意:它的请求域是不可以共享数据的
*/
@WebServlet("/servletDemo36")
public class Demo36 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter writer = resp.getWriter();
Object data = req.getAttribute("data");
System.out.println("共享数据:"+data);
writer.write("共享数据:" + data);//重定向是不可以共享数据的,所以为null
System.out.println("其他方法执行了....");
}
}
response 响应对象下载文件
package cn.cdw.demo;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
/**
* @author DW-CHEN
* response 响应对象下载文件
*/
@WebServlet("/servletDemo37")
public class Demo37 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
ServletContext servletContext = req.getServletContext();
String realPath = servletContext.getRealPath("/img/1.jpg");
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(realPath));
resp.setHeader("Content-Type","application/octet-stream");//设置支持类型响应头参数,Content-Type:表示支持类型;application/octet-stream:表示应用的类型为字节流
resp.setHeader("Content-Disposition","attachment;filename=1.jpg");//设置下载处理响应头参数,Content-Disposition:表示处理的形式;attachment:表示以附件的形式下载;filename:表示指定下载文件的名称(可以自定义命名)
ServletOutputStream outputStream = resp.getOutputStream();
byte[] bytes = new byte[1024];
int len;
while ((len = bufferedInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
bufferedInputStream.close();
}
}
属性名 | 作用 |
---|---|
name | Cooke的名称 |
value | Cookie的值(不支持中文) |
path | Cookie的路径 |
domain | Cooke的域名 |
maxAge | Cookie的存活时间 |
varsion | Cookie的版本号 |
comment | Cookie的描述 |
方法名 | 说明 |
---|---|
Cookie(String name,String value) | 构造方法创建对象 |
属性对应的get/set方法 | 赋值和获取值 |
方法名 | 说明 |
---|---|
void addCookie(Cookie cookie) | 向客户端添加Cookie |
方法名 | 说明 |
---|---|
Cookie[] getCookies() | 获取所有的Cookie |
通过cookie记录最后访问时间
package cn.cdw.demo;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author DW-CHEN
* 通过cookie记录最后访问时间
*/
@WebServlet("/servletDemo40")
public class Demo40 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter writer = resp.getWriter();
Cookie cookie = new Cookie("time", System.currentTimeMillis()+"");//创建一个Cookie记录最后访问时间
cookie.setMaxAge(3600);//设置cookie最大存活时间(单位为秒)
resp.addCookie(cookie);//添加cookie到客户端
Cookie[] cookies = req.getCookies();//获取所有客户端cookie
for (Cookie cookie1 : cookies) {
if ("time".equals(cookie1.getName())) {
//根据名称找到记录最后访问时间的cookie
String value = cookie1.getValue();//获取到记录最后访问时间的值
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//进行一下时间格式化
String lastTime = simpleDateFormat.format(new Date(Long.parseLong(value)));//时间格式化最后访问时间格式
writer.write("最后访问时间为:"+lastTime);
}
}
}
}
HttpSession:服务端会话管理技术(本质也是采用客户端会话管理技术)
作用:可以实现数据共享
域对象 | 说明 |
---|---|
ServletContext | 应用域,在整个应用之间实现数据共享 |
ServletRequest | 请求域,在当前请求或请求转发之间实现数据共享 |
HttpSession | 会话域,在当前会话访问之间实现数据共享 |
方法名 | 说明 |
---|---|
void setAttribute(String name,Object value) | 设置共享数据 |
Object getAttribute(String name) | 获取共享数据 |
void removeAttribute(String name) | 移除共享数据 |
String getId() | 获取唯一标识名称 |
void Invalidate() | 让session立即生效 |
方法名 | 说明 |
---|---|
HttpSession getSession() | 获取HttpSession对象 |
HttpSession getSession(boolean create) | 获取HttpSession对象,未获取到是否自动创建 |
package cn.cdw.demo;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author DW-CHEN
* session
*
* 通过session域设置共享数据,然后另一个servlet获取这个session域的共享数据
*/
@WebServlet("/servletDemo41")
public class Demo41 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter writer = resp.getWriter();
HttpSession session = req.getSession();
session.setAttribute("data","我是Session域的共享数据....");
writer.write("设置session域的的共享数据成功...."+"
");
writer.write(session.toString()+"
");
writer.write(session.getId()+"
");
}
}
package cn.cdw.demo;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author DW-CHEN
* session
*/
@WebServlet("/servletDemo42")
public class Demo42 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter writer = resp.getWriter();
HttpSession session = req.getSession();
Object data = session.getAttribute("data");
writer.write("session域的共享数据为:" + data+"
");
writer.write(session.toString()+"
");
writer.write(session.getId()+"
");
}
}
浏览器禁用Cookie
package cn.cdw.demo;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author DW-CHEN
* 处理浏览器cookie功能关闭后影响session对象问题
*
* 方式一:提示用户打开cookie功能
*/
@WebServlet("/servletDemo43")
public class Demo43 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter writer = resp.getWriter();
HttpSession session = req.getSession(false);//当没有session域时不自动创建session对象
if (session == null) {
writer.write("为了不影响您的使用,请把浏览器的cookie功能打开");
}
writer.write("正常使用....");
}
}
package cn.cdw.demo;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author DW-CHEN
* 处理浏览器cookie功能关闭后影响session对象问题
*
* 方式二:实现url重写,在请求路径后拼接上(;jssionid=session的唯一标识id) 不建议使用
*/
@WebServlet("/servletDemo44")
public class Demo44 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter writer = resp.getWriter();
HttpSession session = req.getSession();
writer.write(session.toString()+"
");
writer.write(session.getId()+"
");
writer.write("点击我");
}
}
钝化和活化:
什么时候钝化
注意:HttpSession的序列化是由服务器自动完成的
JSP(Java Server Pages):是一种动态网页技术标准
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
JSP 标题
<%
System.out.println("jsp 代码块");
out.println("jsp代码块");
%> <%--jsp代码块--%>
<%="jsp表达式"%><%--jsp表达式,相当于out.println("jsp表达式");--%>
<%! String str = "jsp声明";%><%--jsp声明,注意<%! %>:表示声明成员变量或方法,<% %>:表示声明局部变量--%>
<%out.println(str);%>
属性名 | 说明 |
---|---|
contentType | 响应正文支持的类型和设置编码格式 |
language | 使用的语言,默认是java |
errorPage | 当前页面出现异常后跳转的页面 |
isErrorPage | 是否抓住异常,如果为true,则页面种就可以使用异常对象,默认为false |
import | 导包 |
session | 是否创建HttpSession对象,默认为true |
buffer | 设定JspWriter输出jsp内容缓存的大小,默认为8KB |
pageEncoding | 翻译jsp时所用的编码格式 |
isElgnored | 是否忽略EL表达式,默认为false |
隐式对象的名称 | 代表的实际对象 |
---|---|
request | javax.servlet.http.HttpServletRquest |
response | javax.servlet.http.HttpServletResponse |
session | javax.servelt.http.HttpSerssion |
application | javax.servlet.ServletContext |
page | java.lang.Object |
config | javax.servlet.ServletConfig |
exception | java.lang.Throwable |
out | javax.servlet.jsp.JspWriter |
pageContext | javax.servlet.jsp.PageContext |
域对象名称 | 说明 |
---|---|
pageContext | 页面域对象,范围最小,只能当前页面使用 |
ServletRequest | 请求域对象,请求范围,一次请求或当前请求转发用;请求转发后,再次转发的请求域会丢失 |
HttpSession | 会话域对象,多次请求数据共享时使用,但不同的客户端不能共享 |
ServletContext | 应用域,范围最大,整个应用都可以使用;尽量少用,如果对数据有修改需要做同步处理 |
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
el表达式
<%request.setAttribute("data","我是测试数据");%>
Java代码块:<%out.println(request.getAttribute("data"));%>
jsp表达式:<%=request.getAttribute("data")%>
el表达式:${data}
自定义类
package cn.cdw.demo;
public class Student3{
private String name;
private Integer age;
private String address;
public Student3() {
}
public Student3(String name, Integer age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
<%@ page import="cn.cdw.demo.Student3" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
EL 获取不同的数据
===================获取基本数据类型============================
<%
String s = "你好 el....";
pageContext.setAttribute("str", s);
%>
${str}
===================获取自定义对象类型============================
<%
Student3 student = new Student3("小明", 12, "深圳");
pageContext.setAttribute("student", student);
%>
学生对象:${student}
学生姓名:${student.name}
学生年龄:${student.age}
学生地址:${student.address}
===================获取数组类型============================
<%
int[] arr = {12, 22};
pageContext.setAttribute("arr", arr);
%>
数组对象:${arr}
数组的第一个元素:${arr[0]}
数组的第二个元素:${arr[1]}
===================获取list集合数据类型============================
<%
ArrayList arrayList = new ArrayList<>();
arrayList.add(new Student3("小李", 21, "深圳"));
arrayList.add(new Student3("小红", 22, "北京"));
arrayList.add(new Student3("小明", 43, "上海"));
pageContext.setAttribute("arrayList", arrayList);
%>
集合对象:${arrayList}
集合中的第一个学生对象:${arrayList[0]}
集合中的第一个学生对象的姓名:${arrayList[0].name}
集合中的第二个学生对象的地址:${arrayList[1].address}
===================获取map集合数据类型============================
<%
Map map = new HashMap<>();
map.put("stu1", new Student3("小明", 12, "深圳"));
map.put("stu2", new Student3("小李", 22, "北京"));
pageContext.setAttribute("map", map);
%>
map集合:${map}
map集合中Kye为stu2的学生对象:${map.stu2}
map集合中Kye为stu2的学生对象的姓名:${map.stu2.name}
map集合中Kye为stu2的学生对象的年龄:${map.stu2.age}
map集合中Kye为stu2的学生对象的地址:${map.stu2.address}
运算符 | 作用 |
---|---|
== 或者 eq | 等于 |
!= 或者 ne | 不等于 |
< 或者 lt | 小于 |
> 或者 gt | 大于 |
<= 或者 le | 小于等于 |
>= 或者 ge | 大于等于 |
运算符 | 作用 |
---|---|
&& 或者 and | 并且 |
|| 或者 or | 或者 |
! 或者 not | 取反 |
运算符 | 作用 |
---|---|
empty | 判断对象是否空,判断字符串是否为空字符串,判断容器元素是否为0 |
条件 ? 表达式1 : 表达式2 | 三元运算符 |
隐式对象名称 | 说明 |
---|---|
pageContext | 对应的JSP隐式对象是PageContext,功能完全相同 |
applicationScope | 操作应用域数据 |
sessionScope | 操作会话域对象数据 |
requestScope | 操作请求域对象数据 |
pageScope | 操作页面域对象数据 |
header | 获取请求头数据 |
headerValues | 获取请求头数据(多个值) |
param | 获取请求参数数据 |
paramValues | 获取请求参数数据(多个值) |
initParam | 获取全局配置参数数据 |
cookie | 获取Cookie对象 |
<%@ page import="java.util.Collection" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
EL表达式隐式对象
========================================pageContext获取四大域的对象的数据,从小到大查找============================================
<%
pageContext.setAttribute("data", "pageContext");
request.setAttribute("data", "request");
session.setAttribute("data", "session");
application.setAttribute("data","application");
%>
${data}
========================================pageContext获取JSP其他八大隐式对象,并调用对象的方法============================================
<%
String contextPath = request.getContextPath();
out.println("jsp的request隐式对象获取访问虚拟路径:"+contextPath);
%>
el表达式获取jsp的request隐式对象获取访问虚拟路径:${pageContext.request.contextPath}
===========================pageScope,requestScope,sessionScope,applicationScope操作四大域对象数据=========================================================
<%
pageContext.setAttribute("data", "pageContext");
request.setAttribute("data", "request");
session.setAttribute("data", "session");
application.setAttribute("data","application");
%>
${applicationScope.data}
${sessionScope.data}
${requestScope.data}
${pageScope.data}
===========================header,headerValues=========================================================
获取accept-encoding这个请求头的所有值:${header["accept-encoding"]}
获取所有请求头的数据,map集合格式:${headerValues}
获取所有请求头的数据,map集集合中的键为accept-encoding的所有值:${headerValues["accept-encoding"]}
===========================param,paramValues获取请求参数值=========================================================
获取请求属性为name的值:${param.name}
获取所有的请求参数,map集合格式:${paramValues}
获取请求属性为hobby的所有值,数组格式:${paramValues.hobby}
获取请求属性为hobby的所有值的第一个参数:${paramValues.hobby[0]}
获取请求属性为hobby的所有值的第二个参数:${paramValues.hobby[1]}
=============================initParam获取配置全局参数的数据,全局参数在web.xml中配置=======================================================
获取配置全局参数名为encoding的数据:${initParam["encoding"]}
=============================cookie,获取cookie对象=======================================================
获取所有cookie对象,map集合格式:${cookie}
获取cookie名为JSESSIONID的对象:${cookie.JSESSIONID}
获取cookie名为JSESSIONID的name:${cookie.JSESSIONID.name}
获取cookie名为JSESSIONID的value:${cookie.JSESSIONID.value}
组成 | 说明 |
---|---|
core | 核心标签库,通用的逻辑处理 |
fmt | 国际化,不同地域显示不同语言 |
functions | EL函数,EL表达式可以使用的方法 |
sql | 操作数据库 |
xml | 操作XML |
使用JSTL需要下载的jstl-1.2.jar包,下载地址:https://download.csdn.net/download/qq_42795277/12804268
标签库名称 | 说明 |
---|---|
<标签名:if> | 流程控制,用于条件判断 |
<标签名:choose> ,<标签名:when>,<标签名:otherwise> | 流程控制,用于多条件判断 |
<标签名:forEach> | 迭代遍历,用于循环遍历 |
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
jstl使用
=======================jstl的使用,需要在web下的WEB-INF添加jstl-1.2.jar包===============================================================
<%
String str = "A";
pageContext.setAttribute("data", str);
%>
=======================if判断语句===============================================================
你的成绩优秀....
=======================多条件判断语句===============================================================
你的成绩优秀....
你的成绩很好....<
你的成绩一般....
继续努力....
数据错误..
=======================遍历集合===============================================================
<%
ArrayList arrayList = new ArrayList<>();
arrayList.add(12);
arrayList.add(22);
arrayList.add(33);
pageContext.setAttribute("arrayList", arrayList);
%>
${num}
方法名 | 说明 |
---|---|
void init(FilterConfig config) | 初始化方法 |
void doFilter(ServletRequet req,ServletResponse res,FilterChain chain) | 请求资源和响应资源过滤 |
void destroy() | 销毁方法 |
方法名 | 说明 |
---|---|
void doFilter(ServletRequest req,ServletResponse resp) | 放行方法 |
web.xml手动配置过滤器映射
<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">
<welcome-file-list>
<welcome-file>/demo/index.jspwelcome-file>
welcome-file-list>
<filter>
<filter-name>filterNameDemo48filter-name>
<filter-class>cn.cdw.demo.Demo48filter-class>
filter>
<filter-mapping>
<filter-name>filterNameDemo48filter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
注解的方式,使用过滤器统一处理编码问题
package cn.cdw.demo;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author DW-CHEN
* 通过Filter过滤器解决多个资源写出中文乱码问题
*/
@WebFilter("/*") //设置过滤拦截所有请求
public class Demo48 implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
try {
HttpServletRequest req = (HttpServletRequest)servletRequest;
HttpServletResponse resp = (HttpServletResponse)servletResponse;
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
filterChain.doFilter(req, resp);//处理完成后放行
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void destroy() {
}
}
FilterConfig是一个接口,代表过滤器的配置对象,可以加载一些初始化参数
方法名 | 说明 |
---|---|
String getFilterName() | 获取过滤器对象名称 |
String getInitParameter(String key) | 根据key获取value |
Enueration |
获取所有的参数的key |
ServletContext | getServletContext() |
web.xml
<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">
<welcome-file-list>
<welcome-file>/demo/index.jspwelcome-file>
welcome-file-list>
<filter>
<filter-name>filterNameDemo51filter-name>
<filter-class>cn.cdw.demo.Demo51filter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>nameparam-name>
<param-value>aaaparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>filterNameDemo51filter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
package cn.cdw.demo;
import javax.servlet.*;
import java.io.IOException;
import java.util.Enumeration;
/**
* @author DW-CHEN
* FilterConfig
*/
public class Demo51 implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("======================获取过滤器名称========================");
String filterName = filterConfig.getFilterName();
System.out.println(filterName);
System.out.println("\r\n");
System.out.println("\r\n");
System.out.println("=========================根据名称获取过滤器中的初始化值(web.xml中配置的过滤初始化值)===================================");
String encoding = filterConfig.getInitParameter("encoding");
System.out.println(encoding);
System.out.println("\r\n");
System.out.println("\r\n");
System.out.println("=========================获取过滤器中的所有初始化值(web.xml中配置的过滤初始化值)===================================");
Enumeration<String> initParameterNames = filterConfig.getInitParameterNames();
while (initParameterNames.hasMoreElements()) {
String name = initParameterNames.nextElement();
System.out.println(name + " : " + filterConfig.getInitParameter(name));
}
System.out.println("\r\n");
System.out.println("\r\n");
System.out.println("=========================获取上下文对象,然后可以调用上下文对象相关方法使用===================================");
ServletContext servletContext = filterConfig.getServletContext();
String contextPath = servletContext.getContextPath();
System.out.println(contextPath);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
}
@Override
public void destroy() {
}
}
web.xml
<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">
<welcome-file-list>
<welcome-file>/demo/index.jspwelcome-file>
welcome-file-list>
<filter>
<filter-name>filterNameDemo53filter-name>
<filter-class>cn.cdw.demo.Demo53filter-class>
<async-supported>trueasync-supported>
filter>
<filter-mapping>
<filter-name>filterNameDemo53filter-name>
<url-pattern>/index.jspurl-pattern>
<dispatcher>REQUESTdispatcher>
<dispatcher>ERRORdispatcher>
<dispatcher>FORWARDdispatcher>
<dispatcher>INCLUDEdispatcher>
<dispatcher>ASYNCdispatcher>
filter-mapping>
<error-page>
<exception-type>java.lang.Exceptionexception-type>
<location>/err/err.jsplocation>
error-page>
<error-page>
<error-code>404error-code>
<location>/err/err.jsplocation>
error-page>
web-app>
Servlet,看如果修改拦截配置,测试访问servlet看过滤器是否执行
package cn.cdw.demo;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author DW-CHEN
* servlet
* 过滤器的五种拦截行为
*/
@WebServlet("/servletDemo52")
public class Demo52 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// int i = 1 / 0; //测试出现异常,是否执行过滤器,注意测试时修改一下拦截对应的路径
System.out.println("Demo52servlet执行了....");
//req.getRequestDispatcher("/index.jsp").forward(req, resp);//测试进行转发时,是否执行过滤器,注意测试时修改一下拦截对应的路径
req.getRequestDispatcher("/index.jsp").include(req, resp);//测试进行包含时,是否执行过滤器,注意测试时修改一下拦截对应的路径
}
}
过滤器
package cn.cdw.demo;
import javax.servlet.*;
import java.io.IOException;
/**
* @author DW-CHEN
* 过滤器的五种拦截行为
*/
public class Demo53 implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("过滤器Demo53执行了.......");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
监听对象的
监听属性变化的
监听会话相关感知型
package cn.cdw.demo;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/**
* @author DW-CHEN
* 监听ServletContext对象的初创建和销毁
*/
@WebListener
public class Demo54 implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("ServletContext对象创建了,对象为:" + servletContextEvent.getServletContext());
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("ServletContext对象销毁了....");
}
}
方法名 | 说明 |
---|---|
void contextInitialized(ServletContextEvent sec) | 对象创建的时候执行该方法 |
void contextDestroyed(ServletContextEvent sce) | 对象销毁时执行该方法 |
参数:ServletContextEvent 代表事件对象,事件对象中封装了事件源,也就是ServletContext,真正的事件指的是创建或销毁ServletContext对象的操作
方法名 | 说明 |
---|---|
void sessionCreated(HttpSessionEvent se) | 对象创建时执行该方法 |
void sessionDestroyed(HttpSessionEvent se) | 对象销毁时执行该方法 |
参数:HttpSessionEvent 代表事件对象,事件对象中封装了事件源,也就是HttpSession,真正的事件指的时创建或销毁HttpSession对象的操作
ServletRequestListener:用于监听ServletRequest对象的创建和销毁
方法名 | 说明 |
---|---|
void requestInitialized(ServletRequestEvent sre) | 对象创建的时候执行该方法 |
void requestDestroyed(ServletRequestEvent sre) | 对象销毁时执行该方法 |
参数:ServletRequestEvent 代表事件对象,事件对象中封装了事件源,也就是ServletRequest,真正的事件指的时创建或销毁ServletRequest对象的操作
package cn.cdw.demo;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.annotation.WebListener;
/**
* @author DW-CHEN
* 监听应用域对象属性变化
*/
@WebListener
public class Demo55 implements ServletContextAttributeListener {
@Override
public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
System.out.println("应用域添加了属性值为:" + servletContextAttributeEvent.getServletContext().getAttribute("name"));
}
@Override
public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
System.out.println("应用域修改了属性值为:" + servletContextAttributeEvent.getServletContext().getAttribute("name"));
}
@Override
public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
System.out.println("应用域删除了属性,值为:" + servletContextAttributeEvent.getServletContext().getAttribute("name"));
}
}
测试Servlet
package cn.cdw.demo;
import javax.servlet.ServletContext;
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;
/**
* @author DW-CHEN
* 测试应用域对象属性发生改变,监听器是否执行
*/
@WebServlet("/servletDemo56")
public class Demo56 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = req.getServletContext();
servletContext.setAttribute("name", "添加了数据");
servletContext.setAttribute("name", "修改了数据");
servletContext.removeAttribute("name");//删除了数据
}
}
方法名 | 说明 |
---|---|
void attributeAdded(ServletContextAttributeEvent scae) | 域中添加属性时执行该方法 |
void attributeRemoved(ServletContextAttributeEvent scae) | 域中异常属性时执行该方法 |
void attributeReplaced(ServletContextAttributeEvent scae) | 域中替换属性时执行该方法 |
参数:ServletContextAttributeEvent 代表事件对象,事件对象中封装了事件源,也就是ServletContex,真正的事件指的是添加,移除,替换应用域中的属性操作
方法名 | 说明 |
---|---|
void attributeAdded(HttpSessionBindingEvent se) | 域中添加属性时执行该方法 |
void attributeRemoved(HttpSessionBindingEvent se) | 域中异常属性时执行该方法 |
void attributeReplaced(HttpSessionBindingEvent se) | 域中替换属性时执行该方法 |
参数:HttpSessionBindingEvent 代表事件对象,事件对象中封装了事件源,也就是HttpSession,真正的事件指的是添加,移除,替换会话域中的属性操作
方法名 | 说明 |
---|---|
void attributeAdded(ServletRequestAttributeEvent srae) | 域中添加属性时执行该方法 |
void attributeRemoved(ServletRequestAttributeEvent srae) | 域中异常属性时执行该方法 |
void attributeReplaced(ServletRequestAttributeEvent srae) | 域中替换属性时执行该方法 |
参数:ServletRequestAttributeEvent 代表事件对象,事件对象中封装了事件源,也就是ServletRequest,真正的事件指的是添加,移除,替换请求域中的属性操作
方法名 | 说明 |
---|---|
void valueBound(HttpSessionBindingEvent event) | 数据添加到会话域中(绑定)是执行该方法 |
void valueUnbound(HttpSessionBindingEvent event) | 数据从会话域中移除(解绑)时执行该方法 |
参数:HttpSessionBindingEvent 代表事件对象,事件对象中封装了事件源,也是是HttpSession,真正的事件指的是添加,移除会话域中的数据操作
方法名 | 说明 |
---|---|
void sessionWillPassivate(HttpSessionEven se) | 会话数据钝化时执行该方法 |
void sessionDidActivate(HttpSessionEvent se) | 会话域中数据活化时执行该方法 |
参数:HttpSessionEvent代表事件对象,事件对象中封装了事件源,也就是HttpSession,正在的事件指的是会话域中数据钝化,活化操作