ServletContext
web容器在启动的时候,它会为每一个web程序创建一个对应的ServletContext对象,它代表了当前的web应用;
1、共享数据
我在这个Servlet中保存的数据,可以在另外一个servlet中拿到;
1 package com.kuang.servlet; 2 3 import javax.servlet.ServletContext; 4 import javax.servlet.ServletException; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import java.io.IOException; 9 10 public class HelloServlet extends HttpServlet { 11 @Override 12 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 13 14 //this.getInitParameter() 初始化参数 15 //this.getServletConfig() Servlet配置 16 //this.getServletContext() Servlet上下文 17 ServletContext context = this.getServletContext(); 18 19 String username = "王刘"; //数据 20 context.setAttribute("username",username); //将一个数据保存在了ServletContext中,名字为:username,值username 21 22 23 } 24 25 @Override 26 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 27 doGet(req, resp); 28 } 29 }
获取数据:
1 package com.kuang.servlet; 2 3 import javax.servlet.ServletContext; 4 import javax.servlet.ServletException; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import java.io.IOException; 9 10 public class GetServlet extends HttpServlet { 11 @Override 12 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 13 ServletContext context = this.getServletContext(); 14 String username = (String) context.getAttribute("username"); 15 16 resp.setContentType("text/html"); 17 resp.setCharacterEncoding("utf-8"); 18 resp.getWriter().print("名字:"+username); 19 } 20 21 @Override 22 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 23 doGet(req, resp); 24 } 25 }
注册:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 5 http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 6 version="4.0" 7 metadata-complete="true"> 8 9 <servlet> 10 <servlet-name>hello</servlet-name> 11 <servlet-class>com.kuang.servlet.HelloServlet</servlet-class> 12 </servlet> 13 <servlet-mapping> 14 <servlet-name>hello</servlet-name> 15 <url-pattern>/hello</url-pattern> 16 </servlet-mapping> 17 18 <servlet> 19 <servlet-name>getc</servlet-name> 20 <servlet-class>com.kuang.servlet.GetServlet</servlet-class> 21 </servlet> 22 <servlet-mapping> 23 <servlet-name>getc</servlet-name> 24 <url-pattern>/getc</url-pattern> 25 </servlet-mapping> 26 27 28 </web-app>
2、获取初始化参数
1 <!--配置一些web应用初始化参数--> 2 <context-param> 3 <param-name>url</param-name> 4 <param-value>jdbc:mysql://localhost:3306/mybatis</param-value> 5 </context-param>
1 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 2 ServletContext context = this.getServletContext(); 3 String url = context.getInitParameter("url"); 4 resp.getWriter().print(url); 5 }
3、请求转发

