smartboot 开源组织 smartboot 开源组织
首页
  • smart-socket
  • smart-http
  • smart-servlet
  • smart-mqtt
  • smart-license
  • feat
❤️开源捐赠
💰付费服务
🏠加入社区
  • Gitee (opens new window)
  • Github (opens new window)
首页
  • smart-socket
  • smart-http
  • smart-servlet
  • smart-mqtt
  • smart-license
  • feat
❤️开源捐赠
💰付费服务
🏠加入社区
  • Gitee (opens new window)
  • Github (opens new window)
  • 指南

    • 快速上手
    • 服务配置
    • 静态资源服务
    • 请求路由
    • 安全性设计
    • WebSocket
    • 关于 smart-http-restful

请求路由

# 请求路由

熟悉 Servlet 或者 Spring MVC 开发的人应该对这个不陌生, 前端请求的不同接口,需要路由到不同 Servlet 或者 Controller 中进行处理。

smart-http 也提供了请求路由的支持,使用时需要用到HttpRouteHandler。

public class HttpRouteDemo {
    public static void main(String[] args) {
        //1. 实例化路由Handle
        HttpRouteHandler routeHandle = new HttpRouteHandler();

        //2. 指定路由规则以及请求的处理实现
        routeHandle.route("/", new HttpServerHandler() {
            @Override
            public void handle(HttpRequest request, HttpResponse response) throws IOException {
                response.write("smart-http".getBytes());
            }
        }).route("/test1", new HttpServerHandler() {
            @Override
            public void handle(HttpRequest request, HttpResponse response) throws IOException {
                response.write(("test1").getBytes());
            }
        }).route("/test2", new HttpServerHandler() {
            @Override
            public void handle(HttpRequest request, HttpResponse response) throws IOException {
                response.write(("test2").getBytes());
            }
        });

        // 3. 启动服务
        HttpBootstrap bootstrap = new HttpBootstrap();
        bootstrap.httpHandler(routeHandle);
        bootstrap.start();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

当然,如果 smart-http 默认提供的路由组件满足不了你的需求,用户也可以通过继承HttpServerHandler自己实现一套请求路由算法。

静态资源服务
安全性设计

← 静态资源服务 安全性设计→

Theme by Vdoing | Copyright © 2017-2025 三刀
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式