歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

SpringMVC自定義參數綁定用戶信息

通常,我們會把用戶信息存放在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)
@Documented
public @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>

已經有注釋了,相信應該能看懂。

Copyright © Linux教程網 All Rights Reserved