15分钟教你快速整合Spring4+SpringMVC4+Mybatis3+Druid

1        开发环境

eclipse、maven、tomcat8.0、mysql5.7

2        jar包准备

Ø  Spring4+SpringMVC4+Mybatis3+Druid

Ø  Maven依赖

       <!-- Spring Strat -->

       <dependency>

           <groupId>org.aspectj</groupId>

           <artifactId>aspectjweaver</artifactId>

           <version>1.8.8</version>

       </dependency>

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-jdbc</artifactId>

           <version>4.2.5.RELEASE</version>

       </dependency>

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-webmvc</artifactId>

           <version>4.2.5.RELEASE</version>

       </dependency>

       <!-- Spring end -->

       <!-- mybatis start -->

       <dependency>

           <groupId>org.mybatis</groupId>

           <artifactId>mybatis-spring</artifactId>

           <version>1.3.0</version>

       </dependency>

       <dependency>

           <groupId>org.mybatis</groupId>

           <artifactId>mybatis</artifactId>

           <version>3.4.0</version>

       </dependency>

       <!-- mybatis end -->

       <dependency>

           <groupId>com.alibaba</groupId>

           <artifactId>druid</artifactId>

           <version>1.0.28</version>

       </dependency>

       <dependency>

           <groupId>mysql</groupId>

           <artifactId>mysql-connector-java</artifactId>

           <version>5.1.38</version>

       </dependency>

       <dependency>

           <groupId>com.alibaba</groupId>

           <artifactId>fastjson</artifactId>

           <version>1.2.44</version>

       </dependency>

       <dependency>

           <groupId>log4j</groupId>

           <artifactId>log4j</artifactId>

           <version>1.2.17</version>

       </dependency>

       <dependency>

           <groupId>javax.servlet.jsp.jstl</groupId>

           <artifactId>javax.servlet.jsp.jstl-api</artifactId>

           <version>1.2.1</version>

       </dependency>

       <dependency>

           <groupId>taglibs</groupId>

           <artifactId>standard</artifactId>

           <version>1.1.2</version>

       </dependency>

       <dependency>

           <groupId>commons-io</groupId>

           <artifactId>commons-io</artifactId>

           <version>1.3.2</version>

       </dependency>

       <dependency>

           <groupId>commons-fileupload</groupId>

           <artifactId>commons-fileupload</artifactId>

           <version>1.2.2</version>

       </dependency>

3        创建如下包结构

4        创建各个接口与类

Ø  POJO

package com.wskj.pojo;

 

import java.io.Serializable;

import java.util.Date;

 

publicclass User implements Serializable{

    privatestaticfinallongserialVersionUID = 1L;

    private Integer id;

    private String username;

    private String password;

    private String gender;

    private Integer age;

    private String email;

    private Double salary;

    private Integer state;

private String dept;

@DateTimeFormat(pattern="yyyy-MM-dd")

    private Date registTime;

    public Integer getId() {

        returnid;

    }

    publicvoid setId(Integer id) {

        this.id = id;

    }

    public String getUsername() {

        returnusername;

    }

    publicvoid setUsername(String username) {

        this.username = username == null ? null : username.trim();

    }

    public String getPassword() {

        returnpassword;

    }

    publicvoid setPassword(String password) {

        this.password = password == null ? null : password.trim();

    }

    public String getGender() {

        returngender;

    }

    publicvoid setGender(String gender) {

        this.gender = gender == null ? null : gender.trim();

    }

    public Integer getAge() {

        returnage;

    }

    publicvoid setAge(Integer age) {

        this.age = age;

    }

    public String getEmail() {

        returnemail;

    }

    publicvoid setEmail(String email) {

        this.email = email == null ? null : email.trim();

    }

    public Double getSalary() {

        returnsalary;

    }

    publicvoid setSalary(Double salary) {

        this.salary = salary;

    }

    public Integer getState() {

        returnstate;

    }

    publicvoid setState(Integer state) {

        this.state = state;

    }

    public String getDept() {

        returndept;

    }

    publicvoid setDept(String dept) {

        this.dept = dept == null ? null : dept.trim();

    }

    public Date getRegistTime() {

        returnregistTime;

    }

    publicvoid setRegistTime(Date registTime) {

        this.registTime = registTime;

    }

    public User(Integer id, String username, String password, String gender,

           Integer age, String email, Double salary, Integer state,

           String dept, Date registTime) {

       super();

       this.id = id;

       this.username = username;

       this.password = password;

       this.gender = gender;

       this.age = age;

       this.email = email;

       this.salary = salary;

       this.state = state;

       this.dept = dept;

       this.registTime = registTime;

    }

    public User() {

       super();

    }

}

