我想自己制作一个非常纤细的rest框架,并且试图将路由列表和相应的动作传递给我的HttpServlet。
名为 RoutingServlet的HttpServlet必须在init()方法中从Routes.getRoutes()静态方法获取此路由列表,并将请求和响应参数传递给所传递的特定处理程序(< strong>就像使用Spring Controller的Dispatcher Servlet一样)
当我尝试将列表传递给我的RoutingServlet 时,除了doGet()或doPost()方法之外,没有任何错误,路由列表为空(即使之前已填充)。
here Utility类,用于静态存储路由列表
public class Routes {
public static List<RouteMapper> routes = new ArrayList<RouteMapper>();
public static void setRoute(RouteMapper route){
routes.add(route);
}
public static List<RouteMapper> getRoutes(){
return routes;
}
}
Application.java:
public class Application {
public static void main(String[] args) throws Exception{
UserHandler userHandler = new UserHandler();
Routes.setRoute(new RouteMapper("/user/1", (req, res) -> userHandler.firstMapping(req, res)));
Routes.setRoute(new RouteMapper("/user", (req, res) -> userHandler.secondMapping(req, res)));
System.out.println("In main routes size: " + Routes.getRoutes().size());
EmbeddedServer.startServer("8086");
}
}
RoutingServlet.java:
@WebServlet(
name = "RoutingServlet",
urlPatterns = {"/"}
)
public class RoutingServlet extends HttpServlet {
public static List<RouteMapper> routes = new ArrayList<RouteMapper>();
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
routes = Routes.getRoutes();
System.out.println("In oninit routes size: " + routes.size());
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object response = null;
String path = req.getRequestURI();
for(RouteMapper route : routes){
if(Objects.equals(route.getUrlPath(),path)){
response = route.getRoute().action(req, resp);
}
}
String jsonResponse = "";
if(response != null){
ObjectMapper mapper = new ObjectMapper();
jsonResponse = mapper.writeValueAsString(response);
}else{
jsonResponse = "Http Request not mapped!";
}
ServletOutputStream out = resp.getOutputStream();
out.write(jsonResponse.getBytes());
out.flush();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
所以问题是:为什么我不能将任何对象传递给Servlet?我该怎么办?
我成功的唯一方法是在Application类中静态定义列表(不是在主类中,而是在类声明之后),然后通过调用Application.routes从init()中的HttpServlet获取路由列表。我不想使用这种方法,因为我想将一个库中的Servlet和嵌入式Tomcat分开,并通过导入所需的所有库类在我的Application#main中使用此库。