SpringMVC学习笔记2

一、日期赋值

目标:在springMVC中日期赋值兼容性更广泛

不能直接处理,必须使用转换器
1、定义转换器,实现接口Converter<From,To>

package com.zy.converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
                                                    //从字符串转日期
public class MyDateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String value) {//参数就是传入的字符串日期
             //1999年6月6日
                //1999-6-6
                //1999.6.6     
                //1999/6/6 默认支持
            // 第一种为例
                //1创建相对应的日期格式化对象
               SimpleDateFormat simpleDateFormat = null;            
               try {
                   if(value.contains("年")){
                       simpleDateFormat= new SimpleDateFormat("yyyy年MM月dd日");
                   }else if(value.contains("-")){
                       simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd");
                   }else if(value.contains(".")){
                       simpleDateFormat= new SimpleDateFormat("yyyy.MM.dd");
                   }else if(value.contains("/")){
                       simpleDateFormat= new SimpleDateFormat("yyyy/MM/dd");
                   }
                  
                   //2把字符串解析成一个日期对象
                Date parse = simpleDateFormat.parse(value);
                   //3返回结果
                return parse;
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                return null;
        }
        
}

2、配置

spring.xml中

 <!-- 2配置日期转换器 -->
   <bean id="formattingConversion" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
   <property name="converters">
   <list>
   <!-- 配置自己的转换器     一个bean就是一个类-->
   <bean class="com.zy.converter.MyDateConverter"></bean>
   </list>
   </property>   
   </bean>
  <!-- 3引用上文的转换器 -->
  <mvc:annotation-driven conversion-service="formattingConversion"></mvc:annotation-driven>

3、Upload上传

1)导包

2)多功能表单

<form action="file/up" method="post" enctype="multipart/form-data"><!-- 多功能表单 -->
头像:<input type="file" name="myfile"/><input type="submit"/>
</form>

3)文件上传解析器

spring.xml

<!-- 4文件上传解析器     id名为multipartResolver,不然可能会报错-->
   <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <property name="maxUploadSize">
   <value>5242880</value> 
   </property>
   </bean>

4)辅助方法+上传文件

@Controller
@RequestMapping("/file")
public class FileController {
//辅助方法
//1根据逻辑路径得到真实路径
    
    
    //过期的
    //@SuppressWarnings(“deprecation”)表示不检测过期的方法
    @SuppressWarnings("deprecation")
    public String myGetRealPath(String path,HttpServletRequest request){
        String realPath = request.getRealPath(path);
        System.out.println("真实路径:"+realPath);
        File file = new File(realPath);
        if(!file.exists()){
            file.mkdirs();
        }
        
        
        return realPath;
    }
    
    //2更改文件名
    public String newFileName(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        //abc.jpg
        //截取后缀,拼接新的文件名
        //后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //新文件名要求:上传中防止文件名重复,发生覆盖
        String uu = UUID.randomUUID().toString();
        
        String newName=uu+substring;
        return newName;
    
    }
    
//    @Test
//  public void test(){
//      System.out.println(UUID.randomUUID());
//  }
    
    //上传--//如果controller只需要跳转页面的话,可以把返回值写成String 不用写成ModelAndView
    @SuppressWarnings("resource")
    @RequestMapping("/up")
    public String up(MultipartFile myfile,HttpServletRequest request)  throws Exception{
        //得到真实路径                                                                 <!--tomcat服务器来给该request赋值-->
        String path="/img";//逻辑路径
        String myGetRealPath = myGetRealPath(path, request);
        //得到新的文件名
        String newFileName = newFileName(myfile);
        
        //上传----把本地文件按流的方式copy到服务器上
        
            //输入流
            InputStream is = myfile.getInputStream();
            //输出流
            FileOutputStream os = new FileOutputStream(myGetRealPath+"/"+newFileName);
            //copy
            IOUtils.copy(is, os);
            request.setAttribute("img",path+"/"+newFileName);
            os.close();
            is.close();
            return "/index.jsp";    
    }

4、下载

//图片下载
    @SuppressWarnings("resource")
    @RequestMapping("/down")
    public void down(HttpServletResponse response,String fileName,HttpServletRequest request) throws Exception {
        //设置头--[下载attachment/预览]
        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
        //下载的本质--文件按流的方式从服务器copy到本地
        //得到资源在服务器的真实路径
        String path="/aaa/"+fileName;
        String myGetRealPath = myGetRealPath(path, request);
        FileInputStream fileInputStream = new FileInputStream(myGetRealPath);
        ServletOutputStream outputStream = response.getOutputStream();
        
        IOUtils.copy(fileInputStream, outputStream);
        fileInputStream.close();
        outputStream.close();
        //下载以后不要跳页面
    }
    

5、ModeAndView

@RequestMapping("/go")
    public ModelAndView go(){
        ModelAndView modelAndView = new ModelAndView();
        //modelAndView分为两个功能-----我们以前见过的
        //model 数据
        //view 视图
        //------
        //存域
        modelAndView.addObject("mydata","880");
        //跳转
        modelAndView.setViewName("/abc.jsp");
        return modelAndView;
    
    
    }

6、视图解析器(便利性)

spring.xml

<!-- 5视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

  <!-- 前缀 --> <property name="prefix" value="/WEB-INF/view/"/> <!-- 后缀 -->
<property name="suffix" value=".jsp"/> </bean>
@RequestMapping("/show")
    public String show(){
        //带视图解析器的跳转
        // /WEB-INF/view/
        //  .jsp
        return "aaa";
    }
    
    @RequestMapping("/mmm")
    public String mmm(){
        
        return "forward:/WEB-INF/mmm/bbb.jsp";//指定响应方式可以摆脱视图解析器
    }

    //----
    ///WEB-INF下的页面不能通过重定向到
    //return "forward:/WEB-INF/mmm/bbb.jsp"   转发
    //return "redirect:bbb.jsp"    重定向
<hr>
文件上传
<form action="${pageContext.request.contextPath}/file/up.action" method="post" enctype="multipart/form-data"><!-- 多功能表单 -->
头像:<input type="file" name="myfile"/><input type="submit"/>
</form>
<img alt="" src="${pageContext.request.contextPath}${img}">
</body>
文件下载
<a href="${pageContext.request.contextPath}/file/down.action?fileName=110.jpg">下载</a>

<a href="${pageContext.request.contextPath}/file/go.action?">跳转</a>

<a href="${pageContext.request.contextPath}/file/show.action?">带视图解析器跳转</a>

<a href="${pageContext.request.contextPath}/file/mmm.action?">带视图解析器跳转2</a>

猜你喜欢

转载自www.cnblogs.com/qfdy123/p/11272333.html
今日推荐