Spring Controller 編寫 示例
package com.eduoinfo.finances.bank.web.controller;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.eduoinfo.finances.bank.core.entity.JsonResult;
import com.eduoinfo.finances.bank.web.dao.TestMapper;
import com.eduoinfo.finances.bank.web.model.Test;
import com.eduoinfo.finances.bank.web.model.User;
import com.eduoinfo.finances.bank.web.service.impl.TestServiceImpl;
/**
* Spring MVC Controller 編寫示例
*
* @author StarZou
* @since 2014年4月26日 上午11:02:20
**/
@Controller
@RequestMapping(value = "/test")
public class TestController {
/**
* Service 業務層 注入
*/
@Resource
private TestServiceImpl testServiceImpl;
/**
* Dao 注入
*/
@Resource
private TestMapper testMapper;
/**
* 通過註解綁定 參數值 示例
*
* @PathVariable : 從url 中 取得 參數值
* @RequestHeader : 從請求頭中 取得 參數值
* @RequestParam : 從請求參數中 取得 值
* @CookieValue : 從 cookie 中取值
*/
@RequestMapping("/**/{id}")
@ResponseBody
public String testValue(@PathVariable("id") String id, @RequestHeader("User-Agent") String userAgent,
@RequestParam(value = "name", defaultValue = "null", required = false) String name, @CookieValue("JSESSIONID") String jsessionid) {
return userAgent + "<br>" + jsessionid + "<br>" + id + "<br>" + name;
}
/**
* 使用Servlet API對象作爲入參
*
* @param request
* @param response
*/
@RequestMapping("/request")
public void req(HttpServletRequest request, HttpServletResponse response) {
Assert.notNull(request, "請求不能爲空");
response.setStatus(200);
}
/**
* 使用IO對象作爲入參
*
* @param os
* @throws IOException
*/
@RequestMapping("/stream/{path}")
public void img(OutputStream os, @PathVariable("path") String path) throws IOException {
ClassPathResource res = new ClassPathResource("/spring-mvc.xml");
FileCopyUtils.copy(res.getInputStream(), os);
}
/**
* 表單提交 示例,bean的屬性 自動 裝配 <br>
* 指定方法類型:method = RequestMethod.POST <br>
* http://localhost/test/rest/test/body?name=starzou&password=123
*
* @param user
* @return
*/
@RequestMapping(value = "/body")
@ResponseBody
public Object body(User user) {
return user;
}
/**
* httpEntity.getHeaders() 得到所有請求頭
*
* @param httpEntity
* @return
*/
@RequestMapping("/http")
@ResponseBody
public Object http(HttpEntity<String> httpEntity) {
return httpEntity.getHeaders().entrySet();
}
/**
* 調用 業務層 方法示例
*
* @return
*/
@RequestMapping("/date")
@ResponseBody
public String date() {
return testServiceImpl.date();
}
/**
* Spring MVC將匹配方法參數名URI模板變量名稱
*
* @param x
* @param y
* @return
*/
@RequestMapping("/var/{x}/{y}")
@ResponseBody
public String var(@PathVariable String x, @PathVariable String y) {
return x + "<br>" + y;
}
/**
* 測試 mybaits generator生成的 dao model,進行 數據庫操作
*
* @return
*/
@RequestMapping("/tt/add")
@ResponseBody
public Object testAdd() {
com.eduoinfo.finances.bank.web.model.Test test = new com.eduoinfo.finances.bank.web.model.Test();
final long currentTimeMillis = System.currentTimeMillis();
test.setTname("tname : " + currentTimeMillis);
test.setTdate(new Date());
testMapper.insert(test);
return test;
}
/**
* 數據庫 查詢
*
* @return
*/
@RequestMapping("/tt/select")
@ResponseBody
public Object testSelect() {
final List<Test> list = testMapper.selectByExample(null);
return list;
}
/**
* 測試 spring mvc 返回 json , 封裝 Json 格式數據, 減少 類型轉換
*
* @return
*/
@RequestMapping("/json")
@ResponseBody
public JsonResult<Object[]> returnJson() {
// 實際情況 下 String,可能是一個 自定義的Java 類,比如 User , 通常是在 數據庫查詢
List<String> data = new ArrayList<>();
Set<String> data2 = new HashSet<>();
Map<String, String> data3 = new HashMap<>();
int i = 0;
while (i < 10) {
String value = "data-" + (++i);
data.add(value);
data2.add(value);
data3.put(value, value);
}
// 組裝 查詢的 結果 , 添加消息 和 是否成功的標識
JsonResult<List<String>> jsonResult = new JsonResult<>(data, "This is a message.", true);
JsonResult<Set<String>> jsonResult2 = new JsonResult<>(data2, "This is a message.", true);
JsonResult<Map<String, String>> jsonResult3 = new JsonResult<>(data3, "This is a message.", true);
// 複雜一點的 封裝
Object[] objs = { jsonResult, jsonResult2, jsonResult3 };
JsonResult<Object[]> jsonObj = new JsonResult<Object[]>(objs);
return jsonObj;
}
}