有没有一种方法只在Spring MVC控制器中刷新视图?

huangapple go评论143阅读模式
英文:

Is there a way to only refresh a view in Spring MVC Controller?

问题

我有一个Spring Boot在线商店应用程序,我的购物车组件可以从多个不同的视图中访问。

有没有一种方法只在Spring MVC控制器中刷新视图?

我在Thymeleaf中制作我的视图,而那些-+分别是<a th:href="@{'/products/addToCart/'+${product.id}}">。现在,在我的products控制器中,我进行一些后端工作并返回一个redirect:home,但这在某种程度上破坏了放置这些-+的整个目的。我希望它能够从发送请求的同一视图中返回。有办法做到这点吗?我不喜欢为每个视图单独创建控制器的想法。

英文:

I have a Spring Boot online shop application and my shopping cart component is accessible from several different views.

有没有一种方法只在Spring MVC控制器中刷新视图?

I make my views in Thymeleaf and those - and + are <a th:href="@{'/products/addToCart/'+${product.id}}">. Now inside my products controller I do some backend work and return a redirect:home but that kind of kills the whole point of putting these - and + there. I'd like it to return the same view from which the request was sent. Can that be done somehow? I don't like the idea of making seperate controllers for every view.

答案1

得分: 2

你可以使用 referer(是的,官方标头有一个拼写错误)请求头来了解你从哪里导航而来:

  1. public String addProduct(@RequestHeader(value = HttpHeaders.REFERER, required = false) final String referrer) {
  2. // 更新购物车
  3. // 重定向到引荐页面
  4. return "redirect:" + referrer;
  5. }

然而,这可能相当脆弱。我不确定引荐 URL 是否始终会出现。

对于这样的情况,我可能会使用 JavaScript 发起一个 AJAX 请求到一个专用的端点,该端点返回 JSON 数据。你可以在控制器的方法上添加 @ResponseBody,这样响应就不会被视为重定向或页面视图,而是一个 JSON 字符串,例如:

  1. @ResponseBody
  2. public CartInfo updateCart(...) {
  3. // 在这里更新购物车
  4. // 返回一个 CartInfo 对象。它将使用 Jackson 序列化为 JSON 字符串
  5. }

在你的 HTML 页面中,你需要添加一些 JavaScript 来处理 AJAX 调用,可以使用原生的 JS 或者你选择的框架。

英文:

You could use the referer (yes the official header has a typo) request header to know where you navigated from:

  1. public String addProduct(@RequestHeader(value = HttpHeaders.REFERER, required = false) final String referrer) {
  2. // update cart
  3. // redirect to the referred
  4. return "redirect:" + referrer;
  5. }

However, that is probably quite brittle. I'm not sure the referrer URL will always be there.

For something like this, I would probably use JavaScript to do an AJAX request to a dedicated endpoint that returns JSON. You can add @ResponseBody on a method in your controller so the response is not seen as a redirect or a page view, but a JSON string for example.

  1. @ResponseBody
  2. public CartInfo updateCart(...) {
  3. // do update to cart here
  4. // return a CartInfo object. It will be serialized with Jackson to a JSON string
  5. }

In your HTML page, you will need to add some JavaScript to handle the AJAX call using plain JS or your framework of choice.

huangapple
  • 本文由 发表于 2020年9月1日 18:43:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63686105.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定