Ø  Service

l  接口:IUserService

import com.wskj.pojo.User;

publicinterface IUserService {

    User getLogin(User user);

}

l  实现类:UserService

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

 

import com.wskj.dao.UserMapper;

import com.wskj.pojo.User;

@Service

publicclass UserService implements IUserService{

    @Autowired

    private UserMapper userMapper;

    @Override

    public User getLogin(User user) {

       User u = userMapper.userLogin(user);

       returnu;

    }

}

Ø  Dao

l  Dao接口

import com.wskj.pojo.User;

publicinterface UserMapper {

    User userLogin(User user);

}

l  Mapper映射文件(与Dao接口同名)

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.wskj.dao.UserMapper">

  <resultMap id="BaseResultMap" type="user">

    <id column="id" jdbcType="INTEGER" property="id" />

    <result column="username" jdbcType="VARCHAR" property="username" />

    <result column="password" jdbcType="VARCHAR" property="password" />

    <result column="gender" jdbcType="VARCHAR" property="gender" />

    <result column="age" jdbcType="INTEGER" property="age" />

    <result column="email" jdbcType="VARCHAR" property="email" />

    <result column="salary" jdbcType="DOUBLE" property="salary" />

    <result column="state" jdbcType="INTEGER" property="state" />

    <result column="dept" jdbcType="VARCHAR" property="dept" />

    <result column="registTime" jdbcType="TIMESTAMP" property="registTime" />

  </resultMap>

  <sql id="Base_Column_List">

    id, username, password, gender, age, email, salary, state, dept, registTime

  </sql>

  <select id="userLogin" resultMap="BaseResultMap">

       select  <include refid="Base_Column_List" /> from user where username=#{username} and password=#{password}

  </select>

</mapper>

Ø  控制层Controller

import javax.servlet.http.HttpSession;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import com.wskj.pojo.User;

import com.wskj.service.IUserService;

 

@Controller

publicclass UserController {

 

    @Autowired

    private IUserService userService;

    @RequestMapping(value="/login",method=RequestMethod.GET)

    public String login(){

       return"login";

    }

    @RequestMapping(value="/login",method=RequestMethod.POST)

    public String checkLogin(User user,HttpSession session){

       User u = userService.getLogin(user);

       if(u!=null){

           session.setAttribute("user",u);

           return"index";

       }else{

           return"redirect:/login";

       }

    }

}

Ø  登录拦截器

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView;

 

import com.wskj.pojo.User;

/**

 *

 * @Description:SpringMVC的登录拦截器

 * @author lzl

 * @Date 201866日下午3:27:58

 */

publicclass LoginInterceptor implements HandlerInterceptor{

 

    /**

     * 预处理回调方法,实现处理器的预处理(如登录检查),第三个参数为响应的处理器(如我们上一章的Controller实现);

        返回值:true表示继续流程(如调用下一个拦截器或处理器);

              false表示流程中断(如登录检查失败),不会继续调用其他的拦截器或处理器,此时我们需要通过response来产生响应;

     */

    @Override

    publicboolean preHandle(HttpServletRequest request,

           HttpServletResponse response, Object handler) throws Exception {

       System.out.println("方法前拦截");

       String uri = request.getRequestURI();//URL是一个完整的请求路径,URIURL的一部分

       if(uri.lastIndexOf("login")>0){//如果是登录我们放行

           returntrue;

       }

       User u=(User) request.getSession().getAttribute("user");//session中获取到登录用户

       if(u!=null){

           //已经登录

           returntrue;

       }

       //跳转到登录页面

       response.sendRedirect(request.getContextPath()+"/WEB-INF/jsp/login.jsp");

       //或者使用转发

       //request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);

       returnfalse;

    }

 

    /**

     * 后处理回调方法,实现处理器的后处理(但在渲染视图之前),

     * 此时我们可以通过modelAndView(模型和视图对象)对模型数据进行处理或对视图进行处理,modelAndView也可能为null

     */

    @Override

    publicvoid postHandle(HttpServletRequest request,

           HttpServletResponse response, Object handler,

           ModelAndView modelAndView) throws Exception {

      

    }

    /**

     * 整个请求处理完毕回调方法,即在视图渲染完毕时回调,如性能监控中我们可以在此记录结束时间并输出消耗时间,还可以进行一些资源清理,

     * 类似于try-catch-finally中的finally,但仅调用处理器执行链中preHandle返回true的拦截器的afterCompletion

     */

    publicvoid afterCompletion(HttpServletRequest request,

           HttpServletResponse response, Object handler, Exception ex)

           throws Exception {

    }

}

 

