提交 36f83b93 编写于 作者: Y yadong.zhang

规范化代码、解决隐性的代码问题

上级 cee87730
......@@ -19,6 +19,8 @@
*/
package com.zyd.blog;
import com.zyd.blog.business.consts.DateConst;
import com.zyd.blog.util.DateUtil;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
......@@ -26,6 +28,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.util.Date;
/**
* 程序启动类
*
......@@ -46,6 +50,6 @@ public class BlogWebApplication implements ApplicationRunner {
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
System.out.println("启动完成");
System.out.println("博客部署完成,当前时间:" + DateUtil.date2Str(new Date(), DateConst.YYYY_MM_DD_HH_MM_SS_EN));
}
}
/**
* MIT License
*
* Copyright (c) 2018 yadong.zhang
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
......@@ -23,6 +19,8 @@
*/
package com.zyd.blog.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
......@@ -62,6 +60,7 @@ import java.util.Map;
@RequestMapping("/error")
@EnableConfigurationProperties({ServerProperties.class})
public class ErrorPagesController implements ErrorController {
private static final Logger LOG = LoggerFactory.getLogger(ErrorPagesController.class);
private ErrorAttributes errorAttributes;
......@@ -92,7 +91,7 @@ public class ErrorPagesController implements ErrorController {
response.setStatus(HttpStatus.FORBIDDEN.value());
// 404拦截规则,如果是静态文件发生的404则不记录到DB
Map<String, Object> model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML));
if (String.valueOf(model.get("path")).indexOf(".") == -1) {
if (!String.valueOf(model.get("path")).contains(".")) {
model.put("status", HttpStatus.FORBIDDEN.value());
}
return new ModelAndView("error/403", model);
......@@ -134,10 +133,7 @@ public class ErrorPagesController implements ErrorController {
if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
return true;
}
if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM) {
return getTraceParameter(request);
}
return false;
return include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM && getTraceParameter(request);
}
......@@ -163,10 +159,7 @@ public class ErrorPagesController implements ErrorController {
*/
private boolean getTraceParameter(HttpServletRequest request) {
String parameter = request.getParameter("trace");
if (parameter == null) {
return false;
}
return !"false".equals(parameter.toLowerCase());
return parameter != null && !"false".equals(parameter.toLowerCase());
}
/**
......@@ -184,6 +177,7 @@ public class ErrorPagesController implements ErrorController {
try {
return HttpStatus.valueOf(statusCode);
} catch (Exception ex) {
LOG.error("获取当前HttpStatus发生异常", ex);
return HttpStatus.INTERNAL_SERVER_ERROR;
}
}
......
......@@ -54,6 +54,7 @@ public class RenderController {
* sidebar部分的推荐、近期和随机tab页中显示的文章数
*/
private static final int SIDEBAR_ARTICLE_SIZE = 8;
private static final String INDEX_URL = "index";
@Autowired
private BizArticleService bizArticleService;
......@@ -88,7 +89,7 @@ public class RenderController {
*/
@RequestMapping("/")
public ModelAndView home(ArticleConditionVO vo, Model model) {
model.addAttribute("url", "index");
model.addAttribute("url", INDEX_URL);
loadIndexPage(vo, model);
return ResultUtil.view("index");
......@@ -105,7 +106,7 @@ public class RenderController {
@RequestMapping("/index/{pageNumber}")
public ModelAndView type(@PathVariable("pageNumber") Integer pageNumber, ArticleConditionVO vo, Model model) {
vo.setPageNumber(pageNumber);
model.addAttribute("url", "index");
model.addAttribute("url", INDEX_URL);
loadIndexPage(vo, model);
return ResultUtil.view("index");
......@@ -208,11 +209,10 @@ public class RenderController {
/**
* 关于
*
* @param model
* @return
*/
@GetMapping("/about")
public ModelAndView about(Model model) {
public ModelAndView about() {
return ResultUtil.view("about");
}
......@@ -231,11 +231,10 @@ public class RenderController {
/**
* 留言板
*
* @param model
* @return
*/
@GetMapping("/guestbook")
public ModelAndView guestbook(Model model) {
public ModelAndView guestbook() {
return ResultUtil.view("guestbook");
}
......@@ -255,11 +254,10 @@ public class RenderController {
/**
* 免责声明
*
* @param model
* @return
*/
@GetMapping("/disclaimer")
public ModelAndView disclaimer(Model model) {
public ModelAndView disclaimer() {
return ResultUtil.view("disclaimer");
}
......
......@@ -34,6 +34,8 @@ import com.zyd.blog.framework.exception.ZhydLinkException;
import com.zyd.blog.framework.object.ResponseVO;
import com.zyd.blog.util.RestClientUtil;
import com.zyd.blog.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
......@@ -59,6 +61,8 @@ import java.util.Map;
@RequestMapping("/api")
public class RestApiController {
private static final Logger LOG = LoggerFactory.getLogger(RestApiController.class);
@Autowired
private SysLinkService sysLinkService;
@Autowired
......@@ -72,14 +76,15 @@ public class RestApiController {
@PostMapping("/autoLink")
public ResponseVO autoLink(@Validated Link link, BindingResult bindingResult) {
System.out.println("申请友情链接......");
System.out.println(JSON.toJSONString(link));
LOG.info("申请友情链接......");
LOG.info(JSON.toJSONString(link));
if (bindingResult.hasErrors()) {
return ResultUtil.error(bindingResult.getFieldError().getDefaultMessage());
}
try {
sysLinkService.autoLink(link);
} catch (ZhydLinkException e) {
LOG.error("客户端自助申请友链发生异常", e);
return ResultUtil.error(e.getMessage());
}
return ResultUtil.success("已成功添加友链,祝您生活愉快!");
......@@ -97,12 +102,13 @@ public class RestApiController {
try {
json = json.replaceAll("portraitCallBack|\\\\s*|\\t|\\r|\\n", "");
json = json.substring(1, json.length() - 1);
System.out.println(json);
LOG.info(json);
JSONObject object = JSONObject.parseObject(json);
JSONArray array = object.getJSONArray(qq);
nickname = array.getString(6);
} catch (Exception e) {
e.printStackTrace();
LOG.error("通过QQ号获取用户昵称发生异常", e);
}
}
resultMap.put("avatar", "https://q1.qlogo.cn/g?b=qq&nk=" + qq + "&s=40");
......@@ -130,6 +136,7 @@ public class RestApiController {
mailService.sendToAdmin(comment);
}
} catch (ZhydCommentException e) {
LOG.error("评论发生异常", e);
return ResultUtil.error(e.getMessage());
}
return ResultUtil.success("评论发表成功,系统正在审核,请稍后刷新页面查看!");
......@@ -166,7 +173,7 @@ public class RestApiController {
}
@PostMapping("/listNotice")
public ResponseVO listNotice(String token) {
public ResponseVO listNotice() {
return ResultUtil.success("", noticeService.listRelease());
}
......
......@@ -19,10 +19,12 @@
*/
package com.zyd.blog.core.websocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.Set;
/**
* websocket工具类,支持单条发送和批量发送
......@@ -35,6 +37,8 @@ import java.util.concurrent.CopyOnWriteArraySet;
*/
public class WebSocketUtil {
private static final Logger LOG = LoggerFactory.getLogger(WebSocketUtil.class);
/**
* 向客户端发送消息
*
......@@ -44,8 +48,12 @@ public class WebSocketUtil {
* 客户端session
* @throws IOException
*/
public static void sendMessage(String message, Session session) throws IOException {
session.getAsyncRemote().sendText(message);
public static void sendMessage(String message, Session session) {
try {
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
LOG.error("websocket-->向客户端发送数据发生异常", e);
}
}
/**
......@@ -57,17 +65,11 @@ public class WebSocketUtil {
* 客户端session列表
* @throws IOException
*/
public static void broadcast(String message, CopyOnWriteArraySet<Session> sessionSet) {
Iterator<Session> it = sessionSet.iterator();
public static void broadcast(String message, Set<Session> sessionSet) {
// 多线程群发
while (it.hasNext()) {
Session entry = it.next();
for (Session entry : sessionSet) {
if (entry.isOpen()) {
try {
sendMessage(message, entry);
} catch (IOException e) {
e.printStackTrace();
}
sendMessage(message, entry);
} else {
sessionSet.remove(entry);
}
......
......@@ -28,7 +28,6 @@ import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
......@@ -43,7 +42,7 @@ import java.util.concurrent.atomic.AtomicInteger;
@Component
public class ZydWebSocket {
private static final Logger LOGGER = LoggerFactory.getLogger(ZydWebSocket.class);
private static final Logger LOG = LoggerFactory.getLogger(ZydWebSocket.class);
/**
* 初始在线人数
*/
......@@ -51,7 +50,7 @@ public class ZydWebSocket {
/**
* 线程安全的socket集合
*/
private static CopyOnWriteArraySet<Session> webSocketSet = new CopyOnWriteArraySet<Session>();
private static CopyOnWriteArraySet<Session> webSocketSet = new CopyOnWriteArraySet<>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
......@@ -64,8 +63,8 @@ public class ZydWebSocket {
public void onOpen(Session session) {
webSocketSet.add(session);
onlineCount.incrementAndGet();
System.out.println("有链接加入,当前在线人数为:" + getOnlineCount());
WebSocketUtil.broadcast(getOnlineCount() + "", webSocketSet);
LOG.info("有链接加入,当前在线人数为: {}", getOnlineCount());
WebSocketUtil.broadcast(getOnlineCount(), webSocketSet);
}
/**
......@@ -74,8 +73,8 @@ public class ZydWebSocket {
@OnClose
public void onClose() {
onlineCount.decrementAndGet();
System.out.println("有链接关闭,当前在线人数为:" + getOnlineCount());
WebSocketUtil.broadcast(getOnlineCount() + "", webSocketSet);
LOG.info("有链接关闭,当前在线人数为: {}", getOnlineCount());
WebSocketUtil.broadcast(getOnlineCount(), webSocketSet);
}
/**
......@@ -86,15 +85,11 @@ public class ZydWebSocket {
*/
@OnMessage
public void onMessage(String message, Session session) {
LOGGER.info("{}来自客户端的消息:{}", session.getId(), message);
try {
WebSocketUtil.sendMessage(message, session);
} catch (IOException e) {
e.printStackTrace();
}
LOG.info("{}来自客户端的消息:{}", session.getId(), message);
WebSocketUtil.sendMessage(message, session);
}
private int getOnlineCount() {
return onlineCount.get();
private String getOnlineCount() {
return Integer.toString(onlineCount.get());
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册