Servlet

一、Servlet技术

1.什么是Servlet?

  • Servlet 技术就是JavaEE的规范之一。规范就是接口。
  • Servlet就javaWeb三大组件之一。三大组件分别是:Servlet程序,Filter过滤器,Listenner监听器

Servlet是运行在服务器上的一个java程序,它可以接受客户端发送来的请求,并响应数据给客户端。

2.Servlet的生命周期

  • 1.加载和实例化:默认情况下,当Servlet第一次被访问时,由容器创建Servlet对象(通过loadOnStartup=1注解配置   负整数: 第一次被访问时创建Servlet对象   0或正整数 服务器启动时创建,数字越小优先级越高   )
  • 2.执行init初始化方法(该方法只调用一次)
  • 3.请求处理:执行service方法(请求处理每次访问都会调用)
  • 4.服务终止:执行destroy销毁方法(web工程结束时调用)

3.Servlet 对象由谁创建?Servlet 方法由谁调用?

Servlet对象由Web服务器创建,Servlet方法由web服务器调用。

4.Servlet体系结构

Servlet_第1张图片

5.ServletURLpattern 配置规则

Servlet_第2张图片

1.精确匹配

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

/**
 * URL配置
 *
 * 一个URL可以配置多个访问路径
 * 1.精确匹配
 */
@WebServlet(urlPatterns ="/user/select")
public class ServletDemo8 extends MyServlet {
    @Override
    protected void doPost(ServletResponse res, ServletRequest req) {
        System.out.println ("demo8 get....");
    }

    @Override
    protected void doGet(ServletRequest req, ServletResponse res) {
        System.out.println ("demo7 post....");
    }
}

2.目录匹配  ("/user/*")

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

/**
 * URL配置
 *
 * 一个URL可以配置多个访问路径
 * 2.目录匹配
 */
@WebServlet(urlPatterns ="/user/*")
public class ServletDemo9 extends MyServlet {
    @Override
    protected void doPost(ServletResponse res, ServletRequest req) {
        System.out.println ("demo9 post....");
    }

    @Override
    protected void doGet(ServletRequest req, ServletResponse res) {
        System.out.println ("demo9 get....");
    }
}

3.扩展名匹配(不能加 /  *.do )

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

/**
 * URL配置
 *
 * 一个URL可以配置多个访问路径
 * 3.扩展名匹配(不能加 /  *.do )
 */
@WebServlet(urlPatterns ="*.do")
public class ServletDemo10 extends MyServlet {
    @Override
    protected void doPost(ServletResponse res, ServletRequest req) {
        System.out.println ("demo10 post....");
    }

    @Override
    protected void doGet(ServletRequest req, ServletResponse res) {
        System.out.println ("demo10 get....");
    }
}

4.任意匹配       (1. /    2./*   /* 的优先级高于 /)

/**
 * URL配置
 *
 * 一个URL可以配置多个访问路径
 * 4.任意匹配   1. /    2./*   /* 的优先级高于 /
 */
@WebServlet(urlPatterns ="/*")
public class ServletDemo11 extends MyServlet {
    @Override
    protected void doPost(ServletResponse res, ServletRequest req) {
        System.out.println ("demo12 post....");
    }

    @Override
    protected void doGet(ServletRequest req, ServletResponse res) {
        System.out.println ("demo12 get....");
    }
}

6.Request(请求) & Response(响应)

  • Request :获取请求数据
  • Response:设置响应数据
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "ServletTest", value = "/abc")
public class ServletTest extends HttpServlet {
    @Override
    //在get请求时调用
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println ("HelloServlet的doGet方法");
        //使用request 对象 获取请求数据
        String name =request.getParameter ( "name" );
        //使用 response 对象 设置响应数据
        response.setHeader ( "content-type","text/html;charset=utf-8" );//设置响应头

        response.getWriter ().write ( "

"+name+",欢迎您!

" ); } @Override //在post请求时调用 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println ("post"); } }

1.Request 继承体系

Servlet_第3张图片

2.Request 获取请求数据

Servlet_第4张图片


import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet(name = "RequestDemo1", value = "/RequestDemo1")
public class RequestDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String method =request.getMethod ();
        System.out.println (method);
    String contextPath= request.getContextPath ();
        System.out.println (contextPath);
        StringBuffer url =request.getRequestURL ();
        System.out.println (url.toString ());
    String uri=request.getRequestURI ();
        System.out.println (uri);
        String queryString =request.getQueryString ();
        System.out.println (queryString);

        //-------------
        //获取请求头
        //user-agent:浏览器的版本信息
    String header=request.getHeader ( "user-agent" );
        System.out.println (header);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取post的请求体
        //1.获取字符输入流
        BufferedReader br=request.getReader ();
        //2.读取数据
        String Line =br.readLine ();
        System.out.println (Line);
    }
}

3.使用通用方法获取请求参数

Servlet_第5张图片

