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>
6、url-pattern
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>springmvc01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <!-- 配置前端控制器 -->
<servlet>
<servlet-name>aaa</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加载配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value><!-- 配置文件的位置 classpath代表src -->
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>aaa</servlet-name>
<url-pattern>*.action</url-pattern><!-- 拦截规则 --><!-- 后缀拦截 拦截以action结尾的请求-->
</servlet-mapping> <!-- / /* /*范围更广,包括jsp的拦截 --> <!-- 配置编码过滤器 -->
<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> </web-app>
SpringMVC学习笔记2的更多相关文章
- 史上最全的SpringMVC学习笔记
SpringMVC学习笔记---- 一.SpringMVC基础入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于Spring ...
- springmvc学习笔记--REST API的异常处理
前言: 最近使用springmvc写了不少rest api, 觉得真是一个好框架. 之前描述的几篇关于rest api的文章, 其实还是不够完善. 比如当遇到参数缺失, 类型不匹配的情况时, 直接抛出 ...
- springmvc学习笔记---面向移动端支持REST API
前言: springmvc对注解的支持非常灵活和飘逸, 也得web编程少了以往很大一坨配置项. 另一方面移动互联网的到来, 使得REST API变得流行, 甚至成为主流. 因此我们来关注下spring ...
- SpringMVC:学习笔记(8)——文件上传
SpringMVC--文件上传 说明: 文件上传的途径 文件上传主要有两种方式: 1.使用Apache Commons FileUpload元件. 2.利用Servlet3.0及其更高版本的内置支持. ...
- springmvc学习笔记(简介及使用)
springmvc学习笔记(简介及使用) 工作之余, 回顾了一下springmvc的相关内容, 这次也为后面复习什么的做个标记, 也希望能与大家交流学习, 通过回帖留言等方式表达自己的观点或学习心得. ...
- springmvc学习笔记(常用注解)
springmvc学习笔记(常用注解) 1. @Controller @Controller注解用于表示一个类的实例是页面控制器(后面都将称为控制器). 使用@Controller注解定义的控制器有如 ...
- SpringMVC学习笔记之二(SpringMVC高级参数绑定)
一.高级参数绑定 1.1 绑定数组 需求:在商品列表页面选中多个商品,然后删除. 需求分析:功能要求商品列表页面中的每个商品前有一个checkbok,选中多个商品后点击删除按钮把商品id传递给Cont ...
- springmvc学习笔记(13)-springmvc注解开发之集合类型參数绑定
springmvc学习笔记(13)-springmvc注解开发之集合类型參数绑定 标签: springmvc springmvc学习笔记13-springmvc注解开发之集合类型參数绑定 数组绑定 需 ...
- springmvc学习笔记(19)-RESTful支持
springmvc学习笔记(19)-RESTful支持 标签: springmvc springmvc学习笔记19-RESTful支持 概念 REST的样例 controller REST方法的前端控 ...
- springMVC 学习笔记(一):springMVC 入门
springMVC 学习笔记(一):spring 入门 什么是 springMVC springMVC 是 spring 框架的一个模块,springMVC 和 spring 无需通过中间整合层进行整 ...
随机推荐
- 杭电OJ2007----平方和与立方和(易错题)
Problem Description 给定一段连续的整数,求出他们中所有偶数的平方和以及所有奇数的立方和. Input 输入数据包含多组测试实例,每组测试实例包含一行,由两个整数m和n组成. Out ...
- ssh问题之复盘
一.问题发生.排查以及解决 某天H博士在登录B服务器时发现一个严重的问题,问题是H博士在执行脚本出现一个异常,这个异常是过去我执行脚本只需输入一次密码,现在要输入五六次,只有输入五六次后才能正确执行完 ...
- Java并发包源码学习系列:ReentrantLock可重入独占锁详解
目录 基本用法介绍 继承体系 构造方法 state状态表示 获取锁 void lock()方法 NonfairSync FairSync 公平与非公平策略的差异 void lockInterrupti ...
- Linux命令整理,用户管理,用户组管理,系统管理,目录管理常用命令
知识点梳理 Linux课堂笔记 学习目标 能够知道什么是Linux系统以及它的应用场景 能够独立完成安装VMware虚拟机和网络配置 能够独立完成安装CentOS以及远程终端SecureCRT 能够熟 ...
- WPF APP 启动时增加特殊逻辑
public partial class App : Application { public App() { this.Startup += (o1, e1)=>{ string comman ...
- Docker PHP 扩展配置
# PHP 容器配置 # 从官方基础版本构建 FROM php:7.2-fpm # 官方版本默认安装扩展: # Core, ctype, curl # date, dom # fileinfo, fi ...
- 【Redis3.0.x】发布订阅
Redis3.0.x 发布订阅 基本命令 SUBSCRIBE channel [channel...] 订阅给定的一个或多个频道 PSUBSCRIBE pattern [pattern...] 订阅符 ...
- LeetCode237 删除链表中的节点
请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点. 现有一个链表 -- head = [4,5,1,9],它可以表示为: 4 -> 5 -> 1 - ...
- Redis 设计与实现 10:五大数据类型之有序集合
有序集合 sorted set (下面我们叫zset 吧) 有两种编码方式:压缩列表 ziplist 和跳表 skiplist. 编码一:ziplist zset 在 ziplist 中,成员(mem ...
- 这难道不是.NET5 的bug? 在线求锤?
hello,最近在对一个使用.NET5项目的认证授权系统进行重构,对.NET 5的授权中间件的源码有些看法. 也希望同学们能帮我理解. 一个朴素的需求 这是一个api项目,默认所有的api都需要授权, ...