需求:
将http报文请求(保护body和url)中的参数传递给Controller时支持使用别名。
举例:
下面两条请求报文的结果是一致的。
http://example.com/foo?jobType=permanent&location=Stockholm
http://example.com/foo?jt=permanent&loc=Stockholm
返回响应
解决方法
Spring MVC3 提供了丰富的参数映射机制, 详细信息可以参见这里
同时对于Spring MVC默认的提供的映射机制不能涵盖的对象,我们可以通过扩展HandlerMethodArgumentResolver和HttpMessageConverter的机制来实现。
HandlerMethodArgumentResolver对应输入, HttpMessageConverter对应输出
1.预备代码
package com.davidwang456.web.model;
import com.davidwang456.web.annotation.ParamName;
public class Job {
@ParamName("jt")
private String jobType;
@ParamName("loc")
private String location;
public String getJobType() {
return jobType;
}
public void setJobType(String jobType) {
this.jobType = jobType;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
@Override
public String toString(){
return "jobType="+jobType+",location="+location;
}
}
2.注解
package com.davidwang456.web.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
/**
* Overrides parameter name
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ParamName {
/**
* The name of the request parameter to bind to.
*/
String value();
}
3.注解处理器
package com.davidwang456.web.processor;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor;
import com.davidwang456.web.annotation.ParamName;
/**
* Method processor supports {@link ParamName} parameters renaming
*
*/
public class RenamingProcessor extends ServletModelAttributeMethodProcessor {
@Autowired
private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
//Rename cache
private final Map, Map> replaceMap = new ConcurrentHashMap, Map>();
public RenamingProcessor(boolean annotationNotRequired) {
super(annotationNotRequired);
}
@Override
protected void bindRequestParameters(WebDataBinder binder, NativeWebRequest nativeWebRequest) {
Object target = binder.getTarget();
Class> targetClass = target.getClass();
if (!replaceMap.containsKey(targetClass)) {
Map mapping = analyzeClass(targetClass);
replaceMap.put(targetClass, mapping);
}
Map mapping = replaceMap.get(targetClass);
ParamNameDataBinder paramNameDataBinder = new ParamNameDataBinder(target, binder.getObjectName(), mapping);
requestMappingHandlerAdapter.getWebBindingInitializer().initBinder(paramNameDataBinder, nativeWebRequest);
super.bindRequestParameters(paramNameDataBinder, nativeWebRequest);
}
private static Map analyzeClass(Class> targetClass) {
Field[] fields = targetClass.getDeclaredFields();
Map renameMap = new HashMap();
for (Field field : fields) {
ParamName paramNameAnnotation = field.getAnnotation(ParamName.class);
if (paramNameAnnotation != null && !paramNameAnnotation.value().isEmpty()) {
renameMap.put(paramNameAnnotation.value(), field.getName());
}
}
if (renameMap.isEmpty()) return Collections.emptyMap();
return renameMap;
}
}
4.数据绑定
package com.davidwang456.web.processor;
import java.util.Map;
import javax.servlet.ServletRequest;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.web.servlet.mvc.method.annotation.ExtendedServletRequestDataBinder;
/**
* ServletRequestDataBinder which supports fields renaming using {@link ParamName}
*
*/
public class ParamNameDataBinder extends ExtendedServletRequestDataBinder {
private final Map renameMapping;
public ParamNameDataBinder(Object target, String objectName, Map renameMapping) {
super(target, objectName);
this.renameMapping = renameMapping;
}
@Override
protected void addBindValues(MutablePropertyValues mpvs, ServletRequest request) {
super.addBindValues(mpvs, request);
for (Map.Entry entry : renameMapping.entrySet()) {
String from = entry.getKey();
String to = entry.getValue();
if (mpvs.contains(from)) {
mpvs.add(to, mpvs.getPropertyValue(from).getValue());
}
}
}
}
5.注册处理器
或者java config模式
package com.davidwang456.web.configurer;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.davidwang456.web.processor.RenamingProcessor;
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter{
@Override
public void addArgumentResolvers(List argumentResolvers) {
RenamingProcessor renameResolver = new RenamingProcessor(true);
argumentResolvers.add(renameResolver);
}
}
参考文献:
【1】http://stackoverflow.com/questions/8986593/how-to-customize-parameter-names-when-binding-spring-mvc-command-objects
【2】http://geekabyte.blogspot.tw/2014/08/how-to-inject-objects-into-spring-mvc.html
【3】http://www.cnblogs.com/daxin/p/3296493.html
spring mvc绑定参数之 类型转换 有三种方式:
spring mvc绑定参数之类型转换有三种方式: 1.实体类中加日期格式化注解(上次做项目使用的这种.简单,但有缺点,是一种局部的处理方式,只能在本实体类中使用.方法三是全局的.) @DateTim ...
spring mvc 复杂参数注入
过了这么久,又重新把博客拾起来了 来上海工作也已经有将近两周的时间了, 今天在整理项目的时候,遇到了一个关于参数注入的问题 背景: 我的开发前台用的是extjs4,在对后台spring mvc提交表单 ...
Spring MVC温故而知新 – 参数绑定、转发与重定向、异常处理、拦截器
请求参数绑定 当用户发送请求时,根据Spring MVC的请求处理流程,前端控制器会请求处理器映射器返回一个处理器,然后请求处理器适配器之心相应的处理器,此时处理器映射器会调用Spring Mvc 提 ...
Spring MVC请求参数绑定
所谓请求参数绑定,就是在控制器方法中,将请求参数绑定到方法参数上 @RequestParam 绑定单个请求参数到方法参数上 @RequestParam("id") Integer ...
Spring MVC处理参数Convert
Springmvc.xml 配置convert,xml中配置多个相同的泛型时,xml里配置的convert会从上到下挨个执行. < ...
Spring MVC Action参数类型 List集合类型(简单案例)
题目:定义一个员工实体(Employee),实现批量添加员工功能,在表单中可以一次添加多个员工,数据可以不持久化 1,新建一个项目 2, 然后选择Maven框架选择 maven-archetype-w ...
Spring MVC请求参数绑定 自定义类型转化 和获取原声带额servlet request response信息
首先还在我们的框架的基础上建立文件 在domian下建立Account实体类 import org.springframework.stereotype.Controller; import org. ...
Spring MVC初始化参数绑定
初始化参数绑定与类型转换很类似,初始化绑定时,主要是参数类型 ---单日期 在处理器类中配置绑定方法 使用@InitBinder注解 在这里首先注册一个用户编辑器 参数一为目标类型 proper ...
Spring Mvc 传递参数要controller出现了400,日期参数全局处理,格式化yyyy-MM-dd 和yyyy-MM-dd HH:mm:ss
描述:今天做一个业务操作的时候,ajax传递参数要controller出现了400,前后台都没有报错. 问题:springmvc 在接收日期类型参数时,如不做特殊处理 会出现400语法格式错误 解决: ...
随机推荐
初识Hibernate 缓存
生活就像一杯咖啡,让你我慢慢的品尝,品尝它的苦涩和甘甜...... 一.什么是Hibernate缓存. 解析:白话来说就是缓存数据的容器 官方标准点缓存:是计算机领域的概念,它介于应用程序和永久性数据 ...
HITtrainning20140417题解
题目列表: ID Origin Title 10 / 15 Problem A FZU 2152 文件系统 0 / 16 Problem B FZU 2153 A simple geome ...
C++-高效的swap
原始版本: template void swap(T& a, T& b) { T tmp(a); a = b; b = tmp; } 此版本不重视效 ...
AIM Tech Round (Div. 2) C. Graph and String 二分图染色
C. Graph and String 题目连接: http://codeforces.com/contest/624/problem/C Description One day student Va ...
JavaWeb之Maven配置
Maven和C#的nuget类似,可以通过设置就能引入框架等第三方,方便又省事.Java中使用Maven来管理第三方.今天尝试着配置了一下. 一.JDK的安装 关于JDK的安装可以查看百度经验,设置P ...
Spring-事务配置和详解
一.Spring事务配置 在项目开发过程中经常会使用事务来确保数据的一致性.根据网上的资料整理一下在spring中配置事务的几种方式.无论是哪种方式都需要在配置文件中配置连接池和事务管理器,代码如下. ...
常见问题1:默认div隐藏,点击按钮时出现,再点击时隐藏。
例:默认div隐藏,点击按钮时出现,再点击时隐藏. 控制按钮 ...
对称加密----AES和DES加密、解密
目前主流的加密方式有:(对称加密)AES.DES (非对称加密)RSA.DSA 调用AES/DES加密算法包最精要的就是下面两句话: Cipher cipher = Cipher.get ...
linux中安装oracle数据库
1. 执行 ./runInstaller 提示 /tmp 的空间过小执行 mount -o remount,size=1G,noatime /tmp重新设置 /tmp 的大小 2. 安装完成数据库之后 ...
详细解读Volley(四)—— 自定义Request
Volley中提供了几个Request,如果我们有特殊的需求,完全可以自定义Request的,自定义Request自然要继承Request,那么本篇就教大家来一步一步地定义一个自己的Request类. ...