[英]How can I get a User-agent from user request?
I have to get User-agent
from a user request and add custom info to that User-agent
and send it back.我必须从用户请求中获取
User-agent
并将自定义信息添加到该User-agent
并将其发回。 I have the following controller:我有以下 controller:
@RequestMapping("/orders")
@Controller
public class MyController {
@GetMapping("/new_order")
public String newOrder(RedirectAttributes redirectAttributes, Model model) {
if (isUserNotAuthorized()) {
return getLoginRedirectPage(redirectAttributes, "/login");
}
model.addAttribute("order", new Order());
// How to retrieve User-agent and add some custom info and return it back to the user?
return "new_order";
}
}
Thanks for your help!谢谢你的帮助!
You can get the header from the request in the following way您可以通过以下方式从请求中获取 header
@GetMapping("/new_order")
public String newOrder(@RequestHeader(value = "User-Agent") String userAgent, RedirectAttributes redirectAttributes, Model model) {
//...
}
To send the headers back to the client, you can use ResponseEntity要将标头发送回客户端,您可以使用 ResponseEntity
public ResponseEntity<String> newOrder() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("User-Agent", "updated-Value");
return ResponseEntity.ok()
.headers(responseHeaders)
.body("New order created.");
}
Inject HttpServletRequest
in your controller method.在您的 controller 方法中注入
HttpServletRequest
。 From there use HttpServletRequest#getHeader(...)
to get the header you need.从那里使用
HttpServletRequest#getHeader(...)
获取您需要的 header。
@GetMapping("/new_order")
public String newOrder(RedirectAttributes redirectAttributes, HttpServletRequest request, Model model) {
String userAgent = request.getHeader("User-Agent");
if (isUserNotAuthorized()) {
return getLoginRedirectPage(redirectAttributes, "/login");
}
model.addAttribute("order", new Order());
// How to retrieve User-agent and add some custom info and return it back to the user?
return "new_order";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.