歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Spring MVC 前後端傳值方式心得筆記

Spring MVC 前後端傳值方式心得筆記

日期:2017/3/1 9:05:57   编辑:Linux編程

前端傳到Controller:

方法1

通過HttpServletRequest 。寫法如下:

@Controller

public class MyTestController {

@RequestMapping("/print")

public String PrintInfo(HttpServletRequest request) {

System.out.println("name:" +request.getParameter("name"));

System.out.println("age:" + request.getParameter("age"));

return "testpage";

}

}

HttpServletRequest類是Servlet中的類型,代表了一個Servlet請求。無論Post還是Get請求,都能通過這種方式獲取到。

比如上面的代碼,通過Get方法,如下地址

http://127.0.0.1:8080/WebApp/print?name=zhangsan&age=30

也可以通過Post方法,使用Postman工具模擬一個post請求,都可以將值傳到Controller。

這招可以獲得Cookie以及Session數據。

還可以通過注解@Autowired,將HttpServletRequest 自動的注入進來,不必擔心多線程下的並發問題,因為這裡HttpServletRequest注入的是一個AOP proxy ,而不是一個普通bean 。每次請求過來,都會檢查線程本地屬性,來獲取真正的Request對象。這些都是Spring自動配置的默認場景。可以參閱https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-scopes-other-injection

但是不推薦使用這個方法,因為這種方法破壞了對一個注入對象的常規理解,造成混亂。

代碼如下:

@Controller

public class MyTestController {

@Autowired

private HttpServletRequest request;

@RequestMapping(value="/print")

public String PrintInfo() {

System.out.println("name:" +request.getParameter("name"));

System.out.println("age:" + request.getParameter("age"));

return "testpage";

}

}

方法2

使用路徑變量。寫法如下:

@Controller

public class MyTestController {

@RequestMapping("/print/{name}/{age}")

public String PrintInfo(@PathVariable String name, @PathVariable int age) {

System.out.println("name:" + name);

System.out.println("age:" + age);

return "testpage";

}

}

@RequestMapping中的{}中即為路徑變量,該變量還需要在方法的參數值出現,並且標記@PathVariable。

通過URL匹配的方式既可以實現傳值,這是REST風格的一種傳值方式。

上面的例子,只需輸入URL:

http://127.0.0.1:8080/WebApp/print/ZhangSan/30

controller接收到傳值,輸出:

name:ZhangSan

age:30

@RequestMapping("/print/{name}/{age}")是@RequestMapping(Value="/print/{name}/{age}")的縮寫形式,本質上是一樣的。

方法3

參數名匹配的方式:

@Controller

public class MyTestController {

@RequestMapping(value="/print")

public String PrintInfo(String name, int age) {

System.out.println("name:" +name);

System.out.println("age:" + age);

return "testpage";

}

}

或者:

@Controller

public class MyTestController {

@RequestMapping(value="/print")

public String PrintInfo(@RequestParam("name") String name,@RequestParam("age") int age) {

System.out.println("name:" +name);

System.out.println("age:" + age);

return "testpage";

}

}

當請求傳入的參數名字和controller

中代碼的名字一樣的時候,兩種方式都可以,區別在於使用了注解@RequestParam,可以設置一個默認值來處理到null值。

@RequestParam(value="name", defaultValue="John")

但是如果請求中參數的名字和變量名不一樣的時候,就只能使用@RequestParam注解。例如請求的參數為如下的時候:

http://localhost:8080/WebApp/print?user_name=somename&user_age=30

Controller代碼只能如下的寫法

@RequestMapping(value="/print")

public String PrintInfo(@RequestParam("user_name") String name, @RequestParam("user_age")int age) {

...

}

盡量使用@RequestParam注解,因為這樣可以清晰的知道該參數來自Request,可讀性高。

方法4

傳遞請求頭中的參數,需要用到@RequestHeader注解,該注解將Header中的值綁定到參數上,可以獲取一個,多個或者所有的參數。例如

@Controller

