目錄.png
以使用者登入為栗子,示例
API
請求時處理技巧,和
API
傳回資料時如何處理。
一、API傳回時:傳回的json資料
使用
spring mvc
預設配置就可以傳回
json
了,不過需要
jackson
的
jar
包
APIResponse
是一個實體類,配合
@ResponseBody
就會自動轉成
Json
@RequestMapping("user")
@Controller
public class UserController {
@Resource
private UserService userService;
@RequestMapping(value = "/login", method = RequestMethod.POST, headers = "api-version=1")
public @ResponseBody
APIResponse login(HttpServletRequest request) {
return userService.login(new APIRequest(request));
}
@RequestMapping(value = "/query", method = RequestMethod.GET, headers = "api-version=1")
public @ResponseBody
APIResponse query() {
return userService.allUsers();
}
}
二、API請求時:提取和解析參數
springMVC
背景控制層提取和解析請求參數的方式主要有兩種
-
;request.getParameter("name")
- 通過注解
直接擷取;@RequestParam
1.注解方式:@ResponseBody
// 必傳且參數名為`userName`
@RequestParam String userName
// 必傳且指定參數為 user_name
@RequestParam(value="user_name") String userName
// 辨別是否為必傳,required=false 會給參數指派為null
@RequestParam(value="aa", required=true)
完整的如下:
@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam("user_name") String userName) {
APIResponse api = new APIResponse();
api.setUserName(userName);
...
}
value
用來指定要傳入值的
id
名稱
String userName, ModelMap model 是接受 value 傳給的值
2.HttpServletRequest 方式
如果參較多的時候,注解方式可能顯得比較臃腫,這時候也可以使用
HttpServletRequest
提取參數,
request.getParameter("username")
也比較簡單。
這裡着重
Controller
中接收的
HttpServletRequest
做進一步封裝。
APIRequest
對
HttpServletRequest
進一步封裝,提供常用的屬性包括請求的URL、請求參數等。如果提供的屬性不能滿足需求,還提供了原 HttpServletRequest 對象屬性 request。
建立
API
請求的實體類
package com.lugq.web.tools.api;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* API請求實體類
*/
public class APIRequest {
/**
* Raw Request, 單元測試時為null
*/
private HttpServletRequest request;
/**
* 請求頭
*/
private Map<String, Object> header;
/**
* 請求參數
*/
private Map<String, Object> params;
/**
* 用戶端送出請求時的完整URL
*/
private String url;
/**
* 請求行中的資源名部分
*/
private String uri;
/**
* 請求行中的參數部分
*/
private String queryString;
/**
* 請求方法
*/
private String method;
/**
* 送出請求的客戶機的IP位址
*/
private String remoteAddr;
/**
* 送出請求的客戶機的完整主機名
*/
private String remoteHost;
/**
* 送出請求的客戶機的網絡端口号
*/
private int remotePort;
/**
* WEB伺服器的IP位址
*/
private String localAddr;
/**
* WEB伺服器的主機名
*/
private String localName;
/**
* WEB伺服器的網絡端口号
*/
private int localPort;
/**
* 編碼格式
*/
private String characterEncoding;
/**
* 上下文
*/
private String contextPath;
public APIRequest() {
super();
}
public APIRequest(HttpServletRequest request) {
this.request = request;
header = new HashMap<String, Object>();
Enumeration e = request.getHeaderNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
Object value = request.getHeader(name);
header.put(name, value);
}
params = getParamesMap(request.getParameterMap());
url = request.getRequestURL().toString();
uri = request.getRequestURI();
remoteAddr = request.getRemoteAddr();
remoteHost = request.getRemoteHost();
remotePort = request.getRemotePort();
contextPath = request.getContextPath();
localAddr = request.getLocalAddr();
characterEncoding = request.getCharacterEncoding();
localName = request.getLocalName();
localPort = request.getLocalPort();
method = request.getMethod();
queryString = request.getQueryString();
}
private Map<String, Object> getParamesMap(Map properties) {
Map<String, Object> returnMap = new HashMap<String, Object>();
Iterator entries = properties.entrySet().iterator();
Map.Entry entry;
String name;
String value = "";
while (entries.hasNext()) {
entry = (Map.Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if (null == valueObj) {
value = "";
} else if (valueObj instanceof String[]) {
String[] values = (String[]) valueObj;
for (String v : values) {
value = v + ",";
}
value = value.substring(0, value.length() - 1);
} else {
value = valueObj.toString();
}
returnMap.put(name, value);
}
return returnMap;
}
public Object getParameter(String s) {
return params.get(s);
}
public void setAttribute(String s, Object o) {
if (params == null) params = new HashMap<String, Object>();
params.put(s, o.toString());
}
// 省略 get set method. 自行補充
......
}
在控制層
controller
中實作栗子:
@RequestMapping("user")
@Controller
public class UserController {
@Resource
private UserService userService;
@RequestMapping(value = "/login", method = RequestMethod.POST, headers = "api-version=1")
public @ResponseBody
APIResponse login(HttpServletRequest request) {
// 将HttpServletRequest執行個體指派到APIRequest對其進一步封裝
return userService.login(new APIRequest(request));
}
}
Service 層的邏輯處理如下
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserMapper mapper;
public APIResponse login(APIRequest request) {
// 擷取請求參數
String username = (String) request.getParameter("username");
String password = (String) request.getParameter("password");
// 處理業務邏輯
User user = mapper.selectUserByUsername(username);
APIStatus status = API_SUCCESS;
if (user == null) {
status = API_USER_NOT_EXIST;
} else {
if (!MD5Util.md5(password).equals(user.getPassword()))
status = API_USER_PASSWORD_ERROR;
}
// 傳回APIResponse對象,配合@ResponseBody轉為Json
return APIUtil.getResponse(status, user);
}
public APIResponse allUsers() {
List<User> users = mapper.selectAllUser();
return APIUtil.getResponse(API_SUCCESS, users);
}
}