day5 - SpringMVC之日期数据转换及文件上传处理

Date类数据类型转化
SpringMVC文件上传的实现
SpringMVC处理Ajax请求

1. Date类数据类型转化

1.1 解决方案1

创建自定义转换器

1.2 @InitBinder注解标识方法并实现目标类型的转换

在Controller中使用@InitBinder注解标识方法并实现目标类型的转换

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.InitBinder;

/**
 * 处理从字符串到日期格式的转换组件,Controller请继承此类
 * @author Administrator
 *
 */
public class CommonsController {

    private String format = "yyyy-MM-dd";
    
    public final String FULL_DATE_TIME_PARALLEL = "yyyy-MM-dd HH:mm:ss";
    public final String FULL_DATE_TIME_BIAS = "yyyy/MM/dd HH:mm:ss";
    public final String FULL_DATE_PARALLEL = "yyyy-MM-dd";
    public final String FULL_DATE_BIAS = "yyyy/MM/dd";
    public final String FULL_TIME_24 = "HH:mm:ss";
    public final String FULL_TIME_12 = "h:m:s";
    
    @InitBinder
    public void initBinderDate(WebDataBinder dataBinder) {  
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);  
        dateFormat.setLenient(false);  
        dataBinder.registerCustomEditor(Date.class, new   
         CustomDateEditor(dateFormat, true));  
    }


    public void setFormat(String format) {
        this.format = format;
    }
}

2. SpringMVC文件上传的实现

使用spring框架实现文件上传:spring实现用户文件上传使用apache软件社区的commons-fileupload-x.x.x.jar和commons-io-x.x.jar,必须在应用中添加这两个jar文件到库目录下

  • 在springmvc之中配置实现文件上传的视图解析器
    <!--配置spring实现文件上传的视图解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--<property name="uploadTempDir" value="/com"/>-->
        <property name="maxUploadSize" value="10000000000"/>
        <property name="maxUploadSizePerFile" value="102400"/>
        <property name="defaultEncoding" value="utf-8"/>
    </bean>
  • 处理文件上传
    /**
     * 使用普通方法处理文件读写到本地
     * @param file
     * @return
     */
    @RequestMapping("fileUpload")
    public ModelAndView fileUpload(@RequestParam("file") MultipartFile file){

        if (file != null){
            System.out.println(file.getSize());
            try {
                Long begin = new Date().getTime();
                InputStream input = file.getInputStream();
                File newFile = new File(path+new Date().getTime()+file.getOriginalFilename());
                OutputStream outputStream = new FileOutputStream(newFile);
                int count = 0;
                byte[] bytes = new byte[1024];
                while ((count = input.read(bytes, 0, bytes.length))!= -1){
                    outputStream.write(bytes,0,count);
                }
                outputStream.close();
                input.close();
                Long end = new Date().getTime();
                System.out.println("the time Using normal way to upload file: "+ (end-begin));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    /**
     * 测试使用spring的方式处理文件读写到本地
     * @param file
     * @return
     */
    @RequestMapping("fileUploadSpring")
    public ModelAndView fileUploadSpring(@RequestParam("file") MultipartFile file){

        if (file != null){
            System.out.println(file.getSize());
            try {
                Long begin = new Date().getTime();
                System.out.println("the fileName: "+file.getOriginalFilename());
                File newFile = new File(path+new Date().getTime()+file.getOriginalFilename());

                file.transferTo(newFile);
                Long end = new Date().getTime();
                System.out.println("the time Using normal way to upload file: "+ (end-begin));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

3. SpringMVC处理Ajax请求

Ajax请求是用户由浏览器页面向服务器处理器组件发出的异步或同步请求从而服务器完成响应后在当前请求页面做出局部刷新,减少等待事件给用户新鲜的体验

SpringMVC模式处理java web用户请求提供了处理Ajax的能力。Spring提供了以相关注释的应用方式处理返回Ajax数据格式(xml, json)以及用注释方式从客户端封装json格式数据为目标java对象

提示: Spring处理AjaxJSON数据转换依赖jackson组件包

3.1 @ResponseBody @RequestBody注释

  • @ResponseBody注释是spring提供的标识在处理方法上,表示本次请求处理请求响应客户端的数据(json)写入到Http Response主体中,主要用来处理Ajax用户请求

  • @RequestBody注释是spring提供的实现,将客户请求的JSON格式参数数据封装为目标java对象,此注释应用在方法参数列表中

@RequestBody的使用
使用@RequestBody注释通常需要HttpMessageCoverter转化器支持

3.1 Spring注解的HandlerAdapter

@ResponseBody的使用
客户端代码:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <script type="text/javascript" src="js/jquery1_7min.js"></script>

    <script type="text/javascript">
      function loadData(){
        $.ajax({
          url:'ajax/testAjaxDataOut.action', // 请求服务器URL
          //url:'ajax/textAjaxDataOutUseResponse.action',
          async:true,
          dataType:'json',// 期待返回的数据类型格式
          cache:true,// 不使用缓存,对get请求方式有作用
          type:'POST',// 请求方法类型
          contentType:'application/x-www-form-urlencoded;charset=UTF-8',// 处理中文
          success:function(datas){// 服务器处理成功返回后回调的函数
            alert(datas.name);
            $("#h3_0").text(datas.name);
            $("#h3_1").text(datas.age);
            $("#h3_2").text(datas.sex);
          },
          error:function(err){// 请求失败出现错误回调的函数
            alert(err);
          }
        });
      }
    </script>
  </head>
  <body>

      <button onclick="loadData()">加载数据</button><br>
      <label>用户名称:</label><span id="h3_0"></span><br>
      <label>用户年龄:</label><span id="h3_1"></span><br>
      <label>用户性别:</label><span id="h3_2"></span><br>

  </body>
</html>

服务器端处理代码:

    @RequestMapping(value = "testAjaxDataOut", produces = "text/json; charset = utf-8")
    @ResponseBody //将返回的字符串JSON数据写入到客户端
    public String textAjaxDataOut(){

        User u = new User();
        u.setName("Rex"); u.setAge(23); u.setSex("male");
        Gson gson = new Gson();
        String jsonUser = gson.toJson(u);
        System.out.println("json内容: "+jsonUser);
        return jsonUser;
    }

3.2 使用HttpServletResponse输出数据

  • 在不使用@ResponseBody注解标识返回数据添加列响应对象并输出,可以直接使用HttpServletResponse获取的文本输出流并输出数据到客户端
  • 为能够处理中文的正常显示,通常应调用HttpServletResponse对象的setContentType方法设置响应的主体内容及编码格式

服务器端处理的代码:

    @RequestMapping(value = "textAjaxDataOutUseResponse")
    public String textAjaxDataOutUseResponse(HttpServletResponse response){

        response.setContentType("text/json;charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            User u = new User();
            u.setName("Rex"); u.setAge(23); u.setSex("male");
            Gson gson = new Gson();
            String jsonUser = gson.toJson(u);

            out.println(jsonUser);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容