SpringMVC資料繫結demo

曾燕輝發表於2018-07-04

DataBindController.java:

package edu.mvcdemo.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import edu.mvcdemo.model.Admin;
import edu.mvcdemo.model.ListForm;
import edu.mvcdemo.model.MapForm;
import edu.mvcdemo.model.SetForm;
import edu.mvcdemo.model.User;
import edu.mvcdemo.model.XmlForm;

/**
 * @編寫人: yh.zeng
 * @編寫時間:2017-8-20 下午9:58:25
 * @檔案描述: 資料繫結Demo
 */
@Controller
@Scope("singleton") //只例項化一個bean物件(即每次請求都使用同一個bean物件),預設是singleton
public class DataBindController {
	
	/**
	 * 同屬性多物件繫結demo
	 * @param user
	 * @param admin
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/databind/demo/object", method=RequestMethod.GET)
	private String initObject(User user, Admin admin){
		StringBuilder builder = new StringBuilder();
		builder.append(user.toString()).append("<br>");
		builder.append(admin.toString());
		
		return builder.toString();
	}
	
	/**
	 * 通過@InitBinder註解將user.字首的請求引數繫結到變數user中
	 * 每個@RequestMapping註解的Controller方法執行前都會執行該方法
	 * @param binder
	 */
	@InitBinder("user")
	private void initUser(WebDataBinder binder){
		binder.setFieldDefaultPrefix("user.");
	}
	
	/**
	 * 通過@InitBinder註解將admin.字首的請求引數繫結到變數admin中
	 * 每個@RequestMapping註解的Controller方法執行前都會執行該方法
	 * @param binder
	 */
	@InitBinder("admin")
	private void initAdmin(WebDataBinder binder){
		binder.setFieldDefaultPrefix("admin.");
	}
	
	
	/**
	 * 繫結List物件
	 * @param listForm
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/databind/demo/list", method=RequestMethod.GET)
	private String initList(ListForm listForm){
		return listForm.toString();
	}
	
	/**
	 * 繫結Set物件
	 * @param listForm
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/databind/demo/set", method=RequestMethod.GET)
	private String initSet(SetForm setForm){
		return setForm.toString();
	}
	
	/**
	 * 繫結Map物件
	 * @param listForm
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/databind/demo/map", method=RequestMethod.GET)
	private String initSet(MapForm mapForm){
		return mapForm.toString();
	}
	
	/**
	 * 繫結Json物件
	 * @param listForm
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="/databind/demo/json", method=RequestMethod.POST)
	private void initJson(@RequestBody User user, HttpServletResponse reponse) throws IOException{
		reponse.setContentType("text/html");
		reponse.getWriter().println(user.toString());
	}
	
	/**
	 * 繫結Xml物件
	 * demo:
	 * <?xml version="1.0" encoding="UTF-8"?>
     * <user>
     *   <name>李四</name>
     *   <age>18</age>
     * </user>
	 * @param listForm
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="/databind/demo/xml", method=RequestMethod.POST)
	private void initXml(@RequestBody XmlForm user, HttpServletResponse reponse) throws IOException{
		reponse.setContentType("text/html");
		reponse.getWriter().println(user.toString());
	}
	
	@RequestMapping(value="/databind/demo/date", method=RequestMethod.GET)
	@ResponseBody
	private String initDate(Date date){
		return date.toString();
	}
	
	@InitBinder("date")
	private void dateFormat(WebDataBinder binder){
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}
}

Admin.java:

package edu.mvcdemo.model;

/**
 * @編寫人: yh.zeng
 * @編寫時間:2017-8-20 下午10:28:38
 * @檔案描述: todo
 */
public class Admin {
	private Integer no; // 使用者編號
	private String userName; // 使用者名稱
	private Integer age; // 年齡

	public Integer getNo() {
		return no;
	}

	public void setNo(Integer no) {
		this.no = no;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Admin {no=" + no + ", userName=" + userName + ", age=" + age
				+ "}";
	}

}

ListForm.java:

package edu.mvcdemo.model;

import java.util.List;

/**
 * @編寫人: yh.zeng
 * @編寫時間:2017-8-24 上午12:00:57
 * @檔案描述: todo
 */
public class ListForm {
	
	private List<User> users;

	/**
	 * @return the users
	 */
	public List<User> getUsers() {
		return users;
	}

	/**
	 * @param users the users to set
	 */
	public void setUsers(List<User> users) {
		this.users = users;
	}

