2021年3月17日星期三

050_Servlet详解

目录
  • Servlet
    • Servlet简介
    • HelloServlet
    • Servlet原理
    • servlet-mapping Servlet请求路径
    • ServletContext Servlet上下文
      • ServletContext的应用
        • 共享数据:在一个Servlet设置的数据,可以在另一个Servlet获取到
        • 获取初始化参数
        • 请求转发
        • 读取Properties文件
    • HttpServletResponse
      • 下载文件
      • 验证码功能
      • 重定向
    • 重定向和转发的区别
    • 登录demo
    • HttpServletRequest
      • 获取浏览器传递的参数
      • 请求转发


Servlet

package com.qing.servlet;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter;public class HelloServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  doGet(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {  //响应的类型:html  response.setContentType("text/html");  //响应的编码  response.setCharacterEncoding("utf-8");  //获取响应的输出流  PrintWriter out = response.getWriter();  out.println("<html>");  out.println("<head>");  out.println("<title>Hello World!</title>");  out.println("</head>");  out.println("<body>");  out.println("<h1>Hello World!</h1>");  out.println("</body>");  out.println("</html>"); }}
<?

Servlet简介

  1. Servlet是sun公司开发动态web的一门技术
  2. sun公司在这些API中提供一个接口:Servlet,如果想开发一个Servlet程序,只需要完成两个步骤
    1. 编写一个类,实现Servlet接口
    2. 把开发好的java类部署到web服务器中
  3. 我们把实现了Servlet接口的java程序叫做Servlet
  4. Servlet接口sun公司有两个默认的实现类:HttpServlet和GenericServlet

HelloServlet

  1. 构建一个普通maven项目,删掉src目录,这个空的工程就是Maven主工程,可以在里面建立Module;

image.png
image.png

  1. 配置pom.
<?
  1. 在父工程中新建子模块Module;

image.png
image.png
image.png

  1. 关于父子工程的理解:父项目中的jar包子项目可以直接使用;
    1. 父项目中会有
    2. 子项目中会有
 <modules>  <module>servlet-01</module> </modules>
 <parent>  <artifactId>javaweb-03-servlet</artifactId>  <groupId>com.qing</groupId>  <version>1.0-SNAPSHOT</version> </parent>

image.png

  1. Maven环境优化:
    1. 修改web.
    2. 将maven的结构搭建完整:子工程添加java和resources目录;
<?

image.png

  1. 编写一个Servlet程序;
    1. 编写一个普通类
    2. 实现Servlet接口,这里继承HttpServlet

image.png

package com.qing.servlet;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter;public class HelloServlet extends HttpServlet { //由于get或者post只是请求实现的不同方式,可以相互调用,业务逻辑都一样 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  System.out.println("进入doGet方法");  PrintWriter writer = resp.getWriter();//响应流  writer.print("hello,servlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  doGet(req, resp); }}
  1. 在web.

为什么需要映射?
我们写的是Java程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务中注册我们写的Servlet,还需要给他一个浏览器可以访问的路径

<?
  1. 配置Tomcat

image.png

  1. 启动测试

image.png

Servlet原理

Servlet是由web服务器调用,web服务器收到浏览器请求后,会:
image.png

servlet-mapping Servlet请求路径

  1. 一个Servlet指定一个映射路径
 <servlet-mapping>  <servlet-name>helloServlet</servlet-name>  <url-pattern>/hello</url-pattern> </servlet-mapping>
  1. 一个Servlet指定多个映射路径
 <servlet-mapping>  <servlet-name>helloServlet</servlet-name>  <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet-mapping>  <servlet-name>helloServlet</servlet-name>  <url-pattern>/hello1</url-pattern> </servlet-mapping>
  1. 一个Servlet指定通用映射路径
 <servlet-mapping>  <servlet-name>helloServlet</servlet-name>  <url-pattern>/hello/*</url-pattern> </servlet-mapping>
  1. 默认请求路径,会跳过index.jsp,直接进Servlet
 <servlet-mapping>  <servlet-name>helloServlet</servlet-name>  <url-pattern>/*</url-pattern> </servlet-mapping>
  1. 指定后缀
<!--可以自定义后缀实现请求映射,注意:*前面不能加任何字符,否则会报错--><servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>*.qing</url-pattern></servlet-mapping>
  1. 优先级问题:指定固定映射路径优先级最高,如果找不到就会走默认请求路径
<!--404--><servlet> <servlet-name>error</servlet-name> <servlet-class>com.qing.servlet.ErrorServlet</servlet-class></servlet><servlet-mapping> <servlet-name>error</servlet-name> <url-pattern>/*</url-pattern></servlet-mapping>

ServletContext Servlet上下文

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

ServletContext的应用

image.png

共享数据:在一个Servlet设置的数据,可以在另一个Servlet获取到

package com.qing.servlet;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  System.out.println("hello");  //Servlet上下文  ServletContext context = this.getServletContext();  //设置数据  String username = "清风";  context.setAttribute("username", username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  doGet(req, resp); }}
package com.qing.servlet;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class GetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  System.out.println("get");  ServletContext context = this.getServletContext();  String username = (String) context.getAttribute("username");  System.out.println(username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  doGet(req, resp); }}
<?

获取初始化参数

<?
package com.qing.servlet;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class GetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  System.out.println("get");  ServletContext context = this.getServletContext();  String url = context.getInitParameter("url");  resp.getWriter().println(url); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  doGet(req, resp); }}

请求转发

package com.qing.servlet;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class GetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  System.out.println("get");  ServletContext context = this.getServletContext();  //转发到/hello  context.getRequestDispatcher("/hello").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  doGet(req, resp); }}

读取Properties文件

username=rootpassword=123456
package com.qing.servlet;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.InputStream;import java.util.Properties;public class PropertiesServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  //获取流,根路径为打包后target下的项目名称  InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");  Properties properties = new Properties();  properties.load(in);  String user = properties.getProperty("username");  String pwd = properties.getProperty("password");  resp.getWriter().print(user + ":" + pwd); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  doGet(req, resp); }}
<?

HttpServletResponse

  • web服务器接收到浏览器的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象和一个代表响应的HttpServletResponse对象
    • 如果要获取浏览器请求过来的参数:找HttpServletRequest
    • 如果要给浏览器响应一下信息:找HttpServletResponse
  • 简单分类
    • 负责向浏览器发送数据的方法
ServletOutputStream getOutputStream() throws IOException;PrintWriter getWriter() throws IOException;
  • 负责向浏览器发送响应头的方法
void setCharacterEncoding(String var1);void setContentLength(int var1);
  • 响应的状态码
int SC_OK = 200;int SC_CREATED = 201;
  • 常见应用
    • 向浏览器输出消息

下载文件

 - 获取下载文件的路径 - 获取文件名 - 设置浏览器支持下载  - 文件下载的消息头和编码问题 [https://www.cnblogs.com/hackxiyu/p/9046247.html](https://www.cnblogs.com/hackxiyu/p/9046247.html)
response.setHeader("Content-Disposition", "attachment;filename="+new String(AREA_FILE.getBytes("gb2312"), "ISO-8859-1"));
 - 获取下载文件的输入流 - 创建缓冲区 - 获取OutputStream对象 - 将输入流写入buffer缓冲区,使用输出流将缓冲区中的数据输出到客户端
package com.qing.servlet;import javax.servlet.ServletException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.FileInputStream;import java.io.IOException;import java.net.URLEncoder;public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  //获取下载文件的路径  String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/静.jpg");  System.out.println("下载文件的路径为:" + realPath);  //获取文件名  String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);  System.out.println("文件名为:" + fileName);  //设置浏览器支持下载  resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));  //获取下载文件的输入流  FileInputStream fileInputStream = new FileInputStream(realPath);  //创建缓冲区  int len = 0;  byte[] buffer = new byte[1024];  //获取OutputStream对象  ServletOutputStream outputStream = resp.getOutputStream();  //将输入流写入buffer缓冲区,使用输出流将缓冲区中的数据输出到客户端  while ((len=fileInputStream.read(buffer)) != -1) {   outputStream.write(buffer, 0, len);  }  fileInputStream.close();  outputStream.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  doGet(req, resp); }}
<?

验证码功能

package com.qing.servlet;import javax.imageio.ImageIO;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.awt.*;import java.awt.image.BufferedImage;import java.io.IOException;import java.util.Random;public class ImageServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  //设置浏览器3秒自动刷新一次  resp.setHeader("refresh", "3");  //在内存中创建一个图片  BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);  //得到画笔  Graphics2D g = (Graphics2D) image.getGraphics();  //设置画笔颜色,画矩形背景  g.setColor(Color.WHITE);  g.fillRect(0,0,80,20);  //设置画笔颜色和字体,画随机数  g.setColor(Color.BLUE);  g.setFont(new Font(null,Font.BOLD,20));  g.drawString(makeRandom(),0,20);  //告诉浏览器,这个请求用图片的方式打开  resp.setContentType("image/jpeg");  //网站存在缓存,不让浏览器缓存  resp.setDateHeader("expires",-1);  resp.setHeader("Cache-Control","no-cache");  resp.setHeader("Pragma","no-cache");  //把图片写给浏览器  ImageIO.write(image,"jpg",resp.getOutputStream()); } //生产随机数 private String makeRandom() {  Random random = new Random();  String num = random.nextInt(9999999) + "";  StringBuilder sb = new StringBuilder();  for (int i = 0; i < 7 - num.length(); i++) {   sb.append(0);  }  num = sb.toString() + num;  return num; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  doGet(req, resp); }}
<?

重定向

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

image.png
常见场景:用户登录

package com.qing.servlet;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class RedirectServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  /*  重定向相当于  resp.setHeader("Location","/resp/image");  resp.setStatus(302);   */  //重定向  resp.sendRedirect("/resp/image"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  doGet(req, resp); }}
<?

重定向和转发的区别

  • 相同点
    • 页面都会实现跳转
  • 不同点
    • 请求转发的时候,URL不会发生变化 状态码:307
    • 重定向的时候,URL会发生变化 状态码:302

登录demo

  1. pom.
<?
  1. 编辑登录页,${pageContext.request.contextPath}代表当前项目
<html><body><h2>Hello World!</h2><%--这里提交的路径,需要寻找到项目的路径--%><%--${pageContext.request.contextPath}代表当前项目--%><form action="${pageContext.request.contextPath}/login" method="get"> 用户名:<input type="text" name="username"> 密码:<input type="password" name="password"> <input type="submit"></form></body></html>
  1. 编辑登录成功页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head> <title>Success</title></head><body><h1>Success</h1></body></html>
  1. 处理登录请求,重定向到成功页面
package com.qing.servlet;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  System.out.println("进入登录请求");  String username = req.getParameter("username");  String password = req.getParameter("password");  System.out.println(username + ":" + password);  //重定向  resp.sendRedirect("/resp/success.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  doGet(req, resp); }}
  1. 在web.
<?

HttpServletRequest

HttpServletRequest代表客户端的请求,用户通过http协议访问服务器,http请求中的所有信息都会被封装到HttpServletRequest,通过HttpServletRequest的方法,可以获得客户端的所有信息。

获取浏览器传递的参数

String contextPath = req.getContextPath();//项目路径String servletPath = req.getServletPath();//Servlet路径String requestURI = req.getRequestURI();//请求路径String name = req.getParameter("name");String[] names = req.getParameterValues("name");

请求转发

//请求转发//这里的/代表当前的web应用,即contextPathreq.getRequestDispatcher("/success.jsp").forward(req,resp);








原文转载:http://www.shaoqun.com/a/632669.html

跨境电商:https://www.ikjzd.com/

五洲会:https://www.ikjzd.com/w/1068

薇美铺:https://www.ikjzd.com/w/2312


目录ServletServlet简介HelloServletServlet原理servlet-mappingServlet请求路径ServletContextServlet上下文ServletContext的应用共享数据:在一个Servlet设置的数据,可以在另一个Servlet获取到获取初始化参数请求转发读取Properties文件HttpServletResponse下载文件验证码功能重定向重
贝贝母婴网:https://www.ikjzd.com/w/1321
韩蓬:https://www.ikjzd.com/w/1635
imgur:https://www.ikjzd.com/w/156
口述:上司诱我上床还怪我非处女上司非处女办公室:http://lady.shaoqun.com/m/a/42299.html
关于新注册账号和二审,这几条注意事项请收藏:https://www.ikjzd.com/home/114387
2019年的亚马逊,新卖家还有机会吗?:https://www.ikjzd.com/home/21697

没有评论:

发表评论