本文主要介紹了SpringMVC前端和后端數(shù)據(jù)交互的資料,特地發(fā)出來記錄一下。有需要的朋友可以了解一下。
控制器
作為控制器,大體的作用是作為V端的數(shù)據(jù)接收并且交給M層去處理,然后負責管理V的跳轉(zhuǎn)。SpringMVC的作用不外乎就是如此,主要分為:接收表單或者請求的值,定義過濾器,跳轉(zhuǎn)頁面;其實就是servlet的替代品。
傳值方式
springmvc最方便的一點就是可以通過注釋方式來定義它的url。
1
2
3
4
5
6
|
@Controller public class formMVC { @RequestMapping ( "/hello" ) public void login(){ } |
如上面這種方式,在項目名下跟著hello就能訪問這個方法了,相較struts2的xml配置加大了開發(fā)效率,并且是以方法為級別的開發(fā)。
接收表單數(shù)據(jù)只需要在方法的參數(shù)加入響應(yīng)的字段,對應(yīng)表單input的name屬性,因為是通過反射技術(shù)實現(xiàn)的所以字段要完全相同。
1
2
3
4
5
|
@RequestMapping ( "/login" ) public String login(String username,String password){ System.out.println(username+ " " +password); return "form.jsp" ; } |
如上面這種方式,表單提交之后就會獲得值。跳轉(zhuǎn)方式就是使用返回的字符串,springmvc的DispatcherServlet會跳轉(zhuǎn)到字符串的頁面。你也可以配置它的前綴后綴。在它的配置文件中配置下面屬性,就是在這個return的字符串的前面和后面加入你配置的前綴后綴。
1
2
3
4
5
6
7
8
|
<!-- configure the InternalResourceViewResolver --> < bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver" id = "internalResourceViewResolver" > <!-- 前綴 --> < property name = "prefix" value = "" /> <!-- 后綴 --> < property name = "suffix" value = "" /> </ bean > |
另外,springmvc可以使用bean來接收參數(shù),因為是反射技術(shù),所以屬性字段依然要保持完全一樣。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class user { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this .username = username; } public String getPassword() { return password; } public void setPassword(String password) { this .password = password; } } |
1
2
3
4
5
|
@RequestMapping (value= "/Model" ,method=RequestMethod.POST) public String loginModel(user u){ System.out.println(u.getUsername()+ " " +u.getPassword()); return "form.jsp" ; } |
最后,前端發(fā)過來的數(shù)據(jù)是經(jīng)過json包裝的,依然可以在后端使用bean來接收。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
<%@ 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" > <script type= "text/javascript" src= "jquery.min.js" ></script> <title>登錄表單</title> </head> <script type= "text/javascript" > $(document).ready(function(){ $( "#button_submit" ).click(function(){ //序列化表單元素,返回json數(shù)據(jù) var params = $( "#userForm" ).serializeArray(); console.log(params); //也可以把表單之外的元素按照name value的格式存進來 //params.push({name:"hello",value:"man"}); $.ajax({ type: "post" , url: "Model" , data:params }); }); }); </script> <body> <form id= "userForm" > <input name= "username" type= "text" /> <br/> <input name= "password" type= "password" /> <br/> </form> <button id= "button_submit" >提交</button> <button type= "reset" >重置</button> </body> </html> |
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/chentingk/p/6073963.html