1. 上传(非重点)
1.1 导入jar
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions
</dependency>
1.2 表单
<form action="${pageContext.request.contextPath }/upload/test1" method="post"
enctype="multipart/form-data">
file: <input type="file" name="source"/> <br>
<input type="submit" value="提交"/>
</form>
1.3 上传解析器
<!-- 上传解析器
id必须是:“multipartResolver”
-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 最大可上传的文件大小 byte 超出后会抛出MaxUploadSizeExceededException异常,可以异常解析器捕获 -->
<property name="maxUploadSize" value="2097152"></property>
</bean>
1.4 Handler
@RequestMapping("/test1")
public String hello1(String username,MultipartFile source,HttpSession session) {
//文件的原始名称
String filename = source.getOriginalFilename();
//定制全局唯一的命名
String unique = UUID.randomUUID().toString();
//获得文件的后缀
String ext = FilenameUtils.getExtension(filename);//abc.txt txt hello.html html
//定制全局唯一的文件名
String uniqueFileName = unique+"."+ext;
System.out.println("唯一的文件名:"+uniqueFileName);
//文件的类型
String type = source.getContentType();
System.out.println("filename:"+filename+" type:"+type);
//获得 upload_file的磁盘路径 ==> 在webapp目录下创建一个目录"upload_file",且此目录初始不要为空,否则编译时被忽略
String real_path = session.getServletContext().getRealPath("/upload_file");
System.out.println("real_path:"+real_path);
//将上传的文件,存入磁盘路径中
//source.transferTo(new File("d:/xxxx/xxxx/xx.jpg"))
source.transferTo(new File(real_path+"\\"+uniqueFileName));
return "index";
}
2. 下载(非重点)
2.1 超链
<a href="${pageContext.request.contextPath}/download/test1?name=Koala.jpg">下载</a>
2.2 Handler
@RequestMapping("/test1")
public void hello1(String name,HttpSession session,HttpServletResponse response){
System.out.println("name:"+name);
//获得要下载文件的绝对路径
String path = session.getServletContext().getRealPath("/upload_file");
//文件的完整路径
String real_path = path+File.separator+name;
//设置响应头 告知浏览器,要以附件的形式保存内容 filename=浏览器显示的下载文件名
response.setHeader("content-disposition","attachment;filename="+name);
//读取目标文件,写出给客户端
IOUtils.copy(new FileInputStream(real_path), response.getOutputStream());
//上一步,已经是响应了,所以此handler直接是void
}
3. 验证码(非重点)
屏障,防止暴力破解
3.1 导入jar
<!-- Kaptcha -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
3.2 声明验证码组件
<servlet>
<servlet-name>cap</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
<init-param>
<param-name>kaptcha.border</param-name>
<param-value>no</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>4</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.char.string</param-name>
<param-value>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789</param-value>
</init-param>
<init-param>
<param-name>kaptcha.background.clear.to</param-name>
<param-value>211,229,237</param-value>
</init-param>
<init-param>
<param-name>kaptcha.session.key</param-name>
<param-value>captcha</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>cap</servlet-name>
<url-pattern>/captcha</url-pattern>
</servlet-mapping>
3.3 Page
<img src="${pageContext.request.contextPath}/captcha" style="width:85px" id="cap"/>
<script>
$(function(){
$("#cap").click(function(){
//刷新验证码
path = $(this).attr("src")+"?"+new Date().getTime();
$(this).attr("src",path);
});
});
</script>
4.REST
4.1 开发风格
是一种开发风格,遵从此风格开发软件,是restful的。
- 每个资源都有自己的标识
http://localhost:8989/xxx/users
http://localhost:8989/xxx/users/1
http://localhost:8989/xxx/users/1/orders
- 每个请求都有明确的动词 ( GET, POST, PUT, DELETE )
GET :http://localhost:8989/xxx/users 查询所有用户
POST:http://localhost:8989/xxx/users 增加一个用户
PUT :http://localhost:8989/xxx/users/1 修改用户1
DELETE :http://localhost:8989/xxx/users/1 删除用户1
GET:http://localhost:8989/xxx/users/1/orders 查询用户1的订单
POST:http://localhost:8989/xxx/users/1/orders 为用户1增加一个订单
4.2 优点
- 看Url就知道要什么
- 看http method就知道干什么
- 看http status code就知道结果如何
4.3 使用

