gpt4 book ai didi

java - Spring mvc。不区分大小写的获取参数映射

转载 作者:IT老高 更新时间:2023-10-28 13:50:30 40 4
gpt4 key购买 nike

根据 this answer 我尝试编写我的代码:

pojo:

class MyBean{

public String getValueName() {
return valueName;
}

public void setValueName(String valueName) {
this.valueName = valueName;
}

String valueName;
}

内部 Controller :

    @ModelAttribute
public MyBean createMyBean() {
return new MyBean();
}
@RequestMapping(value = "/getMyBean", method = RequestMethod.GET)
public String getMyBean(@ModelAttribute MyBean myBean) {
System.out.println(myBean.getValueName());
return "pathToJsp";
}

web.xml 配置:

<filter>
<filter-name>caseInsensitiveFilter</filter-name>
<filter-class>com.terminal.interceptor.CaseInsensitiveRequestFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>caseInsensitiveFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

过滤器:

@Component
public class CaseInsensitiveRequestFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
filterChain.doFilter(new CaseInsensitiveHttpServletRequestWrapper(request), response);
}

private static class CaseInsensitiveHttpServletRequestWrapper extends HttpServletRequestWrapper {

private final LinkedCaseInsensitiveMap params = new LinkedCaseInsensitiveMap();

/**
* Constructs a request object wrapping the given request.
*
* @param request
* @throws IllegalArgumentException if the request is null
*/
private CaseInsensitiveHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
params.putAll(request.getParameterMap());
}

@Override
public String getParameter(String name) {
String[] values = getParameterValues(name);
if (values == null || values.length == 0) {
return null;
}
return values[0];
}

@Override
public Map getParameterMap() {
return Collections.unmodifiableMap(this.params);
}

@Override
public Enumeration getParameterNames() {
return Collections.enumeration(this.params.keySet());
}

@Override
public String[] getParameterValues(String name) {
return (String[]) params.get(name);
}
}
}

在调试中我看到过滤器方法调用但我无法实现不区分大小写的获取参数映射。

例如 localhost:8081/getMyBean?valueName=trololo 有效,但 localhost:8081/getMyBean?valuename=trololo - 无效

最佳答案

我相信你的问题是 @ModelAttribute。您要求 Spring 将参数映射到 MyBean 对象,并且该对象内的属性是 valueName

为了让 Spring 将参数反射(reflect)到对象,它需要使用正确的大小写。

你有两个选择:

  • 在您的 MyBean 对象中将属性名称更改为 valuename,并将所有属性名称更改为小写,它应该在您的解决方案的帮助下工作。
  • 删除 @ModelAttribute 并为每个属性添加 @RequestParam。如果你有很多 Prop ,这可能会很痛苦。

关于java - Spring mvc。不区分大小写的获取参数映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32364126/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com