public class MyTestController {

@RequestMapping(value="/print")

public String PrintInfo(@RequestHeader Map<String, String> headers) {

for (String elem: headers.keySet()) {

System.out.println(elem + " : " + headers.get(elem));

}

return "testpage";

}

}

或者

@Controller

public class MyTestController {

@RequestMapping(value="/print")

public String PrintInfo(@RequestHeader("User-Agent") String userAgent) {

System.out.println("12");

System.out.println("name:" +userAgent);

//System.out.println("age:" + age);

return "testpage";

}

}

方法5

使用到@RequestBody注解,得到整個RequestBody的信息

@Controller

public class MyTestController {

@RequestMapping(value="/print")

public String PrintInfo(@RequestBody String body) {

System.out.println("body:" +body);

return "testpage";

}

}

@RequestBody可以將Json數據直接映射程Java對象。例如:

方法6

采用@ModelAttribute注解,命名匹配,Post中的參數值和Model中的參數值一致的話,會自動綁定到該值。

@Controller

public class MyTestController {

@RequestMapping(value="/print")

public String PrintInfo(@ModelAttribute User user) {

System.out.println("6");

System.out.println("Name:" +user.getName());

System.out.println("Age:" +user.getAge());

return "testpage";

}

}

public class User {

private String name;

private int age;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

}

然後當Post的值中有name和age時,Controller中的user對象會自動附上值。

Controller傳遞到JSP

方法1

使用ModelAndView類,代碼如下:

@RequestMapping("/hello")

public ModelAndView showMessage() {

ModelAndView mv = new ModelAndView("helloworld");

mv.addObject("userList", GetUserList());

return mv;

}

public List<User> GetUserList()

{

List<User> lst=new ArrayList<User>();

User user1=new User();

user1.setName("zhangsan");

user1.setAge(20);

lst.add(user1);

User user2=new User();

user2.setName("lisi");

user2.setAge(30);

lst.add(user2);

return lst;

}

JSP頁面中:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Spring 4 MVC -HelloWorld</title>

</head>

<body>

<c:forEach items="${userList}" var="user">

${user.name} ${user.age}

<br />

</c:forEach>

</body>

</html>

ModelAndView 初始化的時候,設置了view的名字,同時也把對象存起來,直接傳給view。簡單實用。

方法2

使用Model或者ModelMap

(Model是一個接口,ModelMap實現了Model接口)

該方法和ModelAndView方法相似,只是Model和View分開來了,通過返回一個String來找到View,Model是注入到Controller的一個參數,通過對它添加屬性,在jsp端讀取值。代碼如下:

@Controller

public class HelloWorldController {

String message = "Welcome to Spring MVC!";

@RequestMapping("/hello")

public String showMessage(Model model) {

model.addAttribute("userList", GetUserList());

return "helloworld";

}

public List<User> GetUserList()

{

List<User> lst=new ArrayList<User>();

User user1=new User();

user1.setName("zhangsan");

user1.setAge(10);

lst.add(user1);

User user2=new User();

user2.setName("lisi");

user2.setAge(33);

lst.add(user2);

return lst;

}

}

JSP頁面中:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Spring 4 MVC -HelloWorld</title>

</head>

<body>

<c:forEach items="${userList}" var="user">

${user.name} ${user.age}

<br />

</c:forEach>

</body>

</html>

SpringMVC總結篇 http://www.linuxidc.com/Linux/2016-06/132659.htm

Spring+SpringMVC企業快速開發架構搭建 http://www.linuxidc.com/Linux/2015-09/122942.htm

SpringMVC的亂碼處理 http://www.linuxidc.com/Linux/2015-07/120542.htm

Spring MVC整合Freemarker基於注解方式 http://www.linuxidc.com/Linux/2013-02/79660.htm

SpringMVC詳細示例實戰教程 http://www.linuxidc.com/Linux/2015-06/118461.htm

SpringMVC 異常處理 http://www.linuxidc.com/Linux/2015-06/119049.htm

Spring + Spring MVC + Ibatis + Velocity 框架搭建 http://www.linuxidc.com/Linux/2016-10/135846.htm

Copyright © Linux教程網 All Rights Reserved