以用户登录为栗子,示例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);
}
}