SpringBoot拾级而上·自定义 Servlet

一、编写 Servlet

package com.springboot.springboot_web.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 ServletTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write("自定义 Servlet");
        resp.getWriter().write("
res getContentType:"+resp.getContentType()); resp.getWriter().write("
res getCharacterEncoding:"+resp.getCharacterEncoding()); resp.getWriter().write("
res getHeaderNames:"+resp.getHeaderNames()); } }

二、注册 Servlet
将 Servelt 注册成 Bean。在上文创建的 WebConfig 类中添加如下代码

    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        return new ServletRegistrationBean(new ServletTest(),"/servletTest");
    }

访问 http://127.0.0.1:8081/servletTest,页面返回

自定义 Servlet
res getContentType:text/html;charset=utf-8
res getCharacterEncoding:utf-8
res getHeaderNames:[]

你可能感兴趣的:(SpringBoot拾级而上·自定义 Servlet)