Although we use in springboot Controller can meet most needs, but servlet, etc. are also essential.
Use the servlet springboot in two ways:
The first:
- Creating a servlet with the annotation mode, and declares its url in a comment
- Add @ServletComponentScan ( "com.rong.interceptor.servlet") on the Application class, which is the path of notes in the servlet created.
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);
}
}
The second (this way except that no @ServletComponentScan):
- Still we have to create a servlet, the same as above except that no @WebServlet comment.
- Then create a servlet class configuration, and add the url in the configuration class
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;
}
}