个人主页: 叶落闲庭
我的专栏:
c语言
数据结构
javaEE
操作系统
Redis
石可破也,而不可夺坚;丹可磨也,而不可夺赤。
init()
方法初始化这个对象,完成一些如加载配置文件、创建连接等初始化的工作,该方法只调用一次service()
方法对请求进行处理。destroy()
方法完成资源的释放,在destroy()
方法调用之后,容器会释放这个Servlet实例,该实例随后会被Java的垃圾收集器所回收@WebServlet("/demo")
public class ServletDemo implements Servlet {
/**
* 初始化方法
* 1.调用时机:默认情况下,Servlet被第一次访问时调用
* 2.调用次数:1次
* @param servletConfig
* @throws ServletException
*/
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("init...");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
/**
* 提供服务
* 1.调用时机:每次Servlet被访问时调用
* 2.调用次数:多次
* @param servletRequest
* @param servletResponse
* @throws ServletException
* @throws IOException
*/
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("hello service~");
}
@Override
public String getServletInfo() {
return null;
}
/**
* 销毁方法
* 1.调用时机:内存释放或服务器关闭时
* 2.调用次数:1次
*/
@Override
public void destroy() {
System.out.println("destroy...");
}
}
void init(ServletConfig servletConfig)
void service(ServletRequest servletRequest, ServletResponse servletResponse)
void destroy()
ServletConfig getServletConfig()
String getServletInfo()
@WebServlet("/demo")
public class ServletDemo implements Servlet {
private ServletConfig servletConfig;
/**
* 初始化方法
* 1.调用时机:默认情况下,Servlet被第一次访问时调用
* 2.调用次数:1次
* @param servletConfig
* @throws ServletException
*/
@Override
public void init(ServletConfig servletConfig) throws ServletException {
this.servletConfig = servletConfig;
System.out.println("init...");
}
@Override
public ServletConfig getServletConfig() {
return this.servletConfig;
}
/**
* 提供服务
* 1.调用时机:每次Servlet被访问时调用
* 2.调用次数:多次
* @param servletRequest
* @param servletResponse
* @throws ServletException
* @throws IOException
*/
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("hello service~");
}
@Override
public String getServletInfo() {
return "";
}
/**
* 销毁方法
* 1.调用时机:内存释放或服务器关闭时
* 2.调用次数:1次
*/
@Override
public void destroy() {
System.out.println("destroy...");
}
}
doGet
和doPost
方法:@WebServlet("/demo1")
public class ServletDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get...");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("post...");
}
}
doGet
方法:doPost
方法:DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>doPosttitle>
head>
<body>
<form action="/BBS/demo1" method="post">
<input name="username">
<input type="submit">
form>
body>
html>
String[] urlPatterns() default {};
@WebServlet(urlPatterns = {"/demo1","/demo2"})
@WebServlet(urlPatterns = "/user/select")
http://localhost:8080/BBS/user/select
@WebServlet(urlPatterns = "/user/*")
http://localhost:8080/BBS/user/aaa
(aaa可以使任意字符)@WebServlet(urlPatterns = "*.do")
注意:此处没有/
,这里的*表示任意以.do
的路径均可http://localhost:8080/BBS/demo1.do
@WebServlet(urlPatterns = "/")
或@WebServlet(urlPatterns = "/*")
后者优先级更高http://localhost:8080/BBS/
/
后可为任意内容/
和/*
的区别:"/”
,会覆盖掉tomcat中的DefaultServlet,当其他的url-patterni都匹配不上时都会走这个Servlet“*”
,意味着匹配任意访问路径<web-app>
<display-name>Archetype Created Web Applicationdisplay-name>
<servlet>
<servlet-name>demo2servlet-name>
<servlet-class>test.ServletDemo2servlet-class>
servlet>
<servlet-mapping>
<servlet-name>demo2servlet-name>
<url-pattern>/demo2url-pattern>
servlet-mapping>
web-app>
GET /request-demo/req1?username=zhangsan HTTP/1.1
String getMethod()
:获取请求方式:GETString getContextPath()
:获取虚拟目录(项目访问路径):/request-demoString Buffer getRequestURL()
:获取URL(统一资源定位符):http:/localhost:8080/request–demo/req1String getRequestURI()
:获取URI(统一资源标识符):/request-demo/req1String getQueryString()
:获取请求参数(GET方式):username=zhangsan&password=123@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//String getMethod()
String method = req.getMethod();
System.out.println(method);
//String getContextPath()
String contextPath = req.getContextPath();
System.out.println(contextPath);
//String Buffer getRequestURL()
StringBuffer requestURL = req.getRequestURL();
System.out.println(requestURL.toString());
//String getRequestURI()
String requestURI = req.getRequestURI();
System.out.println(requestURI);
//String getQueryString()
String queryString = req.getQueryString();
System.out.println(queryString);
}
User-Agent:Mozilla/5.0 Chrome/91.0.4472.106
String getHeader((String name);
根据请求头名称,获取值//user-agent:浏览器版本信息
String agent = req.getHeader("user-agent");
System.out.println(agent);
username=superbaby&password=123
ServletInputStream getInputStream();
获取字节输入流BufferedReader getReader();
获取字符输入流@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取字符输入流
BufferedReader reader = req.getReader();
//2.读取数据
String s = reader.readLine();
System.out.println(s);
}
Map
:获取所有参数Map集合
String[]getParameterValues(String name)
:根据名称获取参数值(数组)
String getParameter(String name)
:根据名称获取参数值(单个值)
get方式:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>doPosttitle>
head>
<body>
<form action="/BBS/demo5" method="get">
<input type="text" name="username"><br>
<input type="password" name="password"><br>
<input type="checkbox" name="hobby" value="1"> 游泳
<input type="checkbox" name="hobby" value="2"> 跑步 <br>
<input type="submit">
form>
body>
html>
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Get请求
System.out.println("get...");
//1.获取所有参数的Map集合
Map<String, String[]> parameterMap = req.getParameterMap();
for (String key : parameterMap.keySet()) {
System.out.print(key + ": ");
//获取值
String[] strings = parameterMap.get(key);
for (String string : strings) {
System.out.print(string + " ");
}
System.out.println();
}
System.out.println("----------------------");
//2.根据key获取值
String[] hobbies = req.getParameterValues("hobby");
for (String hobby : hobbies) {
System.out.println(hobby);
}
System.out.println("----------------------");
//3.获取单个参数
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username);
System.out.println(password);
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>doPosttitle>
head>
<body>
<form action="/BBS/demo5" method="post">
<input type="text" name="username"><br>
<input type="password" name="password"><br>
<input type="checkbox" name="hobby" value="1"> 游泳
<input type="checkbox" name="hobby" value="2"> 跑步 <br>
<input type="submit">
form>
body>
html>
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Post请求
System.out.println("get...");
//1.获取所有参数的Map集合
Map<String, String[]> parameterMap = req.getParameterMap();
for (String key : parameterMap.keySet()) {
System.out.print(key + ": ");
//获取值
String[] strings = parameterMap.get(key);
for (String string : strings) {
System.out.print(string + " ");
}
System.out.println();
}
System.out.println("----------------------");
//2.根据key获取值
String[] hobbies = req.getParameterValues("hobby");
for (String hobby : hobbies) {
System.out.println(hobby);
}
System.out.println("----------------------");
//3.获取单个参数
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username);
System.out.println(password);
}
@WebServlet("/demo5")
public class ServletDemo5 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Get请求
System.out.println("get...");
//1.获取所有参数的Map集合
Map<String, String[]> parameterMap = req.getParameterMap();
for (String key : parameterMap.keySet()) {
System.out.print(key + ": ");
//获取值
String[] strings = parameterMap.get(key);
for (String string : strings) {
System.out.print(string + " ");
}
System.out.println();
}
System.out.println("----------------------");
//2.根据key获取值
String[] hobbies = req.getParameterValues("hobby");
for (String hobby : hobbies) {
System.out.println(hobby);
}
System.out.println("----------------------");
//3.获取单个参数
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username);
System.out.println(password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码POST
//设置字符输入流的编码
req.setCharacterEncoding("utf-8");
//获取数据
String username = req.getParameter("username");
System.out.println(username);
}
getQueryString
%
+16进制数
的格式,然后将转换后的字符发送给服务器进行解码,tomcat在进行解码时是通过ISO-8859-1
的字符集进行URL解码,由于编码和解码时用的字符集不同,所以就会出现乱码。protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码GET
String username = req.getParameter("username");
//转换为字节数据,编码
byte[] bytes = username.getBytes(StandardCharsets.ISO_8859_1);
//将字节数组转换为字符串,解码
username = new String(bytes,"utf-8");
System.out.println(username);
}
req.getRequestDispatcher("资源B路径").forward(req,resp);
void setAttribute(String name,Object o)
:存储数据到request域中Object getAttribute(String name)
:根据key,获取值void removeAttribute(String name)
:根据key,删除该键值对@WebServlet("/demo7")
public class ServletDemo7 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("demo7...");
//存储数据
req.setAttribute("msg","hello");
//请求转发
req.getRequestDispatcher("/demo8").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
@WebServlet("/demo8")
public class ServletDemo8 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("demo8...");
//获取数据
Object msg = req.getAttribute("msg");
System.out.println(msg);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
void setStatus(int sc)
void setHeader(String name,String value)
PrintWriter getWriter();
ServletOutputStream getOutputStream();
@WebServlet("/resp1")
public class ResponseDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("resp1...");
//重定向
//设置响应状态码302
//resp.setStatus(302);
//设置响应头
//resp.setHeader("Location","/BBS/resp2");
//简化方式
resp.sendRedirect("/BBS/resp2");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
@WebServlet("/resp2")
public class ResponseDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("resp2...");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("resp1...");
//简化方式
//动态获取虚拟目录
String contextPath = req.getContextPath();
resp.sendRedirect(contextPath + "/resp2");
}
PrintWriter writer resp.getWriter();
writer.write("hello~");
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
resp.setHeader("content-type","text/html");
writer.write("hello~
");
writer.write("你好~
");
}
注意:
ISO-8859-1
ServletOutputStream outputStream resp.getOutputStream();
outputStream.write("字节数据");
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//读取文件
FileInputStream fis = new FileInputStream("d://head.jpg");
//获取response字节输出流
ServletOutputStream os = resp.getOutputStream();
//完成流的copy
byte[] buff = new byte[1024];
int len = 0;
while ((len = fis.read(buff)) != -1) {
os.write(buff,0,len);
}
fis.close();
}
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.6version>
dependency>
IOUtils.copy(fis,os);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//读取文件
FileInputStream fis = new FileInputStream("d://head.jpg");
//获取response字节输出流
ServletOutputStream os = resp.getOutputStream();
//完成流的copy
IOUtils.copy(fis,os);
fis.close();
}