现在的位置: 首页 > 操作系统 > 正文

SpringMVC自定义参数绑定用户信息

2020年02月10日 操作系统 ⁄ 共 7219字 ⁄ 字号 评论关闭

通常,我们会把用户信息存放在session里面作为一个属性。就像这样。session.setAttribute(“userinfo”,userinfo)。但是这样做每次在方法前必须要先从request中获取值,这样很麻烦。但是通过spring的自定义的参数绑定可以通过自定义注解的方式来绑定参数,直接将userinfo作为参数来获取。以下是相关代码和文件配置。

1.定义一个自定义注解。这里我的注解名为:RequestAttribute。

package com.etoak.annotation;import Java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.PARAMETER)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface RequestAttribute { String value();}

继承spring 的HandlerMethodArgumentResolver,通过重写supportParameter()方法和resolverArgument()方法对参数注入。

package com.etoak.core;import org.springframework.core.MethodParameter;import org.springframework.web.bind.support.WebDataBinderFactory;import org.springframework.web.context.request.NativeWebRequest;import org.springframework.web.context.request.WebRequest;import org.springframework.web.method.support.HandlerMethodArgumentResolver;import org.springframework.web.method.support.ModelAndViewContainer;import com.etoak.annotation.RequestAttribute;public class RequestAttributeMethodResolver implements HandlerMethodArgumentResolver{ /** * 检查解析器是否支持解析改参数 */ public boolean supportsParameter(MethodParameter parameter) { return parameter.getParameterAnnotation(RequestAttribute.class) != null; } public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { // TODO Auto-generated method stub// if(parameter.getParameterType()!=null&&parameter.getParameterType().equals(UserInfo.class)){// HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);// UserInfo userinfo = (UserInfo)request.getAttribute(Const.SESSION_USER);// return userinfo;// }else{// return "没有成功";// } RequestAttribute attr = parameter.getParameterAnnotation(RequestAttribute.class); return webRequest.getAttribute(attr.value(), WebRequest.SCOPE_REQUEST); }}

最后需要在spring-mvc的配置文件中配置这个bean。把它交给容器管理。 为了更全面看。我把整个文件都拉出来了。

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"> <!-- 引入属性文件 --> <bean id="propertyConfigure2" class="com.etoak.core.CustomizedPropertyConfigurer"> <property name="fileEncoding" value="UTF-8" /> <property name="locations"> <list> <value>classpath:jdbc.properties</value> <value>classpath:config.properties</value> </list> </property> </bean><!-- 配置扫描注册controller --><context:component-scan base-package="com.etoak.*"></context:component-scan> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="synchronizeOnSession" value="true"></property> <property name="messageConverters"> <util:list id="beanList"> <ref bean ="mappingJacksonHttpMessageConverter"/> </util:list> </property> <!-- 自定义参数解析器 --> <property name="customArgumentResolvers"> <list> <!-- 支持@RequestAttribute注解参数的绑定 --> <bean class="com.etoak.core.RequestAttributeMethodResolver"/> </list> </property></bean> <!-- 启动springMVC的注解功能,完成POJO扫描 --><mvc:annotation-driven /><!-- 上传文件 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8" /> <property name="maxInMemorySize" value="4096000" /> <property name="maxUploadSize" value="10485760000"/></bean><!-- spring视图解析器 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/pages/"></property> <property name="suffix" value=".jsp"></property></bean> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <!-- 登录的URL不拦截 --> <mvc:exclude-mapping path="/index.do"/> <mvc:exclude-mapping path="/loginsubmit.do"/> <bean class="com.etoak.Interceptor.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors> <!-- 避免IE在ajax请求时,返回json出现下载 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <!--先不配置,采用默认配置--> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean><!-- 配置数据源 --><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="initialSize" value="2" /> <property name="minIdle" value="1" /> <property name="maxActive" value="20" /> <!-- 配置获取连接的等待时间 --> <property name="maxWait" value="30000"></property> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="testWhileIdle" value="true" /> <!-- 这里建议配置为TRUE,防止取到的连接不可用 --> <property name="testOnBorrow" value="true" /> <property name="testOnReturn" value="false" /> <property name="proxyFilters"> <list> <ref bean="logFilter" /> </list> </property> <property name="filters" value="log4J" /></bean><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations"> <list> <value>classpath:mybatis/*.xml</value> <value>classpath:mybatis/cus/mysql/*.xml</value> </list> </property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.etoak.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean><bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /></bean><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /></bean><bean id="logFilter" class="com.alibaba.druid.filter.logging.Log4jFilter"> <property name="resultSetLogEnabled" value="true" /></bean><!-- 慢sql记录 --><bean id="statfilter" class="com.alibaba.druid.filter.stat.StatFilter"> <!-- 开启慢查询语句,1秒 --> <property name="slowSqlMillis" value="1000" /> <property name="logSlowSql" value="true" /></bean></beans>

已经有注释了,相信应该能看懂。

本文永久更新链接地址:http://www.xuebuyuan.com/Linux/2017-01/139676.htm

以上就上有关SpringMVC自定义参数绑定用户信息的全部内容,学步园全面介绍编程技术、操作系统、数据库、web前端技术等内容。

抱歉!评论已关闭.