spring-boot 使用原生Servlet
配置一
@WebServlet(urlPatterns = "/testServlet/*")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = -7866686514340118523L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json; charset=utf-8");
String jsonStr = "{\"name\":\"fly\",\"type\":\"虫子\"}";
PrintWriter out = null;
try {
out = resp.getWriter();
out.write(jsonStr);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
}
配置二
public class Test2Servlet extends HttpServlet {
private static final long serialVersionUID = -5327348304390633663L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json; charset=utf-8");
String jsonStr = "{\"name\":\"fly\",\"type\":\"虫子1\"}";
PrintWriter out = null;
try {
out = resp.getWriter();
out.write(jsonStr);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
}
使用配置文件@Bean注入方式
@SpringBootApplication
@ServletComponentScan
@Import(value={SpringUtil.class})
public class App {
@Bean
public ServletRegistrationBean MyServlet1(){
return new ServletRegistrationBean(new Test2Servlet(),"/test2Servlet/*");
}
public static void main(String[] args) {
Class<?>[] c = {App.class};
SpringApplication.run(c, args);
}
}