@Override public void handle(RouteContext context) { context.text("登录成功"); }
@Test public void testRouteMatcher() throws Exception { routeMatcher.addRoute("/", ctx -> ctx.text("Ok"), HttpMethod.GET); routeMatcher.addRoute("/*", ctx -> ctx.text("Ok"), HttpMethod.BEFORE); routeMatcher.register(); Route route = routeMatcher.lookupRoute("GET", "/"); Assert.assertEquals("GET\t/", route.toString()); List<Route> routes = routeMatcher.getBefore("/"); Assert.assertEquals(1, routes.size()); }
public static void main(String[] args) { Blade.of() .get("/hello", ctx -> ctx.text("get route")) .post("/post", ctx -> ctx.text(ctx.request().query("param","null"))) .webSocket("/websocket", new WebSocketHandler() { @Override public void onConnect(WebSocketContext ctx) { System.out.println("客户端连接上了ws1: " + ctx.getSession()); } @Override public void onText(WebSocketContext ctx) { System.out.println("ws1收到:" + ctx.getReqText()); ctx.message("发送: Hello"); } @Override public void onDisConnect(WebSocketContext ctx) { System.out.println("ws1客户端关闭链接: " + ctx.getSession()); } }).start(WebSocketDemo.class); }
.get("/error", ctx -> { int a = 1 / 0; ctx.text("ok"); }) .get("/hello", ctx -> ctx.body(hello)) .get("/error", ctx -> { int a = 1 / 0; ctx.text("Hello World."); }) .post("/hello", ctx -> ctx.text("Hello World.")) .put("/body", ctx -> { ctx.text(ctx.bodyToString()); }) .put("/hello", ctx -> ctx.text("Hello World.")) .delete("/hello", ctx -> ctx.text("Hello World.")) .get("/download", ctx -> { try { int timeout = ctx.fromInt("timeout", new Random().nextInt(1000)); TimeUnit.SECONDS.sleep(timeout); ctx.text("sleep " + timeout + "s"); } catch (InterruptedException e) { e.printStackTrace(); ctx.text("Hello World"); ctx.abort();
@Test public void testAddRoute() throws Exception { routeMatcher.addRoute(Route.builder().httpMethod(HttpMethod.POST).targetType(RouteHandler.class) .target((RouteHandler) (ctx) -> ctx.text("post request")) .path("/save") .build()); routeMatcher.register(); Route saveRoute = routeMatcher.lookupRoute("POST", "/save"); Assert.assertEquals("POST\t/save", saveRoute.toString()); }
@Override public boolean before(RouteContext context) { // 黑名单过滤 if (Utils.isBlackIP(context.address())) { context.text("You are forbidden to access :("); return false; } // 安装向导 if (!context.uri().startsWith("/install") && !Utils.isInstall()) { context.redirect("/install"); return false; } // 后台登录校验 if (context.uri().startsWith("/admin/") && !Utils.isLogin()) { context.redirect("/login"); return false; } return true; }