(在Spring MVC 后臺控制層獲取前臺參數(shù)的方式主要有兩種,一種是requset.getParameter(“name”),另一種是用注解@ResquestParam獲取。) org.springframework.web.bind.annotation.RequestParam 注解類型用于將指定的請求參數(shù)賦值給方法中的形參。 使用@RequestParam注解,可指定@RequestParam支持的屬性
例: 1、前臺代碼 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="show.do" method="post"> 姓名<input type="text" name="name" value="name"/><br/> 年齡<input type="text" name="age" value="age"/><br/> <input type="submit" value="確認(rèn)"/> </form> </body> </html> 兩個前臺參數(shù)name 和 age 2、控制層代碼 import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @Controller public class StudentController { @RequestMapping("/show") public ModelAndView show(@RequestParam(value="name",required=false) String name1,@RequestParam(value="age",required=false) String age1,HttpServletResponse response)throws Exception{ ModelAndView mav=new ModelAndView(); mav.addObject("name", name1); mav.addObject("age", age1); mav.setViewName("show"); return mav; } } @RequestParam(value="name" 中的name 是前臺參數(shù)name ,將它賦給形參name1,然后ModelAndView對象調(diào)用addObject方法,將形參數(shù)據(jù)傳遞給showname 然后前臺用EL表達(dá)式獲取showname,就可以將用戶輸入到輸入框中的數(shù)據(jù)顯示到顯示頁面上。 3、顯示頁面show.jsp <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www./TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> 名字:${showname } 年齡:${showage } </body> </html> 4、結(jié)果顯示 運行 在index.html 輸入框中輸入 數(shù)據(jù) 點確認(rèn)后,后臺控制層處理,將數(shù)據(jù)傳到show.jsp顯示。 參考書籍:《Spring MyBatis企業(yè)應(yīng)用實戰(zhàn)》 瘋狂軟件編著,電子工業(yè)出版社。 來源:https://www./content-4-814851.html |
|