代码改变世界

springMVC+spring+mybatis整合(包括文件上传和下载)

2017-02-21 08:58  甘雨路  阅读(1507)  评论(0编辑  收藏  举报
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
user=LF
pwd=LF
<?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:p="http://www.springframework.org/schema/p" 
       xmlns:tx="http://www.springframework.org/schema/tx" 
       xmlns:aop="http://www.springframework.org/schema/aop" 
       xmlns:context="http://www.springframework.org/schema/context" 
       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">
    
    <!-- 配置引用外部文件 -->
    <context:property-placeholder location="/WEB-INF/config/jdbc.properties"/>
    
    <!-- 配置包扫描 -->
    <context:component-scan base-package="cn.zr"></context:component-scan>

    <!-- 开启动态代理 -->
     <aop:aspectj-autoproxy/>
    <!-- 配置事务属性 -->
    <tx:advice id="advice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 所有已get开头的方法都是只读,换句话说,get开始的方法不参与事务-->
            <tx:method name="get*" read-only="true" />
            <tx:method name="*" rollback-for="java.lang.Throwing" />
        </tx:attributes>
    </tx:advice>
    
    <aop:config>
        <!-- 配置切点 -->
        <aop:pointcut expression="execution(* cn.zr.pringmvctest.service.impl.*.*(..))" id="pointcut"/>
        <aop:advisor advice-ref="advice" pointcut-ref="pointcut" />
    </aop:config>

    <!-- 配置数据源 -->
    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${pwd}"/>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!-- mybatis配置 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="/WEB-INF/config/mybatis-config.xml"/>
        <property name="typeAliasesPackage" value="cn.zr.pringmvctest.pojo"/>
        <property name="mapperLocations">
            <list>
                <value>classpath:cn/zr/pringmvctest/mapper/xml/*Mapper.xml</value>
            </list>
        </property>
    </bean>
    
    <!-- mybatis 扫描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.zr.pringmvctest.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
</beans>





    
    
    
<?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>

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

    <!-- 配置包扫描 -->
    <context:component-scan base-package="cn.zr"/>
    
    <!-- 注解驱动 -->
    <mvc:annotation-driven/>

    <!-- 拦截器 -->
    <bean id="handler" class="cn.zr.pringmvctest.hander.TestHander"></bean>
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/lf*"/>
            <ref bean="handler"/>
        </mvc:interceptor>
    </mvc:interceptors>

    <!-- SpringMVC视图解析器 --> 
    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
    <!-- org.springframework.web.multipart.commons.CommonsMultipartResolver.class commonsMultipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 文件上传文件最大大小,单位byte -->
        <property name="maxUploadSize" value="1200000000" />
    </bean>

</beans>     
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
<?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="cn.zr.pringmvctest.mapper.UserMapper">
    <!-- 配置数据库字段与实体类属性一一对应 -->
    <resultMap type="cn.zr.pringmvctest.pojo.User" id="userMap">
        <id column="name" property="username"/>
        <result column="password" property="password"/>
    </resultMap>
    
    <!-- 查询所有用户 -->
    <select id="getAllUsers" resultMap="userMap">
        SELECT name,password FROM user
    </select>
    
</mapper> 
  
  
  
  
  
package cn.zr.pringmvctest.pojo;

import java.util.Date;

public class User {
    
    private String username;
    private String password;
    private Date date;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
    public User() {
    }
    public User(String username, String password, Date date) {
        this.username = username;
        this.password = password;
        this.date = date;
    }
    @Override
    public String toString() {
        return "User [username=" + username + ", password=" + password
                + ", date=" + date + "]";
    }
    
    
    
}
package cn.zr.pringmvctest.mapper;

import java.util.List;

import org.springframework.stereotype.Repository;

import cn.zr.pringmvctest.pojo.User;

@Repository
public interface UserMapper {

    /**
     * 获取所有用户
     * @return 用户集合
     */
    public List<User> getAllUsers();

}
package cn.zr.pringmvctest.hander;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
 * 拦截器
 * @author lf
 *
 */

public class TestHander implements HandlerInterceptor{

    @Override
    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        System.out.println("afterCompletion...");
        
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
        System.out.println("postHandle...");        
    }

    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2) throws Exception {
        System.out.println("preHandle...");        
        return true;
    }

}
package cn.zr.pringmvctest;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;

public class SuperController {
    
    /**
     * 设置错误默认视图
     */
    private static String error_view="error";
    
