サーブレットの二つの方法をspringboot_

我々はspringbootに使用していますがコントローラーは、ほとんどのニーズを満たすが、サーブレットなどできるも不可欠です。

二つの方法でサーブレットspringbootを使用します。

最初:

  1. 注釈モードでサーブレットを作成し、コメントにURLを宣言
  2. 作成したサーブレットでのノートのパスApplicationクラス、上@ServletComponentScan(「com.rong.interceptor.servletを」)を追加します。
package com.rong.interceptor.servlet;

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("/myservlet")
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       resp.getWriter().write("hello");
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
@SpringBootApplication
@ServletComponentScan("com.rong.interceptor.servlet")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

第二(なし@ServletComponentScanことを除いて、この方法):

  1. それでも私たちは、サーブレットを作成していない@WebServletコメントそれ以外は上記と同じを持っています。
  2. そして、サーブレットクラスのコンフィギュレーションを作成し、コンフィギュレーション・クラスにURLを追加
package com.rong.interceptor.servlet;

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;

public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       resp.getWriter().write("hello");
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
package com.rong.interceptor.config;

import com.rong.interceptor.servlet.MyServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ServletConfig {

    @Bean
    public ServletRegistrationBean myServletRegistration(){
        ServletRegistrationBean registration = new ServletRegistrationBean(new MyServlet());
        registration.addUrlMappings("/myservlet");
        return registration;
    }
}

 

公開された60元の記事 ウォン称賛10 ビュー9178

おすすめ

転載: blog.csdn.net/chaseqrr/article/details/104417892