标签:ann ring hand control mod lan 处理 vco 生效
例:
先创建自定义注解
//
@Target(ElementType.PARAMETER)
//在运行时生效
//RetentionPolicy.RUNTIME 给方法使用
@Retention(RetentionPolicy.RUNTIME)
public @interface CurrentUser {
}
去定义自定义注解的规则
package com.lanou.demo.resolvers;
import com.lanou.demo.annotation.CurrentUser;
import com.lanou.demo.bean.UserBean;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Component
public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {
/*定义一个规则,
*当前的参数解析器可以处理哪个Controller方法的哪个参数
*返回是true 表示对这个参数进行处理
* */
@Override
public boolean supportsParameter(MethodParameter parameter) {
//定义自己的规则
//1.参数被@CurrentUser注解所标记
CurrentUser currentUser
= parameter.getParameterAnnotation(CurrentUser.class);
//2.参数类型为UserBean类型
Class<?> clazz = parameter.getParameterType();
return parameter.hasParameterAnnotation(CurrentUser.class)
&& UserBean.class == clazz;
}
/*如何为这个参数赋值
这个方法的返回值会直接赋值给解析的参数
*/
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
//获取请求
HttpServletRequest req = webRequest.getNativeRequest(HttpServletRequest.class);
//获取session
HttpSession session = req.getSession();
//把user存进session
Object user = session.getAttribute("user");
//返回
return user;
}
}
在xmlzhong把自定义注解配置上
把它改成开放标签
<mvc:annotation-driven/>
例:
<mvc:annotation-driven>
<mvc:argument-resolvers>
<!--配置的哪个类-->
<ref bean="currentUserArgumentResolver"/>
</mvc:argument-resolvers>
</mvc:annotation-driven>
这样就可以使用自定义注解了
@RequestMapping("/insert1")
@ResponseBody
public String insert1(String name, String author, Float price,@CurrentUser UserBean user) {
// 直接在方法的参数中添加形参, 参数名即为前端form中input的name属性
System.out.println(name);
System.out.println(author);
System.out.println(price);
return "insert1";
}
SpringMVC ArgumentREsoler(方法参数解析器)
标签:ann ring hand control mod lan 处理 vco 生效
原文地址:https://www.cnblogs.com/lxx-1843693653/p/10925379.html