    /**
     * 设置日期转换格式
     */
    @InitBinder
    public void binder(WebDataBinder binder){
        System.out.println("进入binder方法...");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        format.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format, false));
    }
    
    /**
     * 异常处理
     */
    @ExceptionHandler(Exception.class)
    public String handlerException(Exception exception) {
        //将控制台数据的错误信息输出到StringWriter
        StringWriter sw = new StringWriter();
        System.out.println("==="+sw.toString()+"===");
        exception.printStackTrace(new PrintWriter(sw));
        
        // 可以在此将异常存到服务器
        
        return error_view;
    }


    public static void setError_view(String error_view) {
        SuperController.error_view = error_view;
    }
    
}
package cn.zr.pringmvctest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
 * 其他描述:
 * 1、拦截器      --------   
 * 2、异常处理
 * 3、文件上传
 * 4、集成
 * 
 */
@Controller
/*@RequestMapping("/login")*/
public class TestController {

    /**
     * 拦截请求的映射路径
     */
    @RequestMapping(value="/lf",method=RequestMethod.GET)
    public String getInfo(){
        return "test";
    }
    
    
}
package cn.zr.pringmvctest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class UploadController {

    
    @RequestMapping(value="/upload",method=RequestMethod.GET)
    public String upload() {
        return "upload";
    }
}
package cn.zr.pringmvctest;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadhandlerController {

    @RequestMapping(value="/uploadhandler")
    public String handlerFile(@RequestParam("image")MultipartFile img,HttpServletRequest request) {
        System.out.println("上传图片......");
        //进行文件上传
        String path = request.getServletContext().getRealPath("/");
        System.out.println(path);
        
        try {
            img.transferTo(new File(path+(int)(Math.random()*10000000)+img.getName()));
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }
}
package cn.zr.pringmvctest;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.zr.pringmvctest.pojo.User;
import cn.zr.pringmvctest.service.UserService;

@Controller
public class UserController extends SuperController{
    
    @Resource
    private UserService userService;
    
    @RequestMapping(value="/login",method=RequestMethod.POST)
    public String getInfo(@RequestParam("username")String username,User user, HttpServletRequest request) {
        
        System.out.println(user);
        System.out.println(userService);
        //取数据
        List<User> users = userService.getAllUsers();
        for (User user2 : users) {
            System.out.println(user2);
        }
        // 将数据存入session
        request.getSession().setAttribute("users", users);
        //如果没有获取到数据,就去相应页面
        if (users.isEmpty() || users.size() == 0) {
            return "test";
        }
        
        return "list";
    }
}
package cn.zr.pringmvctest.service;

import java.util.List;

import cn.zr.pringmvctest.pojo.User;

public interface UserService {

    /**
     * 获取所有用户
     * @return 用户集合
     */
    List<User> getAllUsers();

}
package cn.zr.pringmvctest.service.impl;

import java.util.List;

import javax.annotation.Resource;

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

import cn.zr.pringmvctest.mapper.UserMapper;
import cn.zr.pringmvctest.pojo.User;
import cn.zr.pringmvctest.service.UserService;

@Service
public class UserServiceImpl implements UserService {
    
    @Resource
    private UserMapper userMapper;
    
    @Override
    public List<User> getAllUsers() {
        System.out.println("userMapper"+userMapper);
        return userMapper.getAllUsers();
    }

}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  
    
    <title>用户信息</title>
   

  </head>
  
  <body>
    
    <table>
        <tr>
            <th>用户名</th>
            <th>密码</th>
        </tr>
        
        <c:forEach items="${sessionScope.users }" var="user">
            <tr>
                <td>${user.username }</td>
                <td>${user.password }</td>
            </tr>
        </c:forEach>

        
    </table>

        <p>

  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'ok.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
        上传成功
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    
    <title>测试页面</title>
    

  </head>
  
  <body>
    <h1>欢迎进入测试页面!</h1> 
       
    <form action="login.test" method="post" >
        用户:<input type="text" name="username"><br><br>
        密码:<input type="password" name="password"><br><br>
        日期:<input type="text" name="date"><br><br>
        <input type="submit" value="提交">
    </form>
    
    <br><br><br><br><br>
    <a href="upload.test">上传文件页面</a>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>上传页面</title>

  </head>
  
  <body>
        <form action="uploadhandler.test" method="post" enctype="multipart/form-data">
            文件说明:<input type="text" name="text"><br><br>
            上传:<input type="file" name="image"><br><br>
            <input type="submit" name="提交">
        </form>
  </body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
id="WebApp_ID" version="3.0">
  

    <!-- 配置springmvc核心 Servlet-->
    <servlet>
        <servlet-name>pringmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置文件加载的路径 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config/spring_mvc.xml</param-value>
        </init-param>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>pringmvc</servlet-name>
        <url-pattern>*.test</url-pattern>
    </servlet-mapping>
    <!-- END 配置springmvc核心 Servlet-->
    
    <!-- 配置过滤器 -->
    <filter>
        <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- END 配置过滤器 -->
    
    <!-- 配置spring的路径 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/config/applicationContext.xml</param-value>
    </context-param>
    
    <!-- org.springframework.web.context.ContextLoaderListener.class 配置Spring监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- END 监听器 -->
    
    
    
    

</web-app>