不使用框架实现HTTP API 接口
由于接手的项目不是常用的spring 框架实现的,而是单纯的无框架纯JAVA实现的, 需要实现HTTP API 无法采用常用的 spring 注解实现。
因此,采用 内嵌 jetty 服务器的方式实现。
pom.xml 添加依赖:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.4.12.v20180830</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>9.4.12.v20180830</version>
</dependency>
初始化过程中 内嵌 jetty 服务器
public static void main(String... args) {
initServlet();
}
private static void initServlet(){
Server server = new Server(28080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
// 添加 url -> api 的mapping
context.addServlet(TestApi.class, "/test/*");
//启动服务star
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
API 实现
api 类须继承 HttpServlet 类
public class TestApi extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
String uri = request.getRequestURI();
if(uri.contains("exceptedUrl")) {
// TODO
} else {
notFound(response);
}
}
}
over