英文:
Is there a way to only refresh a view in Spring MVC Controller?
问题
我有一个Spring Boot在线商店应用程序,我的购物车组件可以从多个不同的视图中访问。
我在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.
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
(是的,官方标头有一个拼写错误)请求头来了解你从哪里导航而来:
public String addProduct(@RequestHeader(value = HttpHeaders.REFERER, required = false) final String referrer) {
// 更新购物车
// 重定向到引荐页面
return "redirect:" + referrer;
}
然而,这可能相当脆弱。我不确定引荐 URL 是否始终会出现。
对于这样的情况,我可能会使用 JavaScript 发起一个 AJAX 请求到一个专用的端点,该端点返回 JSON 数据。你可以在控制器的方法上添加 @ResponseBody
,这样响应就不会被视为重定向或页面视图,而是一个 JSON 字符串,例如:
@ResponseBody
public CartInfo updateCart(...) {
// 在这里更新购物车
// 返回一个 CartInfo 对象。它将使用 Jackson 序列化为 JSON 字符串
}
在你的 HTML 页面中,你需要添加一些 JavaScript 来处理 AJAX 调用,可以使用原生的 JS 或者你选择的框架。
英文:
You could use the referer
(yes the official header has a typo) request header to know where you navigated from:
public String addProduct(@RequestHeader(value = HttpHeaders.REFERER, required = false) final String referrer) {
// update cart
// redirect to the referred
return "redirect:" + referrer;
}
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.
@ResponseBody
public CartInfo updateCart(...) {
// do update to cart here
// return a CartInfo object. It will be serialized with Jackson to a JSON string
}
In your HTML page, you will need to add some JavaScript to handle the AJAX call using plain JS or your framework of choice.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论