Vertx3 Cookie操作 官网Demo Java版

本文详细介绍了如何使用Vert.x框架构建Web应用,并通过自定义CookieHandler来跟踪用户会话,实现自动更新和存储用户访问次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package io.vertx.example.web.cookie;

import io.vertx.core.AbstractVerticle;
import io.vertx.example.util.Runner;
import io.vertx.ext.web.Cookie;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.CookieHandler;
import io.vertx.ext.web.handler.StaticHandler;

/*
 * @author <a href="mailto:pmlopes@gmail.com">Paulo Lopes</a>
 */
public class Server extends AbstractVerticle {

  // Convenience method so you can run it in your IDE
  public static void main(String[] args) {
    Runner.runExample(Server.class);
  }

  @Override
  public void start() throws Exception {

    Router router = Router.router(vertx);

    // This cookie handler will be called for all routes
    router.route().handler(CookieHandler.create());

    // on every path increment the counter
    router.route().handler(ctx -> {
      Cookie someCookie = ctx.getCookie("visits");

      long visits = 0;
      if (someCookie != null) {
        String cookieValue = someCookie.getValue();
        try {
          visits = Long.parseLong(cookieValue);
        } catch (NumberFormatException e) {
          visits = 0l;
        }
      }

      // increment the tracking
      visits++;

      // Add a cookie - this will get written back in the response automatically
      ctx.addCookie(Cookie.cookie("visits", "" + visits));

      ctx.next();
    });

    // Serve the static resources
    router.route().handler(StaticHandler.create());

    vertx.createHttpServer().requestHandler(router::accept).listen(8080);
  }
}

 Html:

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
</head>
<body>

<h1>Cookie Example</h1>

<br>
<br>

You have been here <span id="totalTimes">0</span> time(s)!

<br>
<br>

<a href="/">refresh</a>

<script language="JavaScript">
    $(document).ready(function () {
        $('#totalTimes').html($.cookie('visits'));
    });
</script>
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值