1. 程式人生 > >SpringMVC的學習(五)——SpringMVC返回值、SpringMVC實現檔案上傳

SpringMVC的學習(五)——SpringMVC返回值、SpringMVC實現檔案上傳

一、SpringMVC返回值

①json資料

訪問控制器返回Json型別資料

匯入對應的JSON包

支援:

jackson : jackson-databind/jackson-annotations/jack-core

gson: gson

注意:  jackson需要三個jar包!如果使用maven引入jackson-databind會連帶引入 core和annotations。如果非maven專案,必須加入三個jar包!

Fastjson:fastjson

實現程式碼:

主要使用@ResponseBody

@ResponseBody
	@RequestMapping("/json")
	public List<User> getJson() {
		
		User user = new User();
		user.setUsername("小毛");
		user.setPassword("admin");
		user.setBirthday(new Date());

		List<User> list = new ArrayList<User>();
		list.add(user);
		list.add(user);
		return list;
	}

②String

情況1: 查詢到指定的檢視

  return "user/show";  預設就是轉發

情況2: 轉發或者重定向

  return "redirect: path";

  return "forword:path";

③ModelAndView

返回資料檢視模型物件

    ModelAndView mv = new ModelAndView();

    mv.setViewName("查詢檢視路徑");

mv.addObject("key","object type data");

④Object物件

配合@ResponseBody返回Json資料型別!

@ResponseBody
	@RequestMapping("/json1")
	public User getJson1() {
		User user = new User();
		user.setUsername("小毛");
		user.setPassword("admin");
		user.setBirthday(new Date());
		return user;
	}

⑤void

可以返回其他mimetype型別的資料!通常將方法定義成void!

配合方法傳參得到Response物件,通過Response.getWriter().writer("資料")

二、SpringMVC實現檔案上傳

Spring MVC為檔案上傳提供了直接支援,這種支援是通過即插即用的MultipartResolver實現. Spring使用Jakarta Commons FileUpload技術實現了一個MultipartResolver實現類:CommonsMultipartResolver

在SpringMVC上下文中預設沒有裝配MultipartResolver,因此預設情況下不能處理檔案上傳工作。如果想使用Spring的檔案上傳功能,則需要先在上下文中配置MultipartResolver。

①需要引入jar包:

commons-fileupload.jar

  commons-io.jar

②在SpringMVC.xml中配置multipartResolver

<!--multipartResolver配置 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8"/>
		<property name="maxUploadSize" value="5242880"/>
		<property name="uploadTempDir" value="file:/d:/temp"/>
	</bean>

其中屬性詳解:

defaultEncoding="UTF-8" 是請求的編碼格式,預設為iso-8859-1

maxUploadSize="5400000" 是上傳檔案的大小,單位為位元組

uploadTempDir="file:/d:/temp" 為上傳檔案的臨時路徑

③編寫檔案上傳表單

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <center>
      <form method="post" enctype="multipart/form-data" action="user/upload">
            <label for="name">檔名稱<input type="text" id="name" name="name" /></label>
            <input type="file" name="file" />
            <button>提交</button>
      </form>
  </center>
</body>
</

④編寫控制器

@Controller
@RequestMapping("/user")
public class UploadController {

	@RequestMapping("/upload")
	public String saveFile(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) throws IOException {
		// 接收表單提交的資料,包含檔案
		System.out.println("name = " + name);
		if (!file.isEmpty()) {
			file.transferTo(new File("G:/temp/" + file.getOriginalFilename()));
		}
		return "success";
	}
}

SpringMVC會將上傳檔案繫結到MultipartFile物件上. MultipartFile提供了獲取長傳檔案內容,檔名等方法,通過transferTo()方法還可將檔案儲存到磁碟中,具體方法如下:

改進版:

@Controller
@RequestMapping("/user")
public class UploadController {

	@RequestMapping("/upload")
	public String saveFile(@RequestParam("name") String name, @RequestParam("file") MultipartFile file,HttpServletRequest request) throws IOException {
		// 接收表單提交的資料,包含檔案
		System.out.println("name = " + name);
		File path = createDir(request.getSession().getServletContext());
		String fileName=createName(file.getOriginalFilename());
		File f=new File(path, fileName);
		if (!file.isEmpty()) {
			file.transferTo(f);
		}
		return "success";
	}

	// 建立目錄---以日期,一天一個資料夾
	private File createDir(ServletContext context) {
		String realPath = context.getRealPath("/static/upload");
		String date = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
		File file = new File(realPath, date);
		if (!file.exists()) {
			file.mkdir();
		}
		return file;
	}

	// 建立檔名--區分同名檔案,在檔名前加上當前的時間
	private String createName(String name) {
		return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(Calendar.getInstance().getTime()) + "_" + name;
	}
}