java 8 实现简单的Servlet路由

使用注解方式创建Servlet类,doGet方法转向doPost方法


@WebServlet("/svc/*")
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

doPost方法接收HttpServletRequest, HttpServletResponse两个参数,无返回值,可以用BiConsumer接收
通过Map建立字符串到方法的映射

    private Map> routerMap = new HashMap<>();

    @Override
    public void init() throws ServletException {
        routerMap.put("test", this::test);
        routerMap.put("login", this::login);
        routerMap.put("route1", this::route1);
        routerMap.put("route2", this::route2);
    }

reqresp进行编码和格式设置
获取请求的地址并截去公共部分字符串
用所获得的字符串从Map中获取到实际处理请求的方法并执行

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");

        String route = req.getRequestURI().substring(5);

        BiConsumer router = routerMap.get(route);

        if (router == null) router = (request, response) -> System.out.println("no route to" + route);

        router.accept(req, resp);
    }

像写正常的doPost方法一样写处理请求的方法

    public void test(HttpServletRequest req, HttpServletResponse resp) {
        req.getParameterMap().forEach((k, v) -> System.out.println(k));
        try {
            resp.getWriter().print("{\"result\":\"hello\"}");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void login(HttpServletRequest req, HttpServletResponse resp) {
    // ...
    }

    // ...
}

你可能感兴趣的:(学习笔记)