4.3.1 定义Rest风格的 Controller
@RequestMapping(value="/users",method = RequestMethod.GET)等价
@GetMapping("/users")
@Controller
public class RestController {
@GetMapping("/users")
@ResponseBody
public List<User> queryAllUsers(){
System.out.println("get");
List<User> users = ....
return users;
}
@PostMapping("/users")
public String addUser(User user){
System.out.println("Post user :"+user);
return "index";
}
@GetMapping("/users/{id}")
public String queryOneUser(@PathVariable Integer id){//@PathVariable 接收路径中的值
System.out.println("Get user id:"+id);
return "index";
}
@PutMapping("/users")
public String updateUser(@RequestBody User user){
System.out.println("Put user" user:"+user);
return "index";
}
@DeleteMapping("/users/{id}")
public String deleteOneUser(@PathVariable Integer id){//@PathVariable 接收路径中的值
System.out.println("delete user id:"+id);
return "index";
}
/**
*
@PostMapping("/users/{id}/orders")
@ResponseBody
public String addOrderForUser(@PathVariable Integer id,Order order){
System.out.println("delete user id:"+id);
return "index";
}
@GetMapping("/users/{id}/orders")
@ResponseBody
public String queryOrderForUser(@PathVariable Integer id,Order order){
System.out.println("delete user id:"+id);
return "index";
}
*/
}
4.3.2 测试
//增加-表单
<form method="post" action="${pageContext.request.contextPath}/users">
<input type="text" name="name"/>
<input type="text" name="birth"/>
....
<input type="submit" value="提交">
</form>
//更新-表单 (注意此时,会有问题,浏览器默认只支持get/post,其他method会被默认作为get)
<form method="put" action="${pageContext.request.contextPath}/users/${id}">
<input type="text" name="name"/>
<input type="text" name="birth"/>
....
<input type="submit" value="提交">
</form>
4.3.3 解决
<!-- rest过滤器,不支持put、delete的浏览器默认会将他们转为get,所以通过如下过滤器来解决此问题
可以定义一个method="post"的form,附加一个名为"_method"的请求参数(隐藏域),即可模拟put,delete 请求方式
-->
<filter>
<filter-name>httpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>httpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- CharacterEncodingFilter 要配置在此过滤器之后 -->
<form method="post" action="${pageContext.request.contextPath}/users/${id}">
<input type="hidden" name="_method" value="put"> <!-- 添加一个名为 “_method”的参数 -->
<input type="text" name="name"/>
<input type="text" name="birth"/>
....
<input type="submit" value="提交">
</form>
4.3.4 JSP对请求方式的支持
JSP只支持了 head,get,postput,delete,post 之后 均应该 重定向到 get上,再由get转发jsp
4.3.5 Ajax请求
@RequestMapping(value="/users",method = RequestMethod.PUT)
@ResponseBody
public MyRequestStatus updateUser(@RequestBody User user) {
System.out.println("update One");
MyRequestStatus status = new MyRequestStatus("update", "ok");
return status;
}
@RequestMapping(value="/users/{id}",method = RequestMethod.DELETE)
@ResponseBody
public MyRequestStatus deleteOneUser(Integer id){
System.out.println("delete One");
MyRequestStatus status = new MyRequestStatus("delete", "ok");
return status;
}
<script>
function putUser(){
var xhr = new XMLHttpRequest();
//定义 put,delete,get,post方式 即可,不用定义_method
xhr.open("put","${pageContext.request.contextPath}/rest04/users");
// 设置请求头
xhr.setRequestHeader("content-type","application/json");
// 设置请求参数
xhr.send('{"nick":"zhj","username":"zzzz"}');
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200){
var ret = xhr.responseText;
// 解析json,并输出
console.log(eval("("+ret+")"));
}
}
}
function delUser(){
var xhr = new XMLHttpRequest();
//定义 put,delete,get,post方式 即可,不用定义_method
xhr.open("delete","${pageContext.request.contextPath}/rest04/users/1");
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200){
var ret = xhr.responseText;
console.log(eval("("+ret+")"));
}
}
}
</script>
本文详细介绍了在Spring MVC框架下实现文件上传、下载及验证码功能的方法,同时深入探讨了RESTful API的设计原则及其在实际项目中的应用。通过具体示例,读者将了解到如何配置文件上传解析器、处理上传与下载请求,以及如何利用Kaptcha生成验证码。此外,还讲解了RESTful API的开发风格、优点和具体实现,包括如何定义控制器、测试不同HTTP方法及解决浏览器对PUT、DELETE方法的支持问题。

被折叠的 条评论
为什么被折叠?