@WebServlet(name = "RequestDemo2", value = "/req2")
public class RequestDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println ("get...");
        //1.获取所有参数的map集合   获取所有值
    Map map =  request.getParameterMap ();
        for (String key:map.keySet ()
             ) {//username :zhangsan
            System.out.print (key+":");
            String [] values= map.get (key);
            for (String value:values
                 ) {
                System.out.print (value+"");
            }
            System.out.println ();
        }
        //2.根据Key获取参数值,数组
    String[] hobbies=request.getParameterValues ( "hobby" );
        for (String hobby:hobbies
             ) {
            System.out.println (hobby);
        }
        //3根据Key获取单个值
        String name=  request.getParameter ( "username" );
        String password=  request.getParameter ( "password" );
        System.out.println (name);
        System.out.println (password);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println ("post...");
        //1.获取所有参数的map集合   获取所有值
        Map map =  request.getParameterMap ();
        for (String key:map.keySet ()
        ) {//username :zhangsan
            System.out.print (key+":");
            String [] values= map.get (key);
            for (String value:values
            ) {
                System.out.print (value+"");
            }
            System.out.println ();
        }
        //2.根据Key获取参数值,数组
        String[] hobbies=request.getParameterValues ( "hobby" );
        for (String hobby:hobbies
        ) {
            System.out.println (hobby);
        }
        //3根据Key获取单个值
        String name=  request.getParameter ( "username" );
        String password=  request.getParameter ( "password" );
        System.out.println (name);
        System.out.println (password);
    }
}

4.Request 获取请求数据

请求参数如果存在中文就会乱码

get方式发生乱码的原因(编码和解码不一致)

Servlet_第6张图片

@WebServlet(name = "Servlet", value = "/Servlet")
public class Servlet extends HttpServlet {
    @Override
    /**
     * 中文乱码的问题解决方案
     *
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.解决乱码 Post getReader()
        request.setCharacterEncoding ( "UTF-8" );//设置字符输入流的编码


        //2获取数据
        String name= request.getParameter ( "username" );
        System.out.println ("解决乱码前"+name);
        //3.GET 获取参数的方式:getQueryString
        //乱码原因:tomcat进行URL解码默认的字符集"ISO-8859-1"
          //3.1 先对乱码数据进行编码:转换为字节数组
       byte [] bytes =name.getBytes( StandardCharsets.ISO_8859_1 );
            //3.2 字节数组解码
       name =new String (bytes,StandardCharsets.UTF_8);
        System.out.println ("解决乱码后"+name);


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet ( request, response );
    }
}

5.Request 请求转发

请求转发:是在服务器内部的资源跳转方式

Servlet_第7张图片

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
 * 请求转发
 *
 */
@WebServlet(name = "RequestDemo3", value = "/req3")
public class RequestDemo3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println ("3333333333333");

   // 存储数据
        request.setAttribute ( "msg","hello" );
   //转发
        request.getRequestDispatcher ( "/req4" ).forward ( request,response );
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet ( request, response );
    }
}
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "RequestDemo4", value = "/req4")
public class RequestDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println ("44444444444");
  //获取数据
     Object name =request.getAttribute ( "msg" );
        System.out.println (name);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet ( request, response );
    }
}

先执行/req3 然后转发到/req4中继续执行

6.Response对象(设置响应数据)

6.1 Response 设置响应数据功能介绍

Servlet_第8张图片

6.2 Response 完成重定向

Servlet_第9张图片

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "ResponseDemo1", value = "/resp1")
public class ResponseDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println ("resp1");
        //重定向
//        //1.设置响应状态码
//        response.setStatus ( 302 );
//        //2.设置响应头Location
//        response.setHeader ("Location","/resp2");
        //3.简化方式完成重定向
//        response.sendRedirect ( "/resp2" );
        String contextPath =request.getContextPath ();
        response.sendRedirect ( contextPath+"/resp2" );
        System.out.println (contextPath);
        request.setAttribute ("contextPath" ,contextPath );
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet ( request, response );
    }
}
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "ResponseDemo2", value = "/resp2")
public class ResponseDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println ("resp2");
        Object url=request.getAttribute ( "contextPath" );
        System.out.println (url);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet ( request, response );
    }
}
6.3响应字符数据

Servlet_第10张图片

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "ResponseDemo3", value = "/resp3")
public class ResponseDemo3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //1.获取字符输出流
        response.setContentType ( "text/html;charset=utf-8" );//设置字符流的编码格式,防止中文乱码
        PrintWriter writer =response.getWriter ();
        //content-type 告诉浏览器将来的将数据响应是html的
//        response.setHeader ( "content-type","text/html" );
        writer.write ( "好好好" );//写到网页上展示
        writer.write ( "

aaa

" ); //流不需要关闭 } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet ( request, response ); } }
6.4响应字节输出流

Servlet_第11张图片

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet(name = "ResponseDemo4", value = "/resp4")
public class ResponseDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //1.读取文件
  FileInputStream fis =new FileInputStream ("C:\\Users\\18726\\Documents\\CFSystem\\Crossfire20221215_0000.bmp");

     //2.获取response字节输出流
    ServletOutputStream os =response.getOutputStream ();
        //3.完成流的copy            //可以在页面上看到一张图片
        byte[] buff =new byte[1024];
        int len=0;
        while ((len=fis.read (buff))!=-1){
            os.write ( buff,0,len );
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet ( request, response );
    }
}

你可能感兴趣的:(servlet)