首先在controller 建立初始頁面
第一個方法 是return jsp 命名的string , response用Model 夾帶參數
@RequestMapping(value="/testing",method=RequestMethod.GET, produces="application/json; charset=utf-8")
public String testing(Model model){
String message = "yo man";
model.addAttribute("message",message);
return "testing";
}
JSP的部份
<form method="POST" action="../SpringMVC/modelTest" modelAttribute="Accountings">
<center>
<h2>Hello World</h2>
<h2>
${message}
</h2>
/center>
</form>
畫面上就可以看到呈現的字串了
第二個方法使用Ajax傳接值
Controller
@RequestMapping(value="/testingMVC", method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public Map<String,String> showMessage() {
Map<String,String> params = new HashMap<String, String>();
params.put("msg", "hello");
return params;
}
JSP
$( document ).ready(function() {
$.ajax({
type:'GET',
url: 'testingMVC',
dataType : 'json',
success:function(data){
console.log(data.msg);
},
error:function(e){
console.log(e);
},
});
});
畫面上按F12查看console 即可發現 params.put("msg", "hello");的字串
第三種方法 JSON String
JSP
form裡面加個按鈕
<button type="button" id="testBt" onclick="getVal()">get json string</button>
寫一個ajax函數
function getVal(){
var dataValue = {"msg":"bruno mars"};
$.ajax({
type:'POST',
url: 'getMsg',
data:JSON.stringify(dataValue),
contentType : 'application/json; charset=utf-8; text/plain',
dataType : 'json',
success:function(data){
console.log(data);
},
error:function(e){
console.log(e);
},
});
}
Controller
@RequestMapping(value="/getMsg",method = {RequestMethod.POST} , produces="application/json; charset=utf-8")
@ResponseBody
public String callVal(@RequestBody Map<String,String> msg) {
System.out.println("params " + msg.values());
JSONObject json = new JSONObject();
json.put("msg", "that's what I like");
return json.toString();
}
加上@RequestBody annotation 可以取到request的參數
在前端ajax Success裡可取到response data
第四種使用ModelAndView 加上Form表單的modelAttribute
接下來做submit並導頁的case
JSP
<form method="POST" action="../SpringMVC/modelTest" modelAttribute="Accountings">
<table>
<tr>
<td>
<button type="button" id="testBt" onclick="getVal()">get json string</button>
</td>
</tr>
<tr>
<td>
<input type="text" id="remarks" name="remarks" value="this is a modelattribue test">
</td>
</tr>
<tr>
<td>
<button type="submit" id='sub'>clickme</button>
</td>
</tr>
</table>
</center>
</form>
再傳一個要導向的jsp頁面
簡單打上要顯示的值
<form method="POST" action="../SpringMVC/modelTest" modelAttribute="Accountings">
<center>
<h2>
${message.param}
</h2>
</center>
</form>
Model
創一個帳務的model
這邊簡單用remark備註做一個範例
Controller
@RequestMapping(value="/modelTest",method={RequestMethod.POST}, produces="application/json; charset=utf-8")
public ModelAndView testing(@ModelAttribute("Accountings") Accountings accountings,Model model){
String message = accountings.remarks + " 取得帳務備註了!";
model.addAttribute("param",message);
return new ModelAndView("testing2","message",model);
}
點下clickme後 在server可以看到form裡面傳來的值
到View後
就可以得到值了!