springmvc上传文件

SSM整合

  1. 修改web.xml文件

<!-- Spring配置  spring容器,dao,service层-->
    <!-- 当系统启动的时候,spring需要进行一些资源加载或者配置,都需要使用此监听去做 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- spring容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

SpringMVC访问静态文件

    <!--静态资源-->
    <mvc:resources mapping="/statics/**" location="/statics/"/>

mapping:将静态资源映射到指定的路径下 location:本地静态资源文件所在的目录

数据格式化

  1. 实现方式

    • 接口方式:org.springframework.format.Formatter

    • 注解方式:org.springframework.format.AnnotationFormatterFactory

  2. 内置API

    • @DateTimeFormat

    • @NumberFormat

  3. 全局注册

    • Java configuration

    • XML-based configuration

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="registerDefaultFormatters" value="false" />
        <property name="formatters">
            <set>
                <bean class="org.springframework.format.number.NumberFormatAnnotationFormatterFactory" />
                <bean class="org.springframework.format.datetime.DateFormatter" p:pattern="yyyy-MM-dd" />
            </set>
        </property>
        <property name="formatterRegistrars">
            <set>
                <bean class="org.springframework.format.datetime.standard.DateTimeFormatterRegistrar">
                    <property name="dateFormatter">
                        <bean class="org.springframework.format.datetime.standard.DateTimeFormatterFactoryBean">
                            <property name="pattern" value="yyyyMMdd"/>
                        </bean>
                    </property>
                </bean>
            </set>
        </property>
    </bean>
  1. <mvc:annotation-driven conversion-service="conversionService"/>

  2. 日期默认情况下转换失败

HTTP Status 400 – Bad Request

文件上传

配置解析器

在springmvc配置文件中配置

   <!-- 文件上传 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件的最大尺寸为5MB -->
        <property name="maxUploadSize">
            <value>5242880</value>
        </property>
    </bean>
  1. 但是在这里你必须保证 id 是 multipartResolver,原因是在 SpringMVC 的核心类 DispatcherServlet 中,把这 bean 的 id 固定

  2. SpringMVC 中,文件的上传,是通过 MultipartResolver 实现的。 所以,如果要实现文件的上传,只要在 spring-mvc.xml 中注册相应的 MultipartResolver 即可

  3. MultipartResolver 的实现类有两个:

    1. CommonsMultipartResolver

      需要使用 Apache 的 commons-fileupload 等 jar 包支持,但它能在比较旧的 servlet 版本中使用

    2. StandardServletMultipartResolver

      不需要第三方 jar 包支持,它使用 servlet 内置的上传功能,但是只能在 Servlet 3 以上的版本使用

pom.xml

CommonsMultipartResolver解析器依赖commons-fileupload和commons-io

<!-- apache 文件上传 -->
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.3</version>
</dependency>

文件上传

controller

@Controller
@RequestMapping("/demo3")
public class UploadController {
    @RequestMapping("/to_upload")
    public String to_upload(){
        return "upload";
    }
    @RequestMapping("/upload")
    public String upload(User user,MultipartFile pictureFile, HttpSession session){
        //普通元素
        if (user!=null)
            System.out.println(user.getUserName());
        //得到原文件名
        String oldName = pictureFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."));
        System.out.println(newName);
​
        ///statics/upload是web资源路径,path:在服器实际位置
        String path = session.getServletContext().getRealPath("/statics/upload");
        System.out.println(path);
        path = path+"/"+newName;
​
        File file = new File(path);
        try{
            //保存文件
            pictureFile.transferTo(file);
        }catch (Exception ex){
            ex.printStackTrace();
        }
​
        return "upload";
    }
}

jsp页面

<form action="add"  method="post" enctype="multipart/form-data">
    <input type="text" name="name" />
    <input type="file" name="pictureFile" />
    <input type="submit" value="保存">
</form>

Spring表单标签

实体类

public class FormPojo {
    private Integer id; //编号
    private String name;//姓名
    private String[] loves;//爱好
    private List<String>  source;//来源
    private String sex;//性别
    private String cityId;//城市
    //省略get/set
}

controller

@Controller
@RequestMapping("/form")
public class FormController {
    @RequestMapping("/add")
    public String add(@ModelAttribute("user") User user , Model model){
        String[] allLoves = {"吃饭","睡觉","打豆豆"};
        List<String> allSource = new ArrayList<>();
        allSource.add("网络");
        allSource.add("报纸");
        List<City> cityList = new ArrayList<>();
        cityList.add(new City(1,"长沙"));
        cityList.add(new City(2,"湘潭"));
        model.addAttribute("allLoves",allLoves);
        model.addAttribute("allSource",allSource);
        model.addAttribute("cityList",cityList);
        return "form_add";
    }
}

jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <title>spring mvc 表单标签</title>
</head>
<body>
<h2>用户注册</h2>
<sf:form action="add" modelAttribute="user" method="post">
    <p>编号:<sf:input path="id"/></p>
    <p>姓名:<sf:input path="name"/></p>
    <p>爱好:<sf:checkboxes path="loves" items="${allLoves}"/></p>
    <p>来源:<sf:checkboxes path="source" items="${allSource}"/></p>
    <p>性别:<sf:radiobuttons path="sex" items="${['男','女']}" /> </p>
    <p>城市:<sf:select path="cityId" items="${cityList}" itemLabel="name" itemValue="id"/></p>
    <p><input type="submit" value="提交"></p>
</sf:form>
</body>
</html>

修改web.xml文件,乱码问题

 <filter>
        <filter-name>charset</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>charset</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值