只针对spring框架
controller代码:
/**
* 增加配置
*/
@PostMapping("/add")
public void addConfig(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("application/json;charset=UTF-8");
//返回了一个json格式的字符串。。
String result = configService.add(request);
response.getOutputStream().write(result.getBytes());
response.getOutputStream().flush();
}
services代码:
/**
* !!!错误的示例
*
* @param request
* @return
*/
public String add(HttpServletRequest request) {
Map<String, Object> data = new HashMap<String, Object>();
try {
String name = (String) request.getParameter("name");
String value = (String) request.getParameter("value");
//示例代码
long newID = add(name, value);
data.put("code", 0);
data.put("newID", newID);
} catch (CheckException e) {
// 参数等校验出错,已知异常,不需要打印堆栈,返回码为-1
data.put("code", -1);
data.put("msg", e.getMessage());
} catch (Exception e) {
// 其他未知异常,需要打印堆栈分析用,返回码为99
logger.error("add config error", e);
data.put("code", 99);
data.put("msg", e.toString());
}
return JSONObject.toJSONString(data);
}
所以说,simple is not easy。很多人就是因为觉得简单,所以功能完成自己测试ok了就算了,没有思考有没有更加好的方式。归根到底是因为编码习惯太糟糕,写的代码太烂,导致无法定位频繁修改频繁出问题。
@PostMapping("/delete")
public Map<String, Object> delete(long id, String lang) {
Map<String, Object> data = new HashMap<String, Object>();
boolean result = false;
try {
// 语言(中英文提示不同)
Locale local = "zh".equalsIgnoreCase(lang) ? Locale.CHINESE : Locale.ENGLISH;
result = configService.delete(id, local);
data.put("code", 0);
} catch (CheckException e) {
// 参数等校验出错,这类异常属于已知异常,不需要打印堆栈,返回码为-1
data.put("code", -1);
data.put("msg", e.getMessage());
} catch (Exception e) {
// 其他未知异常,需要打印堆栈分析用,返回码为99
log.error(e);
data.put("code", 99);
data.put("msg", e.toString());
}
data.put("result", result);
return data;
}
其实上面的代码也没有大问题。而我接手之后,我会开发自己的代码框架,最后制定代码框架交付的代码如下(这是controller的部分):
@PostMapping("/delete")
public ResultBean<Boolean> delete(long id) {
return new ResultBean<Boolean>(configService.delete(id));
}
用到的技术就是AOP,也不是什么高深技术。怎么样?代码量就一行,特性一个都没有丢。这就是我们项目组现在的controller的样子!(如果恰好有我带过的项目组的人,看到ResultBean<>应该很熟悉应该知道我是谁了)
Java团长
专注于Java干货分享
![640](https://i-blog.csdnimg.cn/blog_migrate/796e140d10ce235a291dcd07af223068.jpeg)
扫描上方二维码获取更多Java干货