一,參數的接收
參數接收的幾種方式:
1.使用servlet API接收參數
在方法參數中添加HttpServletRequest類型的參數,然后就可以像servlet的方法一樣來接收參數?
@RequestMapping("p1")public String param1(HttpServletRequest request){String name = request.getParameter("name");String password = request.getParameter("password");return "hello";}
2.在方法中定義同名參數
@RequestMapping("param2")public String method2(int id,String name){System.out.println(id+name);return "param";}
如果url地址中的參數名與方法的參數名不一致時,可以使用RequestParam注解進行重新關聯
@RequestMapping("param3")public String method3(@RequestParam("p") String password){System.out.println(password);return "param";}
url地址中的參數名p,而方法中的參數名是password,這時我們可以使用RequestParam注解對參數進行重新關聯
當我們在方法中接收一個整數類型的參數時,如果url中沒有傳遞該參數則會拋異常。如果這個參數不是必須要傳遞的,我們可以給該參數設置默認值。
@RequestMapping("p2")public String param2(String name,@RequestParam(defaultValue = "0") int age){System.out.println(name);System.out.println(age);return "hello";}
設置完默認值后,如果url中沒有攜帶id參數,則該參數默認值為0,不會拋出異常
3.使用POJO類接收參數
?什么是POJO?
“Plain Old Java Object”“簡單java對象”。POJO的內在含義是指那些沒有從任何類繼承、也沒有實現任何接口,更沒有被其它框架侵入的java對象。
@RequestMapping("student")public String test(Student student){System.out.println(student);return "param";}
spring會自動的從請求中把參數名與Student類中屬性名相同的數據,進行賦值
4.使用PathVariable接收參數
//restful請求傳參方式,可以傳遞多個參數,每個參數都用/分隔,但是不建議傳遞多個//最好只傳一個@RequestMapping("p4/{id}")public String param4(@PathVariable("id") int id){System.out.println(id);return "hello";}
?使用PathVariable進行參數傳遞,首先要在地址中添加占位符,然后使用PathVariable跟方法入參進行綁定
二,返回數據的幾種方式
1.使用servlet API傳遞數據:
?首先需要在方法中增加HttpServletRequest類型的參數,然后使用request對象傳遞數據,使用方式與之前學習servlet時的用法一致
@RequestMapping("resp2")public String method2(HttpServletRequest request){request.setAttribute("msg","test");Student student=new Student();student.setName("張三");request.setAttribute("student",student);return "resp2";}
2.使用Map集合傳遞參數
首先需要在方法中增加java.util.Map類型的參數,然后使用map對象通過put方法,把數據寫入到map中,進行數據傳遞
@RequestMapping("resp3")public String method3(Map<String,Object> map){map.put("msg","map傳參");Student student=new Student();student.setName("張三");map.put("student",student);return "resp2";}
3.使用Model傳遞數據:
首先需要在方法中增加Model類型的參數,然后使用model對象通過addAttribute方法,把數據寫入到addAttribute對象中,進行數據傳遞
@RequestMapping("r2")public String res2(Model model){//springMVC推薦使Model進行model.addAttribute("msg","model 傳參");return "resp";}
4.使用ModelAndView傳遞數據:
首先在方法中創建ModelAndView對象,使用addObject方法傳遞數據,使用setViewName設置要跳轉的頁面,注意方法的返回值也是ModelAndView類型
@RequestMapping("resp5")public ModelAndView method(){ModelAndView mv=new ModelAndView();//使用addObject方法傳遞參數mv.addObject("msg","ModelAndView傳參");//使用setViewName方法設置跳轉頁面mv.setViewName("resp2");return mv;}
以上四種返回數據的方式都可以使用,效率上也幾乎無差別,沒有具體的好與壞,想要使用哪種看自己的個人喜好
三,文件上傳
- Spring MVC 為文件上傳提供了直接的支持,這種支持是通 過即插即用的 MultipartResolver 實現的。Spring 用 Jakarta CommonsFileUpload 技術實現了一個 MultipartResolver 實現類:CommonsMultipartResovler
- Spring MVC 上下文中默認沒有裝配 MultipartResovler,因 此默認情況下不能處理文件的上傳工作,如果想使用 Spring 的文件上傳功能,需現在上下文中配置 MultipartResolver
配置CommonsMultipartResolver
首先配置編碼,必須跟jsp文件中的編碼保持一致
maxUploadSize用來配置最大支持的文件大小,默認是不限制,單位是byte
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="UTF-8"/><property name="maxUploadSize" value="5242880"/></bean>
導入上傳文件需要的jar包
<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.3</version></dependency>
編寫上傳的jsp頁面
注意enctype屬性,如果不加是無法上傳文件的
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>file</title>
</head>
<body><form action="upload" method="post" enctype="multipart/form-data"><input type="file" name="file"><br/><input type="submit" value="上傳">
</form>
</body>
</html>
編寫用于上傳的controller方法
注意參數類型,一定要用RequestParam注解標注,否則報錯
@RequestMapping("upload")public String upload(@RequestParam("file")MultipartFile file) throws Exception{//獲取文件原名System.out.println(file.getOriginalFilename());String path="D:\\Java\\"+file.getOriginalFilename();file.transferTo(new File(path));return "hello";}
四,處理JSON數據
什么是JSON數據格式
JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式。JSON采用完全獨立于語言的文本格式,這些特性使JSON成為理想的數據交換語言。易于人閱讀和編寫,同時也易于機器解析和生成。
JSON建構于兩種結構:
- “名稱/值”對的集合(A collection of name/value pairs)。相當于Java中的Map
- 值的有序列表(An ordered list of values)。在大部分語言中,它被理解為數組(array)。
JSON數據格式
{
"name": "張三",
"age": 20,
"email": "5689876@qq.com",
"phone": "15122334455",
}
這就是一段最簡單的JSON格式的數據
SpringMVC返回JSON
1.配置jar包
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.11.2</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.11.2</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.11.2</version></dependency>
2.配置文件中添加<mvc:annotation-driven/>標簽
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:comtext="http://www.springframework.org/schema/context"xmlns:avc="http://www.springframework.org/schema/cache"xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"><avc:annotation-driven/><comtext:component-scan base-package="com.haina.springmvc"/><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/views/"></property><property name="suffix" value=".jsp"></property></bean><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="UTF-8"/><property name="maxUploadSize" value="5242880"/></bean>
</beans>
3.添加方法
package com.haina.springmvc;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@Controller
public class JSONController {//ResponseBody注解的作用是讓該方法不再跳轉頁面,而是返回JSON格式的數據@RequestMapping("j1")@ResponseBodypublic Map<String,Object> j1(){Map<String,Object> map=new HashMap<String, Object>();map.put("code",1001);map.put("msg","success");return map;}@RequestMapping("j2")@ResponseBodypublic Student j2(){Student st=new Student();st.setNo(1234);st.setName("張三");st.setAge(20);st.setMajor("計算機");return st;}@RequestMapping("j3")@ResponseBodypublic List<Student> j3(){List<Student> list=new ArrayList<Student>();for (int i=0;i<10;i++){Student st=new Student();st.setNo(1234+i);st.setName("張三"+i);st.setAge(20+i);st.setMajor("計算機"+i);list.add(st);}return list;}}