• Servlet入门


    1.前言

    2.Servlet是什么?

    3.编写Servlet程序

    4.Servlet生命周期

    5.ServletConfig对象

    6.ServletContext对象

    7.Servlet重定向





    #:前言:

    很多人说在2020学习Servlet就如同98年入国军,就现在的技术栈来讲在工作中用到Servlet的机会确实很小,不过熟悉Servlet能帮助我们更好的深入了解当前流行技术的一些细节,如当前火热的Spring框架中就有Servlet的存在。





    #:Servlet是什么?

    Servlet是Java Applet的简称,指用java编写运行在服务器上的小应用程序,用来处理客户端请求并动态生成响应内容。

    1.从客户端发起请求到服务器
    2.服务器(一般是Tomcat)将请求发送给Servlet
    3.Servlet动态生成响应内容发送给服务器
    4.服务器将响应返回给客户端

    图片





    #编写Servlet程序
    package com.mike;
    
    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;
    
    /**
     * @author mike
     * @date 2020-11-12
     * @desc 使用注解@WebServlet配置servlet
     */
    
    @WebServlet(name="MyServlet",value="/helloServlet")
    public class MyServlet extends HttpServlet { 
    	public MyServlet() {
    		super();
    	}
    
    	@Override
    	protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException {
    		System.out.println("get 请求执行");
    	}
    
    	@Override
    	protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException {
    		System.out.println("post 请求执行");
    	}
    }
    

    1.定义一个类MyServlet继承HttpServlet类并重写其中doGet()及doPost方法,并返回一句话"get 请求执行"
    2.使用注解@WebServlet(name="MyServlet",value="/helloServlet")来指定访问此Servlet的路由名称,其中name为Servlet名称,value为路由名称
    3.编译后代码后,在tomcat服务器启动状态下打开浏览器输入 http://localhost:8080/helloServlet
    4.观察tomacat catalina日志中打印日志





    #Servlet生命周期

    1.容器加载MyServlet.class字节码文件
    2.容器调用其构造方法
    3.容器调用init()方法初始化,在此会初始化ServletConfig对象
    4.容器调用service()方法,并调用doGet()或doPost()方法处理客户端端请求
    5.容器关闭时调用destroy()方法释放资源

    #ServletConfig对象
    在init()方法调用时读取web.xml文件中init-param配置信息并初始化ServletConfig对象
    打开web.xml文件添加一个servlet

       <servlet>
            <!-- servlet-name属性表示当前servlet的内部自定义名称-->
            <servlet-name>config</servlet-name>
            <!-- servlet-class属性表示servlet的真实类名称-->
            <servlet-class>com.mike.ServletConfigDemo</servlet-class>
            <!-- 初始参数:这些参数会在加载web应用的时候,封装到ServletConfig对象中 -->
            <init-param>
                <param-name>name</param-name>
                <param-value>mike</param-value>
            </init-param>
            <init-param>
                <param-name>password</param-name>
                <param-value>123456</param-value>
            </init-param>
            <!-- 让servlet对象自动加载,注意:init-param要在自动加载之前 -->
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <!-- 配置servlet和路由映射关系-->
        <servlet-mapping>
            <!-- servlet-name为上文中servlet内部名-->
            <servlet-name>config</servlet-name>
            <!-- 将当前servlet绑定到路由名称可在地址栏访问-->
            <url-pattern>/config</url-pattern>
        </servlet-mapping>
    

    编写ServletConfigDemo类文件

    package com.mike;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @author mike
     * @date 2020-11-15
     * desc 使用ServletConfig对象获取初始化参数
     */
    public class ServletConfigDemo extends HttpServlet {
    	public ServletConfigDemo() {
    		super();
    	}
    
    	@Override
    	public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException {
    		doPost(request,response);
    	}
    
    	@Override
    	public void doPost(HttpServletRequest request,HttpServletResponse  response)throws ServletException,IOException {
    		ServletConfig config = getServletConfig();
    		String name = config.getInitParameter("name"); //利用name获取配置值
    		String password = config.getInitParameter("password");
    		System.out.println("name: " + name + " password:" + password);
    		response.setCharacterEncoding("UTF-8");
    		response.setContentType("text/html");
    		PrintWriter out = response.getWriter();
    		out.println("<HEAD><TITLE>初始化信息</TITLE></HEAD>");
    		out.println("姓名:" + name + "<br>");
    		out.println("密码:" + password + "<br>");
    		out.flush();
    		out.close();
    	}
    }
    
    

    访问http://localhost:8080/config,观察输出





    #ServletContext对象

    ServletContext是servlet上下文对象,各Servlet之间可以通过ServletContext共享信息
    在web.xml添加context-param配置

     <!--注意,context-param必须放在servlet配置外面,它不属于任何servlet,而属于整个应用配置-->
     <context-param>
            <param-name>name</param-name>
            <param-value>mike</param-value>
        </context-param>
        <context-param>
            <param-name>password</param-name>
            <param-value>8888</param-value>
        </context-param>
    

    新建ServletContextDemo类文件

    package com.mike;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Enumeration;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @author mike
     * @date 2020-11-18
     * desc 使用ServletContext获取整个web应用的配置信息
     */
    public class ServletContextDemo extends HttpServlet {
    	public ServletContextDemo() {
    		super();
    	}
    
    	@Override
    	public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException {
    		doPost(request,response);
    	}
    
    	public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException {
    		ServletContext context = getServletContext();
    		Enumeration<String> names = context.getInitParameterNames();
    		while(names.hasMoreElements()) {
    			String name = names.nextElement();
    			String value = context.getInitParameter(name);
    			System.out.println(name+":"+value);
    		}
    	}
    }
    
    

    访问http://localhost:8080/context 查看输出信息

    新建ServletContextDemo2类文件

    package com.mike;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import java.io.IOException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @author mike
     * @date 2020-11-18
     * desc 测试多个servlet利用context通信
     */
    
    @WebServlet(name="ServletContextDemo2",value = "/context2")
    public class ServletContextDemo2 extends HttpServlet{
    	public ServletContextDemo2() {
    		super();
    	}
    
    	@Override
    	public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
    		doPost(request,response);
    	}
    
    	@Override
    	public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException {
    		ServletContext context = getServletContext();
    		String name = "xiuyue";
    		String password = "1234";
    		context.setAttribute("name",name);
    		context.setAttribute("password",password);
    	}
    }
    
    

    最后新建新建ServletContextDemo3类文件

    package com.mike;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @author mike
     * @date 2020-11-18
     * desc 测试多个servlet利用context通信
     */
    
    @WebServlet(name="ServletContextDemo3",value = "/context3")
    public class ServletContextDemo3 extends HttpServlet{
    	public ServletContextDemo3() {
    		super();
    	}
    
    	@Override
    	public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
    		doPost(request,response);
    	}
    
    	@Override
    	public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException {
    		ServletContext context = getServletContext();
    		response.setCharacterEncoding("UTF-8");
    		response.setContentType("text/html");
    		PrintWriter out = response.getWriter();
    		out.println("姓名" + context.getAttribute("name") + "<br>");
    		out.println("密码" + context.getAttribute("password"));
    		out.close();
    	}
    }
    
    

    分别运行http://localhost:8080/context2,http://localhost:8080/context3查看输出信息

    姓名xiuyue
    密码1234

    当运行context2时会修改第一次定义的配置信息,而context3会将修改后信息读取,这就说明ServletContext是对所有Servlet共享的





    #Servlet重定向
    package com.mike;
    
    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;
    
    /**
     * @author mike
     * @date 2020-11-12
     * @desc 测试servlet重定向
     */
    
    @WebServlet(name="MyServlet",value="/helloServlet")
    public class MyServlet extends HttpServlet {
    	public MyServlet() {
    		super();
    	}
    
    	@Override
    	protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException {
    		response.sendRedirect("http://www.baidu.com");
    	}
    
    }
    
    

    访问http://localhost:8080/helloServlet查看结果,网页被重定向到baidu

  • 相关阅读:
    递归函数
    js原生代码添加表格(行,列用户选择)
    Vue列表数组检测及列表过滤
    字符,图片及视频存储
    小程序js-api简介及操作
    小程序开发-了解
    外购入库单审核可以,删除失败,提示采购单据严格按照数量控制,收料通知单关联数量不能大或负数
    PDO基础应用之异常处理
    进程池用法
    [转]解决Error: That port is already in use.
  • 原文地址:https://www.cnblogs.com/gy1010/p/14008164.html
Copyright © 2020-2023  润新知