Servlet学习

Servlet简介

Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,具有独立于平台和协议的特性,主要功能在于交互式地浏览和生成数据,生成动态Web内容。

狭义的Servlet是指Java语言实现的一个接口,广义的Servlet是指任何实现了这个Servlet接口的类,一般情况下,人们将Servlet理解为后者。Servlet运行于支持Java的应用服务器中。从原理上讲,Servlet可以响应任何类型的请求,但绝大多数情况下Servlet只用来扩展基于HTTP协议的Web服务器。

Servlet接口实现类

  1. HttpServlet
  2. GenericServlet

图解Servlet接口、HttpServlet、GenericServlet三者关系
Servlet学习_第1张图片

编写一个Servlet程序,在网页上输出:你好呀,世界
1. 优化web.xml(选做,项目中自带的版本低)
//将项目中自带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"
      metadata-complete="true">
web-app>
2. 编写普通类,继承HttpServlet,从写doGet(),doPost()方法
public class HelloWeb extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print("你好呀,世界");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

3. 在web.xml中编写映射路径

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


<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"
metadata-complete="true">
//注册Servlet
<servlet>
    <servlet-name>helloservlet-name>
    <servlet-class>com.practice.javaweb01.HelloWebservlet-class>
servlet>
//配置Servlet请求路径
<servlet-mapping>
    <servlet-name>helloservlet-name>
    <url-pattern>/hellourl-pattern>
servlet-mapping>
web-app>
4. 配置Tomcat

Mapping问题

Servlet请求路径种类

  1. 一个Servlet拥有单个请求路径
<servlet>
    <servlet-name>helloservlet-name>
    <servlet-class>com.practice.javaweb01.HelloWebservlet-class>
servlet>
<servlet-mapping>
    <servlet-name>helloservlet-name>
    <url-pattern>/hellourl-pattern>
servlet-mapping>

即在:在 ->http://localhost:8080/<-后输入hello,便可以进入“你好呀,世界”页面

  1. 一个Servlet拥有多个请求路径
<servlet>
    <servlet-name>helloservlet-name>
    <servlet-class>com.practice.javaweb01.HelloWebservlet-class>
servlet>
<servlet-mapping>
    <servlet-name>helloservlet-name>
    <url-pattern>/hellourl-pattern>
servlet-mapping>
<servlet-mapping>
	<servlet-name>helloservlet-name>
	<url-pattern>/turl-pattern>
servlet-mapping>
<servlet-mapping>
	<servlet-name>helloservlet-name>
	<url-pattern>/surl-pattern>
servlet-mapping>

即在:在 ->http://localhost:8080/<-后输入hello、t、s,便可以进入“你好呀,世界”页面

  1. 一个Servlet拥有通用请求路径
<servlet>
    <servlet-name>helloservlet-name>
    <servlet-class>com.practice.javaweb01.HelloWebservlet-class>
