1、SpringMVC 響應傳值方式
SpringMVC如何從伺服器傳資料到浏覽器?共四種方式
1.1 Controller方法的傳回值類型為void(了解)
在Controller方法形參上可以定義request和response,使用request或response指定響應結果:
-
使用request請求轉發頁面:
request.getRequestDispatcher(“頁面路徑”).forward(request, response);
-
通過response重定向頁面:
response.sendRedirect(“url”)
-
通過response指定響應結果,例如響應json資料如下:
通過request.setAttribute(“key”,“value”)共享資料
@Controller
public class TestContro03 {
@RequestMapping("/test01")
public void test01(HttpServletRequest req, HttpServletResponse res) throws Exception{
//傳回void類型和共享資料,不用此方式!!!
req.setAttribute("info","test01");
//頁面跳轉
req.getRequestDispatcher("/index.jsp").forward(req,res);
}
1.2 傳回ModelAndView類型和共享資料(掌握)
@RequestMapping("/test02")
public ModelAndView test02(){
//傳回modelandview類型資料,使用多
ModelAndView mv = new ModelAndView();
User user = new User(01,"張三","123");
/*共享資料*/
mv.addObject("info","test02");
mv.addObject("info1",user);
/*跳轉頁面*/
/*當要跳轉的頁面路徑過長時,可以在springmvc配置檔案中配置視圖解析器,指定字首和字尾*/
mv.setViewName("/index.jsp");
return mv;
}
在SpringMVC配置檔案中,重新配置視圖解析器:
Controller方法傳回字元串表示邏輯視圖名,通過視圖解析器解析為實體視圖位址。
此時預設的實體視圖位址為:視圖字首+邏輯視圖名稱+視圖字尾.
<!--配置視圖解析器,頁面路徑過于複雜,配置字首和字尾-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/******"/>
<property name="suffix" value=".jsp"/>
</bean>
1.3 傳回String類型和共享資料(掌握)
(1)傳回值為String類型,字元串傳回值就是要跳轉的頁面(邏輯視圖名),預設視圖的位址:字首+方法的傳回值+字尾
(2)使用參數中的Model對象共享資料
@RequestMapping("/test03")
public String test03(Model model){
model.addAttribute("info","test03");
return "/index.jsp";
}
(3)redirect和forward:
redirect方式相當于“response.sendRedirect()”,轉發後浏覽器的位址欄變為重定向後的位址,不共享之前請求的資料。
forward方式相當于“request.getRequestDispatcher().forward(request,response)”,轉發後浏覽器位址欄還是原來的位址,共享之前請求中的資料。
redirect或者forward之後,配置的視圖解析器中的字首和字尾不再有效.
return "redirect/index.jsp" // (重定向);
return "forward/index.jsp" //(請求轉發)
1.4 傳回對象類型和共享資料(掌握)
注意點:
- 傳回對象類型的方法通常用于傳回JSON字元串時,這種方法一般結合json使用
- 把目前請求的url作為邏輯視圖名稱
- key預設為傳回值類型名user(首字母小寫),可用注解 ModelAttribute修改key值
- value為user對象
1.4.1 SpingMVC結合JSON
1.将對象轉換為json的方法有很多,可以使用工具類處理
有兩種,一種是springMVC底層使用的jackson(此處使用)
另外一個中為阿裡出品,fastjson
(1)導入jackson依賴,導入databind,會自動下載下傳其他依賴。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
(2)在controller類中定義方法
//響應浏覽器json格式資料
@RequestMapping("/test04")
@ResponseBody //可以把傳回的對象,轉換成json格式字元串,響應給浏覽器
public Employee test04(){
Employee emp = new Employee(01,"王五",new Date(),"123",true);
return emp;
}
1.4.2 jackson注解的正常使用
@[email protected]@ToString
@[email protected]
public class Employee {
private Integer id;
private String name;
//@JsonFormat(pattern = "yyyy-MM-dd") 按照指定格式格式化
private Date birthday;
//@JsonIgnore 不顯示此字段
private String password;
//@JsonProperty("gender") 起别名
private Boolean sex;
}
2、SpringMVC 請求傳參方式
2.1 傳統的方式(了解)
方法參數中帶入request,通過request.getParameter(“參數名”),再封裝到JavaBean中(雞肋)
(1)Controller類:
@Controller
public class Controller01 {
@RequestMapping("/test01")
public ModelAndView test01(HttpServletRequest req){
//傳統的方式,方法參數中帶入request,通過request.getParameter("參數名"),再封裝到JavaBean中.
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username+" "+password);
return null;
}
}
(2)jsp頁面
<fieldset>
<legend>請求方式一</legend>
<form action="/test01" method="post">
使用者名:<input type="text" name="username"/>
密碼:<input type="password" name="password"/>
<input type="submit" value="送出">
</form>
</fieldset>
2.2 簡單類型參數和RequestParam注解(掌握)
- 如果請求參數和Controller方法的形參同名. 可以直接接收
- 如果請求參數和Controller方法的形參不同名. 使用@RequestParam注解貼在形參前,設定對應的請求參數名稱.
(1)Controller類:
@RequestMapping("/test02")
public ModelAndView test02(@RequestParam("username") String name, String password){
//簡單類型參數和RequestParam注解(使用此注解,則必須傳值,可設定預設值)
/*同名比對原則,形參名字和表單name屬性名一緻;若不一緻,可使用@RequestParam*/
System.out.println(name+" "+password);
return null;
}
(2)jsp頁面
<fieldset>
<legend>請求方式二</legend>
<form action="/test02" method="post">
使用者名:<input type="text" name="username"/>
密碼:<input type="password" name="password"/>
<input type="submit" value="送出">
</form>
</fieldset>
2.3 對象傳參(掌握)
- 能夠自動把請求參數封裝到聲明在形參上的對象中,此時請求參數必須和對象的屬性同名。
- 此時,SpringMVC會将對象參數直接放入request的作用域中,key名為類型首字母小寫
-
或用@ModelAttribute(“xxx”)注解指定key名
(1)Controller類:
@RequestMapping("/test03")
public ModelAndView test03(User user){
//對象傳參,能夠自動把請求參數封裝到聲明在形參上的對象中,此時請求參數必須和對象的屬性同名(使用比較多).
/*此時,SpringMVC會将對象參數直接放入request的作用域中,
名稱為類型首字母小寫,或用@ModelAttribute("xxx")注解指定key名*/
System.out.println(user);
ModelAndView mv = new ModelAndView();
mv.setViewName("/login.jsp");
return mv;
}
(2)jsp頁面
<fieldset>
<legend>請求方式三</legend>
<form action="/test03" method="post">
id:<input type="text" name="id"/>
使用者名:<input type="text" name="name"/>
日期:<input type="date" name="date"/>
<input type="submit" value="送出">
</form>
</fieldset>
2.4 數組和List集合類型參數(使用)
2.4.1 接收數組類型參數:
(1)Controller類:
@RequestMapping("/test04")
public ModelAndView test04(String id[]){
//數組和List集合類型參數
/*
接收數組類型參數:必須同名
不能直接擷取,隻能通過對象封裝List集合.
*/
for(String i:id){
System.out.println(i);
}
return null;
}
(2)jsp頁面
<fieldset>
<legend>請求方式四</legend>
<form action="/test04" method="post">
<input type="checkbox" name="id" value="1"/>
<input type="checkbox" name="id" value="2"/>
<input type="checkbox" name="id" value="3"/>
<input type="submit" value="送出">
</form>
</fieldset>
2.4.2 接收List類型參數:
不能直接擷取,隻能通過對象封裝List集合.
@[email protected]
public class User {
private List<Long> ids= new ArrayList<Long>();
}
@RequestMapping("/test6")
public ModelAndView test6(User u){
System.out.println(u);
return null;
}
2.5 RESTful(了解)
一種軟體架構風格,嚴格上說是一種編碼風格,其充分利用 HTTP 協定本身語義進而提供了一組設計原則和限制條件。
@RequestMapping("/delete/{id}")
public ModelAndView test05(@PathVariable("id")Long id){
//RESTful是一種軟體架構風格,嚴格上說是一種編碼風格,
// 其充分利用 HTTP 協定本身語義進而提供了一組設計原則和限制條件。
/*主要用于用戶端和伺服器互動類的軟體,該風格設計的軟體可以更簡潔,更有層次,更易于實作緩存等機制。
在背景,RequestMapping标簽後,可以用{參數名}方式傳參,同時需要在形參前加注解@PathVarible,前台的請求位址為localhost:8080/delete/3*/
System.out.println("delete");
System.out.println(id);
return null;
}