springMVC参数默认初始化对象,如何禁止?

是这样的,springMVC action的参数中如果有对象类型,在访问这个action的时候会默认new一个,我现在需要判断参数对象是否为null,可是spring默认会创建对象使我很尴尬,
ps:@ModelAttribute 不行,这时候参数已经new了
 
@Controller
@RequestMapping("/resource")
public class ResourceController extends BaseAction {

@Autowired
private ResourceSer resourceSer;
@Autowired
private AddressSer addressSer;
private static Logger logger = Logger.getLogger(ResourceController.class);


/**
* @Author:
* @Description: 查询所有能查看的资源 通过前端将eqMap, likeMap, btnMap转为json传递至后端,再转为相应的map进行查询
* @Date: Created on 2017/7/21
* @Version: 1.0
*/
@RequestMapping(value = "/resources", method = RequestMethod.GET)
@ResponseBody
public String resources(String eq, String neq, String like, String btn, Pager pager, HttpSession session) {
logger.info(" -------------------- /resource/resources --------------------");
logger.info(" resources pager : " + pager);
//if (!validSite(eq) || !validAuthorL(session, 3)) return UserController.error(session);
eq = decode(eq);
neq = decode(neq);
like = decode(like);
btn = decode(btn);
logger.info(" resources 参数 eq : " + eq + " neq : " + neq + " like : " + like + " btn : " + btn);
List<Resource> resources = resourceSer.findByDynamic(getMap(eq), getMap(neq), getMap(like), getMapList(btn), null, pager).getDatas();
String json = JSON.toJSONString(resources, SerializerFeature.DisableCircularReferenceDetect);
logger.info(" resources 结果 json : " + json);
return json;
}
}
这时候我访问http://localhost:8080/resource/resources  
2017-08-10 14:55:37 -1576140 [http-bio-8088-exec-7] INFO    -  -------------------- /resource/resources --------------------
2017-08-10 14:55:37 -1576891 [http-bio-8088-exec-7] INFO - resources pager : com.chaoxing.core.util.Pager@3e17d44b
理论上说pager应该为null,但是spring自动创建了pager,我需要的是传递参数没有pager的时候pager为null。
有什么解决方法吗?
已邀请:

carl_zhao - http://blog.csdn.net/u012410733

赞同来自: Gallrax

这个是Spring的自动参数绑定机制,你可以实现自定义的参数绑定来解决这个问题。
 
1、Order -- 实体类
public class Order {

private String id;

private String detail;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getDetail() {
return detail;
}

public void setDetail(String detail) {
this.detail = detail;
}

@Override
public String toString() {
return "Order{"
"id='" id '\''
", detail='" detail '\''
'}';
}
}
2、IgnoreNull -- 标记注解
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreNull {

}



3、HandlerMethodIgnoreNullArgumentResolver -- 自定义Spring MVC参数绑定器
public class HandlerMethodIgnoreNullArgumentResolver implements HandlerMethodArgumentResolver {

private HandlerMethodArgumentResolver resolver = new ServletModelAttributeMethodProcessor(false);

@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(IgnoreNull.class);
}

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
// 1、获取HttpServletRequest
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);

// 2、获取所有的请求参数
Map<String, String> parameterNames = request.getParameterMap();

if(parameterNames == null || parameterNames.size() == 0){
return null;
}

// 3、获取参数class
Class<?> parameterType = parameter.getParameterType();

// 4、获取内省信息
BeanInfo beanInfo = Introspector.getBeanInfo(parameterType);

// 5、获取属性描述器
PropertyDescriptor propertyDescriptors = beanInfo.getPropertyDescriptors();

boolean requestHasProperty = false;

for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String name = propertyDescriptor.getName();
if("class".equals(name)) {
continue;
}

if(parameterNames.keySet().contains(name)) {
requestHasProperty = true;
break;
}

}

if(requestHasProperty) {
return resolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
}

return null;
}
}
4、CustomWebMvcConfigurer -- 添加自定义参数解析器到Spring MVC
@EnableWebMvc
@Configuration
public class CustomWebMvcConfigurer extends WebMvcConfigurerAdapter {

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new HandlerMethodIgnoreNullArgumentResolver());
}
}
5、SpringBootMybatisApplication -- Spring boot启动类、测试类
@SpringBootApplication
@RestController
public class SpringBootMybatisApplication {

private Logger logger = LoggerFactory.getLogger(SpringBootMybatisApplication.class);

@RequestMapping("ignore")
public String ignore(@IgnoreNull Order order){
logger.info("order value : " order);
return "order value :" order;
}

public static void main(String args) {
SpringApplication.run(SpringBootMybatisApplication.class, args);
}
}
6、测试:

6.1 请求 http://localhost:8080/ignore 
 

111.jpg


 
6.2 请求 http://localhost:8080/ignore?detail=order 
 

222.jpg



 

wayne

赞同来自:

适当调整自己的判断规则也行,如果让框架适应你的需求,并且你需要做很多工作的话,代价太高,你之后谁会懂会动这个代码很难说

要回复问题请先登录注册