第六次总结
所学内容:
8.1
SpringMVC
1.控制器方法的返回值
控制器类
package cn.itcast.controller;
import cn.itcast.domain.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
@RequestMapping("/user")
public class UserController {
/**
* 返回值是String
* @param model
* @return
*/
@RequestMapping("/testString")
public String testString(Model model){
System.out.println("testString方法执行了");
//模拟从数据库中查询出User对象
User user = new User();
user.setUsername("美美");
user.setPassword("123");
user.setAge(30);
//model对象
model.addAttribute("user",user);
return "success";
}
/**
* 返回值是void,默认会去/WEB-INF/pages/找/user/testVoid.jsp。
* 请求转发:一次请求,不用编写项目的名字
* @param
*/
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception{
System.out.println("testVoid方法执行了");
/*//转发可以直接进WEB-INF
request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);*/
/*//重定向不能直接进WEB-INF
response.sendRedirect(request.getContextPath()+"/index.jsp");*/
//设置中文编码
response.setContentType("text/html;charset=utf-8");
//直接会进行响应
response.getWriter().print("你好");
return ;//转发之后还会执行后面的代码,如果不想后面的代码执行,可以执行return;
}
/**
* 返回ModelAndView对象
* @return
*/
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
System.out.println("testModelAndView执行了");
//1.创建ModelAndView对象
ModelAndView mv = new ModelAndView();
User user = new User();
user.setAge(19);
user.setPassword("123");
user.setUsername("张三");
//把user对象存储到mv对象中,也会把user对象存入到request对象域中
mv.addObject("user",user);
//跳转到哪个页面
mv.setViewName("success");//普通返回String就是在调用这个方法
return mv;
}
/**
* 使用关键字的方式进行转发或者重定向
* @return
*/
@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect(){
System.out.println("testForwardOrRedirect方法执行了...");
//请求的转发
// return "forward:/WEB-INF/pages/success.jsp";
//重定向,关键字的方式,不用加项目名,因为框架已经加好了
return "redirect:/index.jsp";
}
/**
* 模拟异步请求和响应
*/
@RequestMapping("/testAjax")
public @ResponseBody User testAjax(@RequestBody User user){
System.out.println("testAjax方法执行了");
//客户端发送ajax的请求,传的是json字符串,后端把json字符串封装到user对象中,需要处理json数据的依赖,如jackson等
System.out.println(user);
//做响应:模拟查询数据库
user.setUsername("haha");
user.setAge(28);
return user;
}
}
SpringMVC.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 创建核心容器时扫描的包-->
<context:component-scan base-package="cn.itcast"></context:component-scan>
<!-- 视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 前端控制器,哪些静态资源不拦截
location:指webapp目录下的所有文件
mapping:映射请求
-->
<mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
<mvc:resources mapping="/css/**" location="/css/"></mvc:resources>
<mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
<!-- 开启SpringMVC框架注解的支持-->
<mvc:annotation-driven ></mvc:annotation-driven>
</beans>
2.文件上传
2.1.1.文件上传的必要前提
A form 表单的 enctype 取值必须是:multipart/form-data
(默认值是:application/x-www-form-urlencoded)
enctype:是表单请求正文的类型
B method 属性取值必须是 Post
C 提供一个文件选择域<input type=”file” />
2.1.2.文件上传的原理分析
当 form 表单的 enctype 取值不是默认值后,request.getParameter()将失效。
enctype=”application/x-www-form-urlencoded”时,form 表单的正文内容是:
key=value&key=value&key=value
当 form 表单的 enctype 取值为 Mutilpart/form-data 时,请求正文内容就变成:
每一部分都是 MIME 类型描述的正文
-----------------------------7de1a433602ac 分界符
Content-Disposition: form-data; name="userName" 协议头
aaa 协议的正文
-----------------------------7de1a433602ac
Content-Disposition: form-data; name="file";
filename="C:\Users\zhy\Desktop\fileupload_demofile\b.txt"
Content-Type: text/plain 协议的类型(MIME 类型)
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
-----------------------------7de1a433602ac--
2.1.3.第三方组件实现文件上传
使用 Commons-fileupload 组件实现文件上传,需要导入该组件相应的支撑 jar 包:Commons-fileupload 和
commons-io。commons-io 不属于文件上传组件的开发 jar 文件,但Commons-fileupload 组件从 1.1 版本开始,它
工作时需要 commons-io 包的支持。
选择war部署时在tomcat的webapps中
选择exploded_war部署时,在target中
2.2.三种文件上传
package cn.itcast.controller;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/user")
public class UserController {
/**
* 传统文件上传(第三方组件文件上传)
* @return
*/
@RequestMapping("/fileupload1")
public String fileupload1(HttpServletRequest request) throws Exception{
System.out.println("文件上传");
//使用fileupload组件完成文件上传
//上传的位置
String realPath = request.getServletContext().getRealPath("/uploads/");
//判断是否存在
File file = new File(realPath);
if (!file.exists()){
file.mkdirs();//创建文件夹
}
//解析request对象,获取上传文件项
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//解析request
List<FileItem> items = upload.parseRequest(request);
//遍历
for (FileItem item : items) {
//进行判断,当前item对象是否是上传文件项
if (item.isFormField()){
//说明是普通表单项
} else {
//说明是上传文件项
//获取上传文件的名称
String filename = item.getName();
//把文件的名称设置唯一值.uuid
String uuid = UUID.randomUUID().toString().replace("-","");
filename = uuid+"_"+filename;
System.out.println(realPath+filename);
//完成文件上传
item.write(new File(realPath,filename));
}
}
return "success";
}
/**
* SpringMVC方式上传
*/
@RequestMapping("/fileupload2")
public String fileupload2(HttpServletRequest request,MultipartFile upload) throws Exception{
System.out.println("SpringMVC文件上传");
String realPath = request.getServletContext().getRealPath("/uploads/");
//判断是否存在
File file = new File(realPath);
if (!file.exists()){
file.mkdirs();//创建文件夹
}
//说明是上传文件项
//获取上传文件的名称
String filename = upload.getOriginalFilename();
//把文件的名称设置唯一值.uuid
String uuid = UUID.randomUUID().toString().replace("-","");
filename = uuid+"_"+filename;
System.out.println(realPath+filename);
//完成文件上传
upload.transferTo(new File(realPath,filename));
return "success";
}
/**
* SprungMVC垮服务器文件上传
* @param
* @param upload
* @return
* @throws Exception
*/
@RequestMapping("/fileupload3")
public String fileupload3(MultipartFile upload) throws Exception{
System.out.println("SpringMVC垮服务器文件上传");
//定义上传文件服务器路径
String path = "http://localhost:9090/fileuploadServlet_war_exploded/uploads/";
//说明是上传文件项
//获取上传文件的名称
String filename = upload.getOriginalFilename();
//把文件的名称设置唯一值.uuid
String uuid = UUID.randomUUID().toString().replace("-","");
filename = uuid+"_"+filename;
//完成文件上传,跨服务器上传
//创建客户端的对象
Client client = Client.create();
//和图片服务器进行连接
WebResource webResource = client.resource(path + filename);
//上传文件
webResource.put(upload.getBytes());
return "success";
}
}
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>传统文件上传</h3>
<form action="user/fileupload1" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload" accept="image/*"><br>
<input type="submit" value="上传">
</form>
<h3>SpringMVC文件上传</h3>
<form action="user/fileupload2" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload" accept="image/*"><br>
<input type="submit" value="上传">
</form>
<h3>SpringMVC垮服务器上传文件</h3>
<form action="user/fileupload3" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload" accept="image/*"><br>
<input type="submit" value="上传">
</form>
</body>
</html>
报错:
垮服务器文件上传405
在tomcat的conf/web.xml中的DefaultServlet中设置初始化参数readonly为false
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>readonly</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>