1、Servlet原理

Servlet是由Web服务器调用的,web服务器在收到浏览器请求之后,

2、Mapping问题

  1. 一个Servlet可以指定一个映射路径
    1. <servlet-mapping>
    2. <servlet-name>hello</servlet-name>
    3. <url-pattern>/hello</url-pattern>
    4. </servlet-mapping>
  1. 一个Servlet可以指定多个映射路径

    1. <!--通过映射可以把多个不同的后缀映射到一个实现类上-->
    2. <servlet-mapping>
    3. <servlet-name>hello</servlet-name>
    4. <url-pattern>/hello2</url-pattern>
    5. </servlet-mapping>
    6. <servlet-mapping>
    7. <servlet-name>hello</servlet-name>
    8. <url-pattern>/hello3</url-pattern>
    9. </servlet-mapping>
  1. 一个Servlet可以指定通用映射路径
    1. <servlet-mapping>
    2. <servlet-name>hello</servlet-name>
    3. <url-pattern>/hello/*</url-pattern>
    4. </servlet-mapping>
  1. 默认请求路径(不推荐使用)
    1. <servlet-mapping>
    2. <servlet-name>hello</servlet-name>
    3. <url-pattern>/*</url-pattern>
    4. </servlet-mapping>
  1. 指定一些后缀或者前缀等等…
    1. <!--可以自定义后缀实现请求映射
    2. 注意点,*前面不能加项目映射的路径
    3. /hello/*.shuai (报错)
    4. -->
    5. <servlet-mapping>
    6. <servlet-name>hello</servlet-name>
    7. <url-pattern>*.shuai</url-pattern>
    8. </servlet-mapping>
  1. 优先级问题
    指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求

    1. <!--注册404页面-->
    2. <servlet>
    3. <servlet-name>error</servlet-name>
    4. <servlet-class>com.shuai.Servlet.ErrorServlet</servlet-class>
    5. </servlet>
    6. <servlet-mapping>
    7. <servlet-name>error</servlet-name>
    8. <url-pattern>/*</url-pattern>
    9. </servlet-mapping>

3、ServletContext

web容器在启动的时候,它会为每个web程序都创建一对应的ServletContext对象,他代表了当前的web应用;

1、共享数据

我在这个Servlet中保存的数据,可以在另外一个Servlet中拿到;
存数据:

  1. @Override
  2. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  3. // this.getInitParameter() 初始化参数
  4. // this.getServletConfig() Servlet配置
  5. // this.getServletContext() Servlet上下文
  6. ServletContext context = this.getServletContext();
  7. String username = "无敌最俊朗";
  8. context.setAttribute("username",username); // 将一个数据存在了ServletContext中,名字为:username,值为无敌最俊朗
  9. }
  10. @Override
  11. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  12. doGet(req,resp);
  13. }

获取数据:

  1. @Override
  2. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  3. ServletContext context = this.getServletContext();
  4. String username = (String) context.getAttribute("username");
  5. // 设置字符编码避免乱码
  6. resp.setContentType("text/html");
  7. resp.setCharacterEncoding("utf-8");
  8. resp.getWriter().print("名字:"+ username);
  9. }
  10. @Override
  11. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  12. super.doPost(req, resp);
  13. }

web.xml

  1. <servlet>
  2. <servlet-name>hello</servlet-name>
  3. <servlet-class>com.shuai.servlet.HelloServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>hello</servlet-name>
  7. <url-pattern>/hello</url-pattern>
  8. </servlet-mapping>
  9. <servlet>
  10. <servlet-name>getc</servlet-name>
  11. <servlet-class>com.shuai.servlet.GetServlet</servlet-class>
  12. </servlet>
  13. <servlet-mapping>
  14. <servlet-name>getc</servlet-name>
  15. <url-pattern>/getc</url-pattern>
  16. </servlet-mapping>

2、获取初始化参数

  1. // ServletDemo3.java
  2. @Override
  3. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  4. ServletContext context = this.getServletContext();
  5. String url = context.getInitParameter("url");
  6. resp.getWriter().print(url);
  7. }
  8. @Override
  9. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  10. super.doPost(req,resp);
  11. }

web.xml

  1. <!--配置一些web应用初始化参数-->
  2. <context-param>
  3. <param-name>url</param-name>
  4. <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
  5. </context-param>

3.请求转发

  1. // ServletDemo4.java
  2. @Override
  3. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  4. ServletContext context = this.getServletContext();
  5. // RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp"); // 转发的请求路径
  6. // requestDispatcher.forward(req,resp); // 转发forward实现请求转发
  7. context.getRequestDispatcher("/gp").forward(req,resp);
  8. }
  9. @Override
  10. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  11. super.doPost(req, resp);
  12. }

web.xml

  1. <servlet>
  2. <servlet-name>sd4</servlet-name>
  3. <servlet-class>com.shuai.servlet.ServletDemo4</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>sd4</servlet-name>
  7. <url-pattern>/sd4</url-pattern>
  8. </servlet-mapping>

4、读取资源文件

Properties

  • 在java目录下新建properties
  • 在resources目录下新建properties

发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath:

思路:需要一个文件流

  1. username = root
  2. password = dfafafaf
  1. @Override
  2. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  3. InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/shuai/servlet/aa.properties");
  4. Properties prop = new Properties();
  5. prop.load(is);
  6. String user = prop.getProperty("username");
  7. String pwd = prop.getProperty("password");
  8. resp.getWriter().print(user + ":" + pwd);
  9. }
  10. @Override
  11. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  12. super.doPost(req, resp);
  13. }

4、HttpServletReaponse

web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletResquest对象,代表响应的一个HttpServletReaponse;

  • 如果要获取客户端请求过来的参数:找HttpServletResquest
  • 如果要给客户端响应一些信息:找HttpServletReaponse

1、简单分类

负责向浏览器发送数据的方法

  1. ServletOutputStream getOutputStream() throws IOException;
  2. PrintWriter getWriter() throws IOException;

负责向浏览器发送响应头的方法

  1. void sendError(int var1, String var2) throws IOException;
  2. void sendError(int var1) throws IOException;
  3. void sendRedirect(String var1) throws IOException;
  4. void setDateHeader(String var1, long var2);
  5. void addDateHeader(String var1, long var2);
  6. void setHeader(String var1, String var2);
  7. void addHeader(String var1, String var2);
  8. void setIntHeader(String var1, int var2);
  9. void addIntHeader(String var1, int var2);
  10. void setStatus(int var1);

2、下载文件

  1. @Override
  2. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  3. /*
  4. * 前四个是字符串操作
  5. * 后四个是IO操作*/
  6. // 解决乱码问题
  7. req.setCharacterEncoding("utf-8");
  8. resp.setCharacterEncoding("utf-8");
  9. resp.setContentType("text/html;charset=utf-8");
  10. // 1. 要获取下载文件的路径
  11. // String realPath = this.getServletContext().getRealPath("\1.jpg");
  12. String realPath = "G:\\JavaProjects\\javaweb-servlet-02\\Response\\target\\classes\\1.jpg";
  13. System.out.println("下载的文件路径:"+ realPath);
  14. // 2. 下载的文件名是啥?
  15. String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
  16. // String fileName = "1.jpg";
  17. // 3.设置想办法让浏览器能够支持 下载我们需要的东西
  18. resp.setHeader("Content-Disposition","attachment:filename"+ URLEncoder.encode(fileName,"UTF-8"));
  19. // 4.获取下载文件的输入流
  20. FileInputStream in = new FileInputStream(realPath); // 把文件变成流就能用了
  21. // 5.创减缓冲区
  22. int len = 0;
  23. byte[] buffer = new byte[1024];
  24. // 6.获取OutputStream对象
  25. ServletOutputStream out = resp.getOutputStream();
  26. // 7.将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端!
  27. while ((len=in.read(buffer))>0){
  28. out.write(buffer,0,len); // 把流写入缓冲区长度从0到len
  29. }
  30. in.close();
  31. out.close();
  32. }
  33. @Override
  34. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  35. doGet(req, resp);
  36. }

