(在Spring MVC 后臺(tái)控制層獲取前臺(tái)參數(shù)的方式主要有兩種,一種是requset.getParameter(“name”),另一種是用注解@ResquestParam獲取。)
org.springframework.web.bind.annotation.RequestParam 注解類型用于將指定的請(qǐng)求參數(shù)賦值給方法中的形參。
使用@RequestParam注解,可指定@RequestParam支持的屬性
@RequestParam注解支持的屬性屬性類型是否必要說(shuō)明
nameString否指定請(qǐng)求頭綁定的名稱
valueString否前臺(tái)name屬性的別名
requiredboolean否指示參數(shù)是否必須綁定
defaultValueString否如果沒(méi)有傳遞參數(shù)而使用的默認(rèn)值
例:
1、前臺(tái)代碼
<!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>
兩個(gè)前臺(tái)參數(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 是前臺(tái)參數(shù)name ,將它賦給形參name1,然后ModelAndView對(duì)象調(diào)用addObject方法,將形參數(shù)據(jù)傳遞給showname
然后前臺(tái)用EL表達(dá)式獲取showname,就可以將用戶輸入到輸入框中的數(shù)據(jù)顯示到顯示頁(yè)面上。
3、顯示頁(yè)面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.w3.org/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é)果顯示
運(yùn)行? 在index.html 輸入框中輸入 數(shù)據(jù)
點(diǎn)確認(rèn)后,后臺(tái)控制層處理,將數(shù)據(jù)傳到show.jsp顯示。
參考書(shū)籍:《Spring MyBatis企業(yè)應(yīng)用實(shí)戰(zhàn)》 瘋狂軟件編著,電子工業(yè)出版社。
來(lái)源:
https://www.icode9.com/content-4-814851.html