Ø  登录页面jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8" isELIgnored="false"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>登录页面</title>

</head>

<body>

    <form action="${pageContext.request.contextPath}/login" method="post">

       <table>

           <tr>

              <td>登录名:</td>

              <td><input type="text" name="username"/></td>

           </tr>

           <tr>

              <td>登录名:</td>

              <td><input type="password" name="password"/></td>

           </tr>

           <tr>

              <td></td>

              <td><button>登录</button></td>

           </tr>

          

       </table>

    </form>

</body>

</html>

Ø  静态资源文件所在位置

Ø  登录成功跳转页面index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8" isELIgnored="false"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

<h1>欢迎${user.username }登录成功</h1>

</body>

</html>

 

5        各个配置文件配置

Ø  web.xml配置

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

  <display-name>ssm</display-name>

<!--   Spring的配置 -->

    <context-param>

       <param-name>contextConfigLocation</param-name>

       <param-value>classpath:applicationContext.xml</param-value>

    </context-param>

    <!-- 编码过滤器 -->

    <filter>

       <filter-name>encoding</filter-name>

       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

       <init-param>

           <param-name>encoding</param-name>

           <param-value>utf-8</param-value>

       </init-param>

    </filter>

    <filter-mapping>

       <filter-name>encoding</filter-name>

       <url-pattern>/*</url-pattern>

    </filter-mapping>

    <!-- 监听器 -->

    <listener>

       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

    </listener>

   

    <!-- SPring MVC配置 -->

    <servlet>

       <servlet-name>springmvc</servlet-name>

       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

       <init-param>

           <param-name>contextConfigLocation</param-name>

           <param-value>classpath:springMVC.xml</param-value>

       </init-param>

       <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>

       <servlet-name>springmvc</servlet-name>

       <!--   restful风格 -->

       <url-pattern>/</url-pattern>

    </servlet-mapping>

</web-app>

Ø  applicationContext-tx.xml配置

<?xml version="1.0" encoding="UTF-8"?>

<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:aop="http://www.springframework.org/schema/aop"

        xmlns:tx="http://www.springframework.org/schema/tx"

        xsi:schemaLocation="http://www.springframework.org/schema/beans

        http://www.springframework.org/schema/beans/spring-beans.xsd

        http://www.springframework.org/schema/context

        http://www.springframework.org/schema/context/spring-context.xsd

        http://www.springframework.org/schema/aop

        http://www.springframework.org/schema/aop/spring-aop.xsd

        http://www.springframework.org/schema/tx

        http://www.springframework.org/schema/tx/spring-tx.xsd">

  <!--   事务管理器 -->

  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

           <!-- 管理数据源 -->

       <property name="dataSource" ref="dataSource"></property>

  </bean>

  <!-- 通知 -->

  <tx:advice id="txAdvice" transaction-manager="transactionManager">

       <!-- 事务的传播行为 -->

       <tx:attributes>

           <!-- 必须开启事务 -->

           <tx:method name="add*" propagation="REQUIRED"/>

           <tx:method name="save*" propagation="REQUIRED"/>

           <tx:method name="update*" propagation="REQUIRED"/>

           <tx:method name="modify*" propagation="REQUIRED"/>

           <tx:method name="delete*" propagation="REQUIRED"/>

           <tx:method name="remove*" propagation="REQUIRED"/>

           <!-- 只读事务 -->

           <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>

           <tx:method name="query*" propagation="SUPPORTS" read-only="true"/>

           <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>

           <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>

       </tx:attributes>

  </tx:advice>

<!--   配置切面 -->

<aop:config>

    <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.wskj.service..*.*(..))"/>

</aop:config>

</beans>

Ø  数据源配置:druid.properties

#数据库驱动如果不配置,系统会根据url自动识别

#driverClassName=com.mysql.jdbc.Driver

#URL

druid.url=jdbc:mysql://127.0.0.1:3306/t150

#用户名

druid.username=root

#密码

druid.password=root

filters=stat

initialSize=2

#最大连接池数量

maxActive=300

#获取连接时最大等待时间,单位毫秒

maxWait=60000

#Destroy线程会检测连接的间隔时间

timeBetweenEvictionRunsMillis=60000

minEvictableIdleTimeMillis=300000

#用来检测连接是否有效的sql,要求是一个查询语句

validationQuery=SELECT1

#建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,

#如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。

testWhileIdle=true

#申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。

testOnBorrow=false

#归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能

testOnReturn=false

#是否缓存preparedStatement,也就是PSCachePSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。

poolPreparedStatements=false

maxPoolPreparedStatementPerConnectionSize=200

Ø  日志文件log4j.properties配置

# Global logging configuration

log4j.rootLogger=DEBUG,stdout

# Console output...

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%5p[%t]-%m%n

Ø  Mybatis逆向工程配置文件generatorConfig.xml(要想使用此文件需要安装mybatis的插件)

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >

<generatorConfiguration >

    <!-- 指定数据连接驱动jar地址 --> 

    <classPathEntry location="E:\appsource\maven\resporstory\mysql\mysql-connector-java\5.1.38\mysql-connector-java-5.1.38.jar" /> 

    <!-- 一个数据库一个context --> 

    <context id="infoGuardian"> 

        <!-- 注释 --> 

        <commentGenerator > 

            <property name="suppressAllComments" value="true"/><!-- 是否取消注释   设置为true 取消注释 --> 

            <property name="suppressDate" value="true" /><!-- 是否生成注释代时间戳--> 

        </commentGenerator> 

         

        <!-- jdbc连接 --> 

        <jdbcConnection driverClass="com.mysql.jdbc.Driver" 

            connectionURL="jdbc:mysql://127.0.0.1:3306/t150"

           userId="root" 

            password="root" /> 

         

        <!-- 类型转换 --> 

        <javaTypeResolver> 

            <!-- 是否使用bigDecimal false可自动转化以下类型(Long, Integer, Short, etc. --> 

            <property name="forceBigDecimals" value="false"/> 

        </javaTypeResolver> 

         

        <!-- 生成实体类地址 -->   

        <javaModelGenerator targetPackage="com.wskj.pojo" 

            targetProject="ssm" > 

            <!-- 是否在当前路径下新加一层schema,egfase路径com.oop.eksp.user.model true:com.oop.eksp.user.model.[schemaName] --> 

            <property name="enableSubPackages" value="false"/> 

            <!-- 是否针对string类型的字段在set的时候进行trim调用 --> 

            <property name="trimStrings" value="true"/> 

        </javaModelGenerator> 

         

        <!-- 生成mapxml文件 --> 

        <sqlMapGenerator targetPackage="com.wskj.dao"

            targetProject="ssm" > 

            <!-- 是否在当前路径下新加一层schema,egfase路径com.oop.eksp.user.model true:com.oop.eksp.user.model.[schemaName] --> 

            <property name="enableSubPackages" value="false" /> 

        </sqlMapGenerator> 

         

        <!-- 生成mapxml对应client,也就是接口dao -->     

        <javaClientGenerator targetPackage="com.wskj.dao"

            targetProject="ssm" type="XMLMAPPER" > 

            <!-- 是否在当前路径下新加一层schema,egfase路径com.oop.eksp.user.model true:com.oop.eksp.user.model.[schemaName] --> 

            <property name="enableSubPackages" value="false" /> 

        </javaClientGenerator> 

         

       <!--  配置表信息  

        <table schema="${jdbc_user}" tableName="s_user" 

            domainObjectName="UserEntity" enableCountByExample="false" 

            enableDeleteByExample="false" enableSelectByExample="false" 

            enableUpdateByExample="false"> 

            schema即为数据库名

            tableName为对应的数据库表

    domainObjectName是要生成的实体类 enable*ByExample  

                                                是否生成 example   

             

            忽略列,不生成bean 字段 

            <ignoreColumn column="FRED" /> 

            指定列的java数据类型 

            <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> 

        </table>  -->

            <table schema="t150" tableName="stuinfo" 

            domainObjectName="StuInfo" enableCountByExample="false" 

            enableDeleteByExample="false" enableSelectByExample="false" 

            enableUpdateByExample="false"> 

            <!-- schema即为数据库名

             tableName为对应的数据库表

             domainObjectName是要生成的实体类

             enable*ByExample 是否生成 example   -->           

            <!-- 指定列的java数据类型 --> 

            <property name="useActualColumnNames" value="true"/>

        </table>

    </context> 

</generatorConfiguration>

Ø  Mybatis全局配置文件SqlMapConfig.xml配置

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE configuration

PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <typeAliases>

       <!-- 给实体类指定别名 -->

       <package name="com.wskj.pojo"/>

    </typeAliases>

</configuration>

Ø  Spring全局配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<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:aop="http://www.springframework.org/schema/aop"

        xmlns:tx="http://www.springframework.org/schema/tx"

        xsi:schemaLocation="http://www.springframework.org/schema/beans

        http://www.springframework.org/schema/beans/spring-beans.xsd

        http://www.springframework.org/schema/context

        http://www.springframework.org/schema/context/spring-context.xsd

        http://www.springframework.org/schema/aop

        http://www.springframework.org/schema/aop/spring-aop.xsd

        http://www.springframework.org/schema/tx

        http://www.springframework.org/schema/tx/spring-tx.xsd">

      <!--  导入事务配置文件 -->

      <import resource="applicationContext-tx.xml"/>

      <!--   配置注解扫描 -->

      <context:component-scan base-package="com.wskj">

            <!-- 不扫描带@Controller的注解 -->

           <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>

      </context:component-scan>

     <!--   加载外部配置文件 -->

     <context:property-placeholder location="classpath:druid.properties"/>

    <!--  配置数据源 -->

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">

          <property name="username" value="${druid.username}"></property>

          <property name="password" value="${druid.password}"></property>

          <property name="url" value="${druid.url}"></property>

          <property name="initialSize" value="${initialSize}"></property>

          <property name="maxWait" value="${maxWait}"></property>

          <property name="maxActive" value="${maxActive}"></property>

    </bean>

   <!--  配置SqlSessionFactory -->

   <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">

           <!-- 配置数据源 -->

           <property name="dataSource" ref="dataSource"></property>

           <!-- 加载mybatis全局配置文件 -->

           <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>

   </bean>

   <!--    配置xxxx.mapper.xml文件的扫描 -->

   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

        <!-- 扫描包的路径接口名称必须和Mapper映射文件名称保持一致 -->

        <property name="basePackage" value="com.wskj.dao"></property>

   </bean>

</beans>

Ø  SpringMVC的配置文件:springMVC.xml

<?xml version="1.0" encoding="UTF-8"?>

<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

    xmlns:mvc="http://www.springframework.org/schema/mvc"

    xsi:schemaLocation="http://www.springframework.org/schema/beans

        http://www.springframework.org/schema/beans/spring-beans.xsd

        http://www.springframework.org/schema/context

        http://www.springframework.org/schema/context/spring-context.xsd

        http://www.springframework.org/schema/aop

        http://www.springframework.org/schema/aop/spring-aop.xsd

        http://www.springframework.org/schema/tx

        http://www.springframework.org/schema/tx/spring-tx.xsd

        http://www.springframework.org/schema/mvc

        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

 

<!--   扫描controller -->

<context:component-scan base-package="com.wskj.controller"></context:component-scan>

 

<!-- 注解驱动相当于配置了处理器映射器和处理器适配器 -->

<mvc:annotation-driven>

    <mvc:message-converters>

       <!-- 配置json的支持 -->

       <bean id="jsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">

           <property name="charset" value="utf-8"></property>

           <property name="supportedMediaTypes">

              <list>

                  <value>application/json;charset=utf-8</value>

                  <value>text/html;charset=utf-8</value><!-- 防止IE浏览器去当作JSON格式的文件下载 -->

              </list>

           </property>

       </bean>

    </mvc:message-converters>

</mvc:annotation-driven>

<!-- 视图解析器 -->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

    <property name="prefix" value="/WEB-INF/jsp/"></property>

    <property name="suffix" value=".jsp"></property>

</bean>

<!-- 文件上传解析配置 -->

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- 配置文件的编码 -->

    <property name="defaultEncoding" value="utf-8"></property>

    <!-- 设置上传文件的大小 -->

    <property name="maxUploadSize" value="10240000"></property>

</bean>

<!-- 静态资源放行 -->

<mvc:resources location="/static" mapping="/**"></mvc:resources>

<!-- 另外一种静态资源的放行方式 -->

<!-- <mvc:default-servlet-handler/> -->

 

<!-- 拦截器配置 -->

<mvc:interceptors>

    <mvc:interceptor>

       <mvc:mapping path="/**"/>

       <bean class="com.wskj.interceptor.LoginInterceptor"></bean>

    </mvc:interceptor>

</mvc:interceptors>

</beans>

 


  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值