英文:
How to get query string without equal sign using SpringBoot?
问题
我们知道 @RequestParam 是一种获取查询参数的好方法,比如像 "?name=Tom" 这样的:
www.example.com/?name=Tom
你可以使用:
@RequestParam(value="name") String name
来获取键 "name"。
但是如何获取没有等号的查询字符串,比如:
www.example.com/?1+1
在这种情况下没有键值对,我无法从互联网上找到答案,因为基本上查询字符串是由键值对组成的。
顺便说一下,框架必须是使用 Java 的 Spring Boot,还有 Thymeleaf 用于 HTML。
英文:
We know @RequestParam is a good way to get query parameters like "?name=Tom" for example:
www.example.com/?name=Tom
and you can use
@RequestParam(value="name") String name
to get the key "name".
But how to get the query string without equal sign such as:
www.example.com/?1+1
There is no key-value pair in this case and I can't find the answer from the internet because basically query string is used by key-value case.
Btw, the Framework has to be SpringBoot with Java, and also html for Thymeleaf.
答案1
得分: 2
可以从HttpServletRequest.getQueryString()获取它。在控制器方法中,HttpServletRequest由SpringMVC注入。
@RestController
class WhatEverController {
@GetMapping("whatever")
public void whatEver(HttpServletRequest request,
HttpServletResponse response) {
String queryString = request.getQueryString();
}
}
英文:
You can get it from HttpServletRequest.getQueryString(). In the controller method, the HttpServletRequest is injected by SpringMVC.
@RestController
class WhatEverController {
@GetMapping("whatever")
public void whatEver(HttpServletRequest request,
HttpServletResponse response {
String queryString = request.getQueryString();
}
}
答案2
得分: 0
public static Map<String, String> getQueryMap(String query) {
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params) {
String[] p = param.split("=");
String name = p[0];
if (p.length > 1) {
String value = p[1];
map.put(name, value);
}
}
return map;
}
// 使用方法
Map params = getQueryMap(querystring);
String id = (String) params.get("id");
String anotherparam = (String) params.get("anotherparam");
英文:
Querystring from another source :
public static Map<String, String> getQueryMap(String query)
{
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params)
{ String [] p=param.split("=");
String name = p[0];
if(p.length>1) {String value = p[1];
map.put(name, value);
}
}
return map;
}
You can use
Map params=getQueryMap(querystring);
String id=(String)params.get("id");
String anotherparam=(String)params.get("anotherparam");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论