2. Servlet3.0注解方式 @WebServlet

web.xml配置还是比较麻烦,这次使用注解方式

编写servlet

2. Servlet3.0注解方式  @WebServlet

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(value = "/test2")
public class ServletTest2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        System.out.println("雷霆嘎巴无情哈拉");
        response.getWriter().write("雷霆嘎巴无情哈拉");
    }
}

运行效果

2. Servlet3.0注解方式  @WebServlet


刚才的@WebServlet注解是3.0提出的,那么 3.0还有哪些规范

文档: https://download.oracle.com/otndocs/jcp/servlet-3.0-fr-eval-oth-JSpec/

2. Servlet3.0注解方式  @WebServlet

  • 一个容器在启动的时候会去找 ServletContainerInitializer 实例对象,该 实例对象 必须放在
    META-INF/services 目录下中一个文件名称叫 javax.servlet.ServletContainerInitializer 里面

2. Servlet3.0注解方式  @WebServlet

  • javax.servlet.ServletContainerInitializer

2. Servlet3.0注解方式  @WebServlet

com.min.demo2.MyServletContainerInitializerTest
  • 编写一个servlet

2. Servlet3.0注解方式  @WebServlet

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 MyServletTest3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        System.out.println("MyServletTest3--------------");
        response.getWriter().write("大威天龙");
    }
}
  • 编写 ServletContainerInitializer 的实现类

2. Servlet3.0注解方式  @WebServlet

import com.min.demo3.MyServletTest3;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import java.util.Set;

public class MyServletContainerInitializerTest implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException { //启动时执行的方法
        //System.out.println("MyServletContainerInitializerTest-------------");

        //servletContext.addServlet(名称,new出来的Servlet对象);
        //servletContext.addFilter();
        //servletContext.addListener();

        //添加上自己定义的servlet
        ServletRegistration.Dynamic dynamic = servletContext.addServlet("aaa", new MyServletTest3());
        //设置启动顺序
        dynamic.setLoadOnStartup(1);
        //设置访问路径
        dynamic.addMapping("/demo3");
    }
}
  • 运行效果

2. Servlet3.0注解方式  @WebServlet

2. Servlet3.0注解方式 @WebServlet

上一篇:Nginx之HTTPS实战


下一篇:android.mk详解