servlet>
<servlet-mapping>
    <servlet-name>helloservlet-name>
    <url-pattern>/hello/*url-pattern>
servlet-mapping>
  1. 默认请求路径
<servlet>
    <servlet-name>helloservlet-name>
    <servlet-class>com.practice.javaweb01.HelloWebservlet-class>
servlet>
<servlet-mapping>
    <servlet-name>helloservlet-name>
    <url-pattern>/*url-pattern>
servlet-mapping>

注意,这种情况下Web服务器会直接响应“你好呀,世界”,这个页面

  1. 自定义后缀,请求路径
<servlet>
    <servlet-name>helloservlet-name>
    <servlet-class>com.practice.javaweb01.HelloWebservlet-class>
servlet>
<servlet-mapping>
    <servlet-name>helloservlet-name>
    <url-pattern>*.dourl-pattern>
servlet-mapping>

即在:在 ->http://localhost:8080/<-后输入以“.do”为后缀的数据,便可以进入“你好呀,世界”页面

Servlet请求路径优先级

已经指定的(确定的)Mapping映射路径优先级最高,若找不到映射页面,则走默认的Mapping映射路径

ServletContext

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

ServletContext应用

1.共享数据

即在一个Servlet中保存的数据,在另外一个servlet中拿到数据

 ServletContext context = this.getServletContext(); //获取context对象
 context.setAttribute("username","张三丰");  //向context中存放数据
 String username = (String) context.getAttribute("username"); //获取context中的数据

具体实现类

  1. xml配置
//保存数据请求路径配置
    <servlet>
        <servlet-name>saveservlet-name>
        <servlet-class>com.practice.javaweb02.Contextservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>saveservlet-name>
        <url-pattern>/saveurl-pattern>
    servlet-mapping>
////获取数据请求路径配置
    <servlet>
        <servlet-name>getsaveservlet-name>
        <servlet-class>com.practice.javaweb02.getContextservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>getsaveservlet-name>
        <url-pattern>/getsaveurl-pattern>
    servlet-mapping>
  1. 保存数据类
public class Context extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        context.setAttribute("username","张三丰");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
  1. 获取数据类
public class getContext extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String username = (String) context.getAttribute("username");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print("姓名:"+username);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

注意:应先保存数据后,在获取数据,否则数据为空

2.获取context初始化参数
  • 使用getInitParameter()方法
  1. xml配置
 <context-param>
        <param-name>urlparam-name>
        <param-value>jdbc:mysql//mysql:3306param-value>
 context-param>
  1. 实现类
public class init extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String url = context.getInitParameter("url");
        resp.getWriter().print("url:"+url);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
3.请求、转换
  • 使用: getRequestDispatcher()、forward( )方法
  1. xml配置
    <servlet>
        <servlet-name>disservlet-name>
        <servlet-class>com.practice.javaweb02.Dispservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>disservlet-name>
        <url-pattern>/dispathurl-pattern>
    servlet-mapping>
  1. 实现类
public class Disp extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        context.getRequestDispatcher("/c").forward(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
请求、转换图解解释

Servlet学习_第2张图片
注:请求,转换URL路径不会发生改变
注:A请求的东西在C处,所以A告诉B自己所需的东西后,B向C请求资源,得到资源后响应给A,所以url路径不会发生变化

4.读取资源文件
  • 调用getResourceAsStream(资源路径)
    注:建立的资源文件,都会被打包在类路径(classes)下

具体实现类

public class Pro  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ServletContext context = this.getServletContext();
        InputStream in = context.getResourceAsStream("/WEB-INF/classes/pro.propertise");
        Properties properties = new Properties();
        properties.load(in);
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print("姓名:"+username+"\t"+"密码:"+password+"\t"+"路径:"+url);

    }
}

HttpServletResponse

HttpServletResponse应用
1.向浏览器输出信息(上面的案例都是)
2.下载文件
  1. 下载文件的响应头
//设置下载文件响应头,为避免中文乱码,使用URLEncoder.encode(filename,"utf-8"),参数一下载文件名,参数二编码
resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));

注:为避免中文乱码,使用URLEncoder.encode(filename,“utf-8”)来加工下,参数一:下载文件名,参数二:编码类型

  1. 具体实现类
public class Resp extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //1.获取资源绝对路径
        String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/路飞.jpg");
      //2.获取下载文件名
        String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
      //3.设置下载文件响应头,为避免中文乱码,使用URLEncoder.encode(filename,"utf-8"),参数一下载文件名,参数二编码
      resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));
      //4.获取输入流
        FileInputStream input = new FileInputStream(realPath);
      //5.创建缓冲区
        int len=0;
        byte[] buffer = new byte[1024];
      //6.获取输出流,将资源写入客户端
        ServletOutputStream output = resp.getOutputStream();
        while((len=input.read(buffer))!=-1){
            output.write(buffer,0,len);
        }
      //7. 关闭流
      input.close();
      output.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

3.网页验证码,(定期刷新页面)

相关头的配置

resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");

具体实现类

public class down_Im extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //1.定期5秒刷新网页
        resp.setHeader("refresh","3");
       //2.生成照片
        BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
       //3.获取2D画笔,设置背景颜色
        Graphics2D g = (Graphics2D) image.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0,0,80,20);
        //4.设置字体相关配置
        g.setColor(Color.BLUE);
        g.setFont(new Font(null,Font.BOLD,20));
        g.drawString(makeNum(),0,20);
        //5.设置响应类型
        resp.setContentType("image/jpeg");
        //6.设置缓存响应头,缓存控制,以及Pragma,作用:避免占用web资源
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");
        //7.将图片写给浏览器
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    //生成7位数验证码
    private  String makeNum(){
        Random random = new Random();
        String num = random.nextInt(9999999) + "";
        //确保生成7位数的随机数
        StringBuffer s = new StringBuffer();
        for (int i = 0; i < 7-num.length(); i++) {
            s.append("0");
        }
        num=s.toString()+num;
        return  num;
    }
}

4.重定向
  1. 重定向:即一个web资源收到客户端请求后,通知客户端去访问另一个web资源的过程
    • 使用sendRedirect(“跳转路径”);
  2. 重定向图解了解:
    Servlet学习_第3张图片
  3. 代码实现
public class sD extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/d");
    }
}

HttpServletRequest

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

  1. 获取前端初始化参数方法
    1. getParameter() 返回一个String类性值
    2. getParameterValues() 返回一个String类型数组
  2. 请求,转换方法
    getRequestDispatcher(路径)
    forward()
    例子:

    req.getRequestDispatcher("/success.jsp").forward(req,resp);

HttpServletRequest应用

HttpServletRequest获得前段初始化参数,以及转换页面
  1. 初始化页面实现
    注:${pageContext.request.getContextPath()} //代表当前web项目
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录title>
head>
<body>
<h1>注册h1>
<form action="${pageContext.request.getContextPath()}/login" method="post">
   用户名: <input type="text" name="username"><br>
   密码:   <input type="password" name="password"><br>
   爱好: <input type="checkbox" name="hobby" value="电影">电影
         <input type="checkbox" name="hobby" value="阅读">阅读
         <input type="checkbox" name="hobby" value="跑步">跑步 <br>

    <input type="submit" name="注册">
form>
body>
html>
  1. 跳转页面实现
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
<h1 style="color: aqua">成功h1>
body>
html>
  1. 功能实现类实现
public class requ extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String hobby = Arrays.toString(req.getParameterValues("hobby"));
        System.out.println("姓名:"+username+"\t"+"密码:"+password+"\t"+"爱好:"+hobby);
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

你可能感兴趣的:(Servlet学习)