3、实现重定向

B一个web资源收到客户端A请求后,B它会通知A客户端去访问另外一个web资源C,这个过程叫做重定向

常见场景:

  • 用户登录
  1. void sendRedirect(String var1) throws IOException;

测试:

  1. @Override
  2. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  3. // resp.sendRedirect("/r/file"); // 重定向
  4. ServletContext context = this.getServletContext();
  5. context.getRequestDispatcher("/file").forward(req,resp);
  6. }
  7. @Override
  8. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  9. doGet(req, resp);
  10. }

面试题:请你聊聊重定向和转发的区别?

相同点:

  • 页面都会跳转

不同点

  • 请求转发的时候,url不会产生变化;
  • 重定向的时候,url地址栏会发生变化;

5、HttpServletResquest

1、获取参数,请求转发

  1. @Override
  2. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  3. // 防止请求和响应乱码
  4. req.setCharacterEncoding("utf-8");
  5. resp.setCharacterEncoding("utf-8");
  6. resp.setContentType("text/html;charset=utf-8");
  7. // 处理请求(得到前端的参数)
  8. String username = req.getParameter("username");
  9. String password = req.getParameter("password");
  10. String[] hobbys = req.getParameterValues("hobbys"); // 得到数组
  11. System.out.println("==================");
  12. System.out.println(username);
  13. System.out.println(password);
  14. System.out.println(Arrays.toString(hobbys));
  15. System.out.println("==================");
  16. System.out.println(req.getContextPath()); // /r
  17. // 通过请求转发
  18. // 这里的/代表当前的web项目
  19. req.getRequestDispatcher("/success.jsp").forward(req,resp);
  20. }
  21. @Override
  22. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  23. doGet(req, resp);
  24. }