1 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 2 ServletContext context = this.getServletContext(); 3 System.out.println("进入了ServletDemo04"); 4 //RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp"); //转发的请求路劲 5 //requestDispatcher.forward(req,resp); //调用forward实现请求转发; 6 context.getRequestDispatcher("/gp").forward(req,resp); 7 }
4、读取资源文件
Properties
- 在java目录下新建properties
- 在resources目录下新建properties
发现:都被打包到了同一个路劲下:classes,我们俗称这个路劲为classpath:
思路:需要一个文件流;
db.properties
username=root
password=123456
1 public class ServletDemo05 extends HttpServlet { 2 @Override 3 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 4 InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties"); 5 Properties prop = new Properties(); 6 prop.load(is); 7 String user = prop.getProperty("username"); 8 String pwd = prop.getProperty("password"); 9 10 resp.getWriter().print(user + ":" + pwd); 11 } 12 13 @Override 14 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 15 doGet(req, resp); 16 } 17 }
访问测试即可;
6.6、HttpServletResponse
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest
对象,代表响应的一个HttpServletResponse;
- 如果要获取客户端请求过来的参数:找HttpServletRequest
- 如果要给客户端响应一些信息:找HttpServletResponse
1、简单分类
负责向浏览器发送数据的方法
1 ServletOutputStream getOutputStream() throws IOException;2 PrintWriter getWriter() throws IOException;
负责向浏览器发送响应头的方法
1 void setCharacterEncoding(String var1); 2 3 void setContentLength(int var1); 4 5 void setContentLengthLong(long var1); 6 7 void setContentType(String var1);
1 void setDateHeader(String var1, long var2); 2 3 void addDateHeader(String var1, long var2); 4 5 void setHeader(String var1, String var2); 6 7 void addHeader(String var1, String var2); 8 9 void setIntHeader(String var1, int var2); 10 11 void addIntHeader(String var1, int var2);
响应的状态
1 int SC_CONTINUE = 100; 2 int SC_SWITCHING_PROTOCOLS = 101; 3 int SC_OK = 200; 4 int SC_CREATED = 201; 5 int SC_ACCEPTED = 202; 6 int SC_NON_AUTHORITATIVE_INFORMATION = 203; 7 int SC_NO_CONTENT = 204; 8 int SC_RESET_CONTENT = 205; 9 int SC_PARTIAL_CONTENT = 206; 10 int SC_MULTIPLE_CHOICES = 300; 11 int SC_MOVED_PERMANENTLY = 301; 12 int SC_MOVED_TEMPORARILY = 302; 13 int SC_FOUND = 302; 14 int SC_SEE_OTHER = 303; 15 int SC_NOT_MODIFIED = 304; 16 int SC_USE_PROXY = 305; 17 int SC_TEMPORARY_REDIRECT = 307; 18 int SC_BAD_REQUEST = 400; 19 int SC_UNAUTHORIZED = 401; 20 int SC_PAYMENT_REQUIRED = 402; 21 int SC_FORBIDDEN = 403; 22 int SC_NOT_FOUND = 404; 23 int SC_METHOD_NOT_ALLOWED = 405; 24 int SC_NOT_ACCEPTABLE = 406; 25 int SC_PROXY_AUTHENTICATION_REQUIRED = 407; 26 int SC_REQUEST_TIMEOUT = 408; 27 int SC_CONFLICT = 409; 28 int SC_GONE = 410; 29 int SC_LENGTH_REQUIRED = 411; 30 int SC_PRECONDITION_FAILED = 412; 31 int SC_REQUEST_ENTITY_TOO_LARGE = 413; 32 int SC_REQUEST_URI_TOO_LONG = 414; 33 int SC_UNSUPPORTED_MEDIA_TYPE = 415; 34 int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; 35 int SC_EXPECTATION_FAILED = 417; 36 int SC_INTERNAL_SERVER_ERROR = 500; 37 int SC_NOT_IMPLEMENTED = 501; 38 int SC_BAD_GATEWAY = 502; 39 int SC_SERVICE_UNAVAILABLE = 503; 40 int SC_GATEWAY_TIMEOUT = 504; 41 int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
2、常见应用
1.向浏览器输出消息
2.下载文件
- 要获取下载文件的路径
- 下载文件名是啥?
- 设置想办法让浏览器能够支持下载我们需要的东西
- 获取下载文件的输入流
- 创建缓冲区
- 获取OutputStream对象
- 将FileOutputStream流写入到buffer缓冲区
- 使用OutputStream将缓冲区中的数据输出到客户端!
1 public class FileServlet extends HttpServlet { 2 @Override 3 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 4 5 // 要获取下载文件的路径 6 String realPath = "F:\\develop\\workspace\\JavaWeb\\javaweb-02-servlet\\response\\target\\classes\\王刘.jpg"; 7 System.out.println("下载文件的路径:"+realPath); 8 // 下载文件名是啥? 9 String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1); 10 // 设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名URLEncoder.encode进行编码,否则有可能乱码 11 resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8")); 12 // 获取下载文件的输入流 13 FileInputStream in = new FileInputStream(realPath); 14 // 创建缓冲区 15 int len = 0; 16 byte[] buffer = new byte[1024]; 17 // 获取OutputStream对象 18 ServletOutputStream out= resp.getOutputStream(); 19 // 将FileOutputStream流写入到buffer缓冲区.使用OutputStream将缓冲区中的数据输出到客户端! 20 while ((in.read(buffer))!=-1) { 21 out.write(buffer,0,len); 22 } 23 24 in.close(); 25 out.close(); 26 }
3、验证码的功能
验证码怎么来的?
- 前端实现
- 后端实现,需要用到java的图片类,生成一个图片
1 public class ImageServlet extends HttpServlet { 2 @Override 3 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 4 5 //如何让浏览器5秒自动刷新一次; 6 resp.setHeader("refresh","3"); 7 8 //在内存中创建一个图片 9 BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB); 10 //得到图片 11 Graphics2D g = (Graphics2D) image.getGraphics(); //笔 12 //设置图片的背景颜色 13 g.setColor(Color.WHITE); 14 g.fillRect(0,0,80,20); 15 //给图片写数据 16 g.setColor(Color.blue); 17 g.setFont(new Font(null, Font.BOLD,20)); 18 g.drawString(makeNum(),0,20); 19 20 //告诉浏览器这个请求用图片的方式打开 21 resp.setContentType("image/jpg"); 22 //网站存在缓存,不让浏览器缓存 23 resp.setDateHeader("expires", -1); 24 resp.setHeader("Cache-Control","no-cache"); 25 resp.setHeader("Pragma","no-cache"); 26 27 //把图片写给浏览器 28 boolean write = ImageIO.write(image,"jpg", resp.getOutputStream()); 29 } 30 31 //生成随机数 32 private String makeNum(){ 33 Random random = new Random(); 34 String num = random.nextInt(9999999) + ""; 35 StringBuffer sb = new StringBuffer(); 36 for (int i = 0; i < 7-num.length(); i++) { 37 sb.append("0"); 38 } 39 num = sb.toString() + num; 40 return num; 41 } 42 43 @Override 44 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 45 doGet(req, resp); 46 } 47 }
4、实现重定向

B一个web资源收到客户端请求后,B他会通知A客户端去访问另外一个web资源C,这个过程叫重定向
常见场景:
- 用户登录
1 void sendRedirect(String var1) throws IOException;
测试
1 public class RedirectServlet extends HttpServlet { 2 @Override 3 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 4 resp.sendRedirect("/r/img"); //重定向 5 6 }
面试提:请你聊聊重定向和转发的区别?
相同点
- 页面都会跳转
不同点
- 请求转发的时候,url不会产生变化
- 重定向的时候,url地址栏会发生变化;
1 public class RequestTest extends HttpServlet { 2 @Override 3 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 4 //处理请求 5 String username = req.getParameter("username"); 6 String password = req.getParameter("password"); 7 8 System.out.println(username+":"+password); 9 10 //重定向的时候一定要注意,路径问题,否则404; 11 resp.sendRedirect("/r/success.jsp"); 12 } 13 14 @Override 15 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 16 doGet(req, resp); 17 } 18 }
1 <html> 2 <body> 3 <h2>Hello World!</h2> 4 5 <%--这里提交的路径,需要寻找到项目的路径--%> 6 <%--${pageContext.request.contextPath}代表当前的项目--%> 7 <form action="${pageContext.request.contextPath}/login" method="get"> 8 用户名:<input type="text" name="username"> <br> 9 密码:<input type="password" name="password"> <br> 10 <input type="submit" value="提交"> 11 </form> 12 13 </body> 14 </html>
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 8 <h1>Success</h1> 9 10 </body> 11 </html>
6.7、HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest,获取客户端的所有信息
1、获取参数,请求转发
1 public class LoginServlet extends HttpServlet { 2 @Override 3 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 4 req.setCharacterEncoding("utf-8"); 5 resp.setCharacterEncoding("utf-8"); 6 String username = req.getParameter("username"); 7 String password = req.getParameter("password"); 8 String[] hobbys = req.getParameterValues("hobbys"); 9 System.out.println("================================"); 10 //后台接收中文乱码问题 11 System.out.println("username"); 12 System.out.println("password"); 13 System.out.println(Arrays.toString(hobbys)); 14 System.out.println("================================"); 15 16 System.out.println(req.getContextPath()); 17 //通过请求转发 18 //这里的/代表当前的web应用 19 req.getRequestDispatcher("/success.jsp").forward(req,resp); 20 21 } 22 23 @Override 24 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 25 doGet(req, resp); 26 } 27 }
面试提:请你聊聊重定向和转发的区别?
相同点
- 页面都会跳转
不同点
- 请求转发的时候,url不会产生变化;307
- 重定向的时候,url地址栏会发生变化;302


浙公网安备 33010602011771号