	@Override
	public String toString() {
		return "users=" + users;
	}
	
}

MapForm.java:

package edu.mvcdemo.model;

import java.util.Map;

/**
 * @編寫人: yh.zeng
 * @編寫時間:2017-10-7 下午5:27:15
 * @檔案描述: todo
 */
public class MapForm {
	private Map<String,User> users;

	public Map<String,User> getUsers() {
		return users;
	}

	public void setUsers(Map<String,User> users) {
		this.users = users;
	}

	public String toString() {
		return "users=" + users ;
	}
	
}

MsgObject.java:

package edu.mvcdemo.model;

/**
 * @編寫人: yh.zeng
 * @編寫時間:2018-7-4 上午8:36:04
 * @檔案描述: todo
 */
public class MsgObject {

	private String msg;

	/**
	 * @return the msg
	 */
	public String getMsg() {
		return msg;
	}

	/**
	 * @param msg the msg to set
	 */
	public void setMsg(String msg) {
		this.msg = msg;
	}
	
}

SetForm.java:

package edu.mvcdemo.model;

import java.util.HashSet;
import java.util.Set;

/**
 * @編寫人: yh.zeng
 * @編寫時間:2017-10-5 下午12:27:15
 * @檔案描述: todo
 */
public class SetForm {
	
	private Set<User> users;
	
    public SetForm(){
    	users = new HashSet<User>();
    	users.add(new User());
    	users.add(new User());
   }

	public Set<User> getUsers() {
		return users;
	}

	public void setUsers(Set<User> users) {
		this.users = users;
	}

	@Override
	public String toString() {
		return "users=" + users ;
	}
	
}

User.java:

package edu.mvcdemo.model;

/**
 * @編寫人: yh.zeng
 * @編寫時間:2017-7-10 下午9:26:18
 * @檔案描述: todo
 */
public class User {

	private Integer no; // 使用者編號
	private String userName; // 使用者名稱
	private Integer age; // 年齡

	public Integer getNo() {
		return no;
	}

	public void setNo(Integer no) {
		this.no = no;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "User {no=" + no + ", userName=" + userName + ", age=" + age
				+ "}";
	}

}

XmlForm.java:

package edu.mvcdemo.model;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @編寫人: yh.zeng
 * @編寫時間:2017-10-7 下午10:28:03
 * @檔案描述: todo
 */
@XmlRootElement(name="user")
public class XmlForm {
	private String name;
	private Integer age;

	@XmlElement(name="name")
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@XmlElement(name="age")
	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "XmlForm {name=" + name + ", age=" + age + "}";
	}

}

jsondata-bind-demo.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>繫結Json資料的Demo</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
   function sendData(){
	   var jsonObject =$("#jsonData").val();
	   $.ajax({ 
		   type: "POST", 
		   url: "${pageContext.request.contextPath}/databind/demo/json", 
		   contentType: "application/json; charset=utf-8", 
		   data: jsonObject, 
		   dataType: "html", 
		   success: function (data,textStatus) { 
			   $("#returnContent").html(data);
		   }, 
		   error: function (XMLHttpRequest, textStatus, errorThrown) { 
			   $("#returnContent").html(textStatus);
		   } 
       }); 
   }
</script>
</head>
<body>
   要傳送的Json資料內容:<br>
  <textarea id="jsonData" rows="8" cols="40">{"userName":"張三","age":"22"}</textarea><br>
  <input type="button" value="傳送" onclick="sendData();"/><br>
  返回的內容:<br>
  <div id="returnContent"></div>
</body>
</html>

xmldata-bind-demo.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>繫結Xml資料的Demo</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
   function sendData(){
	   var jsonObject =$("#jsonData").val();
	   $.ajax({ 
		   type: "POST", 
		   url: "${pageContext.request.contextPath}/databind/demo/xml", 
		   contentType: "application/xml; charset=utf-8", 
		   data: jsonObject, 
		   dataType: "html", 
		   success: function (data,textStatus) { 
			   $("#returnContent").html(data);
		   }, 
		   error: function (XMLHttpRequest, textStatus, errorThrown) { 
			   $("#returnContent").html(textStatus);
		   } 
       }); 
   }
</script>
</head>
<body>
   要傳送的Xml資料內容:<br>
  <textarea id="jsonData" rows="8" cols="40"><?xml version="1.0" encoding="UTF-8"?>
<user>
    <name>李四</name>
    <age>18</age>
</user></textarea><br>
  <input type="button" value="傳送" onclick="sendData();"/><br>
  返回的內容:<br>
  <div id="returnContent"></div>
</body>
</html>

 

相關文章