SpringMVC -- 梗概--源码--贰--下载

1.配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 前端控制器 
         /=默认的url-pattern
         /a/b/c  /a
         
         /a/d/c
         /a/d
         /a
         /
         *注意:此控制器默认加载/WEB-INF下的xxx-servlet.xml文件
                        :其中xxx等于【DispatcherServlet的配置名】
  -->
  <servlet>
      <servlet-name>mvc62</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:mvc62.xml</param-value>
      </init-param>
      <!-- 随项目启动而启动 -->
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>mvc62</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 专治Post请求参数乱码 -->
  <filter>
      <filter-name>encoding62</filter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      <!-- 将请求的编码方式设置为utf-8 -->
      <init-param>
          <param-name>encoding</param-name>
          <param-value>utf-8</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>encoding62</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

2.配置SpringMVC.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- xmlns:xml name space 是每一个schema唯一标识 -->
<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                              http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                              http://www.springframework.org/schema/context
                              http://www.springframework.org/schema/context/spring-context-3.2.xsd
                              http://www.springframework.org/schema/mvc
                              http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- 扫描所有控制器中的注解 -->
    <context:component-scan base-package="com.c61.controller"></context:component-scan>
    <!-- 
        MVC中基于注解开发,导入注解驱动
        <mvc:annotation-driven/>
     -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <!-- 支持的格式:application/json -->
                        <value>application/json</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!-- 视图解析器:解析视图
         控制器方法的返回值,会被视图解析器捕获。"abc"
         根据捕获的内容,解析出一个视图地址:/abc.jsp
     -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!-- 
        静态资源:html,js,css,jpg
        访问404 解决
     -->
     <mvc:default-servlet-handler/>
     
     <!-- 声明异常处理器 -->
     <bean class="com.c61.ex.resolver.MyExceptionResolver"></bean>
     
     <!-- 拦截器配置 -->
     <!-- 
         /a/b
         inter1
         inter2
         拦截顺序:先配置先拦截
         具体顺序:pre1==pre2==contorller==post2==post1==after2==after1
      -->
     <mvc:interceptors>
         <mvc:interceptor>
             <!-- 定义要拦截的路径 
                  /inter/*  匹配   /inter/a   /inter/b    inter/cssdafasfsafs
                                                  不能匹配/inter/a/b
                 /inter/** 匹配 /inter/a  /inter/xxsjaflsajf   /inter/a/b/c/e/d/xxxcvx
                 *注意:exclude-mapping不能单独使用。要配合mapping使用
                             :在mapping匹配的范围中排除一些个。
             -->
             <mvc:mapping path="/inter/**"/>
             <mvc:mapping path="/a/b"/>
             <mvc:mapping path="/c/**"/>
             <mvc:exclude-mapping path="/inter/test/*"/>
             <mvc:exclude-mapping path="/c/b/**"/>
             <!-- 声明拦截器 -->
             <bean class="com.c61.interceptor.MyInterceptor"/>
         </mvc:interceptor>
         <mvc:interceptor>
             <!-- 定义要拦截的路径 -->
             <mvc:mapping path="/inter/test"/>
             <!-- 声明拦截器 -->
             <bean class="com.c61.interceptor.MyInterceptor2"/>
         </mvc:interceptor>
     </mvc:interceptors>
     <!-- 声明文件上传解析器 
           注意:此解析器,id必须为:multipartResolver
     -->
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
         <!-- 最大允许的上传大小    byte -->
         <property name="MaxUploadSize" value="2097152"></property>
     </bean>
     <!-- 
         注册,验证码生成器
      -->
      <bean id="captcha" class="com.google.code.kaptcha.servlet.KaptchaExtend">
        <constructor-arg>
            <props>  
                <!-- 是否有边框 边框颜色 边框粗细 -->
                <prop key="kaptcha.border">no</prop>  
                <prop key="kaptcha.border.color">105,179,90</prop>  
                <prop key="kaptcha.border.thickness">20</prop>
                <prop key="kaptcha.textproducer.font.color">black</prop>  
                <prop key="kaptcha.image.width">200</prop>  
                <prop key="kaptcha.image.height">50</prop>  
                <prop key="kaptcha.textproducer.font.size">40</prop>  
                <prop key="kaptcha.session.key">code61</prop>  
                <prop key="kaptcha.textproducer.char.length">4</prop>  
                <prop key="kaptcha.textproducer.font.names">Arial,Courier</prop> 
              <!--   <prop key="kaptcha.background.clear.from">black</prop> 
                <prop key="kaptcha.background.clear.to">255,0,0</prop>  -->
            </props>  
        </constructor-arg>
    </bean>
</beans>

3.配置控制器

package com.c61.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/down")
public class DownLoadController {
    //通过MultipartFile接收文件
    @RequestMapping("/test")
    public String testDown(String name,HttpSession s,HttpServletResponse res) throws FileNotFoundException, IOException{
        String path=s.getServletContext().getRealPath("/up61");
        String filePath=path+File.separator+name;
        //如果文件名中有中文:
        String name2=URLEncoder.encode(name, "utf-8");
        System.out.println(name2);
        //设置响应头,实现附件形式下载文件
        res.setHeader("content-disposition", "attachment;filename="+name2);
        //输入流读取所有字节,输出流将所有读取到的字节写出
        IOUtils.copy(new FileInputStream(filePath),res.getOutputStream());
        return null;//如上语句,已经响应了请求,则必须return null;
    }
}

4.配置视图

View : download.jsp

<%@ 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 'index.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>
      <a href="${pageContext.request.contextPath}/down/test?name=html教程全.ppt">免费下载</a>
  </body>
</html>

 

下载 

1 定制超链接

<a href="${pageContext.request.contextPath}/down/test?name=html教程全.ppt">免费下载</a>

2 定制下载的Controller

public String testDown(String name,HttpSession s,HttpServletResponse res) throws FileNotFoundException, IOException{
    String path=s.getServletContext().getRealPath("/up61");
    String filePath=path+File.separator+name;
    //如果文件名中有中文:
    String name2=URLEncoder.encode(name, "utf-8");
    //设置响应头,实现附件形式下载文件(告知浏览器,需要以附件形式接收)
    res.setHeader("content-disposition", "attachment;filename="+name2);
    //输入流读取所有字节,输出流将所有读取到的字节写出
    IOUtils.copy(new FileInputStream(filePath),res.getOutputStream());
    return null;//如上语句,已经响应了请求,则必须return null;
}
posted @ 2017-04-15 23:53  limeOracle  阅读(244)  评论(0编辑  收藏  举报