4. controller
4.1. HomeController
@Controller
public class HomeController {
@Autowired
NewsService newsService;
@Autowired
UserService userService;
@Autowired
LikeService likeService;
@Autowired
HostHolder hostHolder;
@Autowired
MailSender mailSender;
private List<ViewObject> getNews(int userId, int offset, int limit) {
List<News> newsList = newsService.getLatestNews(userId, offset, limit);
int localUserId = hostHolder.getUser() != null ? hostHolder.getUser().getId() : 0;
List<ViewObject> vos = new ArrayList<>();
for (News news : newsList) {
ViewObject vo = new ViewObject();
vo.set("news", news);
vo.set("user", userService.getUser(news.getUserId()));
if (localUserId != 0) {
vo.set("like", likeService.getLikeStatus(localUserId, EntityType.ENTITY_NEWS, news.getId()));
} else {
vo.set("like", 0);
}
vos.add(vo);
}
return vos;
}
@RequestMapping(path = {"/", "/index"}, method = {RequestMethod.GET, RequestMethod.POST})
public String index(Model model,
@RequestParam(value = "pop", defaultValue = "0") int pop) {
model.addAttribute("vos", getNews(0, 0, 10));
if (hostHolder.getUser() != null) {
pop = 0;
}
model.addAttribute("pop", pop);
return "home";
}
@RequestMapping(path = {"/user/{userId}"}, method = {RequestMethod.GET, RequestMethod.POST})
public String userIndex(Model model, @PathVariable("userId") int userId) {
model.addAttribute("vos", getNews(userId, 0, 10));
return "home";
}
}
4.2. IndexController
//@Controller
public class IndexController {
private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
@Autowired
private ToutiaoService toutiaoService;
@RequestMapping(path = {"/", "/index"}, method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String index(HttpSession session) {
logger.info("Visit Index");
return "Hello NowCoder," + session.getAttribute("msg")
+ "<br> Say:" + toutiaoService.say();
}
@RequestMapping(value = {"/profile/{groupId}/{userId}"})
@ResponseBody
public String profile(@PathVariable("groupId") String groupId,
@PathVariable("userId") int userId,
@RequestParam(value = "type", defaultValue = "1") int type,
@RequestParam(value = "key", defaultValue = "nowcoder") String key) {
return String.format("GID{%s},UID{%d},TYPE{%d},KEY{%s}", groupId, userId, type, key);
}
@RequestMapping(value = {"/vm"})
public String news(Model model) {
model.addAttribute("value1", "vv1");
List<String> colors = Arrays.asList(new String[]{"RED", "GREEN", "BLUE"});
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < 4; ++i) {
map.put(String.valueOf(i), String.valueOf(i * i));
}
model.addAttribute("colors", colors);
model.addAttribute("map", map);
model.addAttribute("user", new User("Jim"));
return "news";
}
@RequestMapping(value = {"/request"})
@ResponseBody
public String request(HttpServletRequest request,
HttpServletResponse response,
HttpSession session) {
StringBuilder sb = new StringBuilder();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
sb.append(name + ":" + request.getHeader(name) + "<br>");
}
for (Cookie cookie : request.getCookies()) {
sb.append("Cookie:");
sb.append(cookie.getName());
sb.append(":");
sb.append(cookie.getValue());
sb.append("<br>");
}
sb.append("getMethod:" + request.getMethod() + "<br>");
sb.append("getPathInfo:" + request.getPathInfo() + "<br>");
sb.append("getQueryString:" + request.getQueryString() + "<br>");
sb.append("getRequestURI:" + request.getRequestURI() + "<br>");
return sb.toString();
}
@RequestMapping(value = {"/response"})
@ResponseBody
public String response(@CookieValue(value = "nowcoderid", defaultValue = "a") String nowcoderId,
@RequestParam(value = "key", defaultValue = "key") String key,
@RequestParam(value = "value", defaultValue = "value") String value,
HttpServletResponse response) {
response.addCookie(new Cookie(key, value));
response.addHeader(key, value);
return "NowCoderId From Cookie:" + nowcoderId;
}
@RequestMapping("/redirect/{code}")
public String redirect(@PathVariable("code") int code,
HttpSession session) {
/*
RedirectView red = new RedirectView("/", true);
if (code == 301) {
red.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
}
return red;*/
session.setAttribute("msg", "Jump from redirect.");
return "redirect:/";
}
@RequestMapping("/admin")
@ResponseBody
public String admin(@RequestParam(value = "key", required = false) String key) {
if ("admin".equals(key)) {
return "hello admin";
}
throw new IllegalArgumentException("Key 错误");
}
@ExceptionHandler()
@ResponseBody
public String error(Exception e) {
return "error:" + e.getMessage();
}
}
1)model.addAttribute("k",v)
model.addAttribute("editPageFlg",editPageFlg)的作用:类似于hashmap。
向Map里面添加键值对,key="editPageFlg",value=editPageFlg。
此类来源于ModelMap的定义,
public class ModelMap extends LinkHashMap<String,Object>
其中addAttribute的源码为:
public ModelMap addAttribute(String attributeName, Object attributeValue){
Assert.notNull(attributeName, "Model attribute name must not be null");
put(attributeName, attributeValue);
return this;
}
在put之前,会进行判空检测。这就是addAttribute与put的区别。
2)@CookieValue
@CookieValue的作用
用来获取Cookie中的值
@CookieValue参数
1、value:参数名称
2、required:是否必须
3、defaultValue:默认值
3)用 JSP 设置 Cookies
用 JSP 设置 Cookies 包括三个步骤:
- (1) 创建一个 Cookie 对象
用 cookie 的名称和值调用 cookie 构造函数,名称和值是字符串。
Cookie cookie = new Cookie("key","value");
这个名字和值都不应该包含空格或任何以下字符:[ ] ( ) = , " / ? @ : ;
- (2) 设置最大持续时间
使用setMaxAge
指定 cookie 的有效期是多长时间(以秒为单位)。以下是建立了一个持续 24 小时的 cookie。
cookie.setMaxAge(60*60*24);
- (3) 将 cookie 发送到 HTTP 响应标题中
使用response.addCookie
在 HTTP 响应标题中添加 cookies,如下所示:
response.addCookie(cookie);
4)request和response方法的总结
Request
JSP中的隐藏对象 -- request
request
可以在JSP网页中使用,在转译为Servlet之后,它会转换为javax.servlet.http.HttpServletRequest
型态的对象,HttpServletRequest对象是有关于客户端所发出的请求之对象,只要是有关于客户端请求的信息,都可以藉由它来取得,例如请求标头、请求方法、请求参数、使用者IP等等信息。
方法 | 作用 |
---|---|
getParameterNames() | 取得客户端所发出的请求参数名称 |
getParameter() | 可以让您指定请求参数名称,以取得对应的设定值 |
getServerName() | 请求的服务器 |
getProtocol() | 使用协议 |
getMethod() | 请求方法 |
getServerPort() | 请求端口号 |
getContextPath() | Context路径. context理解为上下文比较好(也就是一个项目) |
getServletPath() | Servlet路径 |
getRequestURI() | URI路径 |
getQueryString() | 查询字符串 |
getRemoteAddr() | 使用者主机IP |
getRemotePort() | 使用者使用端口号 |
response
JSP中的隐藏对象 --response
JSP的response
隐藏对象在转换为Servlet之后,对应于HttpServletResponse型态对象,HttpServletResponse
对象是有关于对客户端请求之响应,您可以利用它来设定一些要响应的讯息,例如标题信息、响应状态码等.
方法 | 作用 |
---|---|
setHeader() | 是一个通用的标头设定方法,您可以用它来设定任何「名称/值」的标头 |
setIntHeader() | 是专门用来设定整数值标头的版本 |
setDateHeader() | 是setHeader()的Date设定版本,第二个参数是设定Date的Long数值,0表示GMT 1970/1/1 00:00。 |
setStatus() | 是用来设定回应的状态码,例如404 Not Found,HttpServletResponse类中提供了一些助忆常数设定,例如SC_NOT_FOUND就是表示404状态码(可以在Servlet API文件中查询相关的助忆常数) |
sendError() | 会根据服务器的预设错误网页回报方式显示错误讯息 |
sendRedirect() | 设置重定向页面 |
getWriter() | 取得PrintWriter对象,由它来写出响应至服务器的本体信息 |
5)HttpServletResponse和HttpServletRequest
HttpServletResponse和HttpServletRequest
Request
Request是Servlet.service()方法的一个参数,类型为javax.servlet.http.HttpServletRequest
。在客户端发出每个请求时,服务器都会创建一个request对象,并把请求数据封装到request中,然后在调用Servlet.service()方法时传递给service()方法,这说明在service()方法中可以通过request对象来获取请求数据
Request的功能可以分为以下几种:
- 封装了请求头数据
- 封装了请求正文数据,如果是GET请求,那么就没有正文
- request是一个域对象,可以把它当成Map来添加获取数据
- request提供了请求转发和请求包含功能
Response
Response是Servlet.service方法的一个参数,类型为javax.servlet.http.HttpServletResponse
。在客户端发出每个请求时,服务器都会创建一个response对象,并传入给Servlet.service()方法。response对象是用来对客户端进行响应的,这说明在service()方法中使用response对象可以完成对客户端的响应工作
response对象的功能分为以下四种:
- 设置响应头信息
- 发送状态码
- 设置响应正文
- 重定向
6)numeration接口
Enumeration是java.util中的一个接口类,在Enumeration中封装了有关枚举数据集合的方法,与Iterator差不多,用来遍历集合中的元素 但是枚举Enumeration只提供了遍历Vector和Hashtable
类型集合元素的功能,这种类型的集合对象通过调用elements()方法获取一个Enumeration对象 然后Enumeratino对象再调用以下方法来对集合中的元素进行遍历。
package java.util;
public interface Enumeration<E> {
boolean hasMoreElements();
E nextElement();
}
方法 | 描述 |
---|---|
boolean hasMoreElements( ) | 测试此枚举是否包含更多的元素 |
Object nextElement( ) | 如果此枚举对象至少还有一个可提供的元素,则返回此枚举的下一个元素 |
7)Iterator接口
package java.util;
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
8) Spring MVC 重定向常用处理方式
Controller 视图方法间的跳转,无非就是带参跳转和不带参跳转。常用的方法有通过 String 映射 RequestMapping
实现重定向,或者通过 ModelAndView
对象,又或者是 RedirectView
对象,下面逐一说明。
String 重定向
是 return 映射到另一个 Controller 方法的字符串。如果有请求参数,就拼接在 RequestMapping 映射的字符串后面。
// 返回字符串映射的方式
@RequestMapping("hello")
public String hello(HttpServletRequest req, HttpServletResponse resp) {
doSomething();
return "redirect:/bye";
// return "redirect:/bye?username=yxd";
}
ModelAndView 重定向
另一种方法是通过返回 ModelAndView
对象来实现跳转。类似的,如果有请求参数,也可以通过类似 GET 参数拼接的方式:
// 返回 ModelAndView 对象
@RequestMapping("hello")
public ModelAndView hello(HttpServletRequest req, HttpServletResponse resp) {
doSomething();
return new ModelAndView("redirect:/bye");
// return new ModelAndView("redirect:/bye?username=yxd");
}
RedirectView 重定向
还有一种方法是通过返回 RedirectView
对象实现跳转,该方法和上面的不同之处在于,RedirectView
对象不需要设置 redirect 前缀:
// 返回 RedirectView 对象
@RequestMapping("hello")
public RedirectView hello() {
doSomething();
return new RedirectView("/bye");
// return new RedirectView("bye?username=yxd");
}
4.3. LikeController
@Controller
public class LikeController {
@Autowired
LikeService likeService;
@Autowired
HostHolder hostHolder;
@Autowired
NewsService newsService;
@Autowired
EventProducer eventProducer;
@RequestMapping(path = {"/like"}, method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String like(@Param("newId") int newsId) {
long likeCount = likeService.like(hostHolder.getUser().getId(), EntityType.ENTITY_NEWS, newsId);
System.out.println("like likecount " + likeCount);//20180802
// 更新喜欢数
News news = newsService.getById(newsId);
newsService.updateLikeCount(newsId, (int) likeCount);
eventProducer.fireEvent(new EventModel(EventType.LIKE)
.setActorId(hostHolder.getUser().getId()).setEntityId(newsId)
.setEntityType(EntityType.ENTITY_NEWS).setEntityOwnerId(news.getUserId()));
//return "redirect:/"; //20180802
return ToutiaoUtil.getJSONString(0, String.valueOf(likeCount));
}
@RequestMapping(path = {"/dislike"}, method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String dislike(@Param("newId") int newsId) {
long likeCount = likeService.disLike(hostHolder.getUser().getId(), EntityType.ENTITY_NEWS, newsId);
// 更新喜欢数
newsService.updateLikeCount(newsId, (int) likeCount);
//return "redirect:/"; //20180802
return ToutiaoUtil.getJSONString(0, String.valueOf(likeCount));
}
}
4.4. LoginController
@Controller
public class LoginController {
private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
@Autowired
UserService userService;
@Autowired
EventProducer eventProducer;
@RequestMapping(path = {"/reg/"}, method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String reg(Model model, @RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam(value = "rember", defaultValue = "0") int rememberme,
HttpServletResponse response) {//用户名,密码,记住登陆
logger.info("/reg/ " + username + " " + password + " " + rememberme);//20180802
try {
Map<String, Object> map = userService.register(username, password);
if (map.containsKey("ticket")) {
Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
cookie.setPath("/");//设置为全站有效
if (rememberme > 0) {
cookie.setMaxAge(3600 * 24 * 5);//勾选过记住我,则有五天的有效时间
}
response.addCookie(cookie);
logger.info("cookie : " + cookie.getValue() +" " + cookie.getName());//20180802
//return "redirect:/";
return ToutiaoUtil.getJSONString(0, "注册成功");
} else {
model.addAttribute("error","注册失败,请重新注册");//20180802
//return "redirect:/register";//20180802
return ToutiaoUtil.getJSONString(1, map);
}
} catch (Exception e) {
logger.error("注册异常" + e.getMessage());
model.addAttribute("error","注册异常");//20180802
//return "redirect:/register";//20180802
return ToutiaoUtil.getJSONString(1, "注册异常");
}
}
// @RequestMapping(value = "/login",method = RequestMethod.GET)
// public String login(){
//
// return "login";
// }
//
// @RequestMapping(value = "/register",method = RequestMethod.GET)
// public String register(){
//
// return "register";
// }
@RequestMapping(path = {"/login/"}, method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String login(Model model, @RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam(value = "rember", defaultValue = "0") int rememberme,
HttpServletResponse response) {
try {
Map<String, Object> map = userService.login(username, password);
if (map.containsKey("ticket")) {
Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
cookie.setPath("/");
if (rememberme > 0) {
cookie.setMaxAge(3600 * 24 * 5);
}
response.addCookie(cookie);
eventProducer.fireEvent(new EventModel(EventType.LOGIN)
.setActorId((int) map.get("userId"))
.setExt("username", username).setExt("email", "1751341161@qq.com"));
//return "redirect:/";//20180802
return ToutiaoUtil.getJSONString(0, "成功");
} else {
model.addAttribute("error","登录失败,请重新登录!");//20180802
//return "redirect:/login";//20180802
return ToutiaoUtil.getJSONString(1, map);
}
} catch (Exception e) {
logger.error("注册异常" + e.getMessage());
model.addAttribute("error","登录异常");//20180802
//return "redirect:/login";//20180802
return ToutiaoUtil.getJSONString(1, "注册异常");
}
}
@RequestMapping(path = {"/logout/"}, method = {RequestMethod.GET, RequestMethod.POST})
public String logout(@CookieValue("ticket") String ticket) {
userService.logout(ticket);
logger.info("logout:跳转到首页");//20180802
return "redirect:/";
}
}
1) 返回给前端JSON
return ToutiaoUtil.getJSONString(0, "注册成功");
0,惯例表示成功
2)token
3)登陆登出
- 登陆
- 服务器密码校验/三方校验回调,token登记
1.1 服务器端token关联userid
1.2 客户端存储token(app存储本地,浏览器存储cookie) - 服务端/客户端token有效期设置(记住登陆) 注:token可以是sessionid,或者是cookie里的一个key
- 登出
服务端/客户端token删除 session清理
4)页面访问
- 客户端:
带token的HTTP请求 - 服务端:
- 根据token获取用户id
- 根据用户id获取用户的具体信息
- 用户和页面访问权限处理
- 渲染页面/跳转页面
4.5 MessageController
@Controller
public class MessageController {
private static final Logger logger = LoggerFactory.getLogger(MessageController.class);
@Autowired
MessageService messageService;
@Autowired
UserService userService;
@Autowired
HostHolder hostHolder;
@RequestMapping(path = {"/msg/list"}, method = {RequestMethod.GET})
// 当前用户的所有站内信,包括与所有用户的信息
public String conversationList(Model model) {
try {
int localUserId = hostHolder.getUser().getId();
List<ViewObject> conversations = new ArrayList<ViewObject>();
List<Message> conversationList = messageService.getConversationList(localUserId, 0, 10);
for (Message msg : conversationList) {
ViewObject vo = new ViewObject();
vo.set("conversation", msg);
//获取与当前用户对话的user信息
//如果是我方发送(msg.getFromId() == localUserId),则user.id为消息发送的toId
//如果不是我方发送(即我方为接收方),则user.id 为消息发送的fromId
int targetId = msg.getFromId() == localUserId ? msg.getToId() : msg.getFromId();
User user = userService.getUser(targetId);
vo.set("user", user);
vo.set("unread", messageService.getConvesationUnreadCount(localUserId, msg.getConversationId()));
conversations.add(vo);
}
model.addAttribute("conversations", conversations);
//return "letter";//20180802
} catch (Exception e) {
logger.error("获取站内信列表失败" + e.getMessage());
}
return "letter";
}
@RequestMapping(path = {"/msg/detail"}, method = {RequestMethod.GET})
public String conversationDetail(Model model, @Param("conversationId") String conversationId) {
try {
//当前用户与多个用户的所有的站内信
List<Message> conversationList = messageService.getConversationDetail(conversationId, 0, 10);
List<ViewObject> messages = new ArrayList<>();
for (Message msg : conversationList) {
ViewObject vo = new ViewObject();
vo.set("message", msg);
//获取当前用户收到信息方的user(即获取我方收到所有信息对应的用户)
User user = userService.getUser(msg.getFromId());
if (user == null) {
continue;
}
vo.set("headUrl", user.getHeadUrl());
vo.set("userId", user.getId());
messages.add(vo);
}
model.addAttribute("messages", messages);
} catch (Exception e) {
logger.error("获取详情消息失败" + e.getMessage());
}
return "letterDetail";
}
@RequestMapping(path = {"/msg/addMessage"}, method = {RequestMethod.POST})
@ResponseBody
//发送信息
public String addMessage(@RequestParam("fromId") int fromId,
@RequestParam("toId") int toId,
@RequestParam("content") String content) {
try {
Message msg = new Message();
msg.setContent(content);
msg.setFromId(fromId);
msg.setToId(toId);
msg.setCreatedDate(new Date());
message.setHasRead(0);// 0 代表未读 1 代表已读//20180802
msg.setConversationId(fromId < toId ? String.format("%d_%d", fromId, toId) : String.format("%d_%d", toId, fromId));//20180802
messageService.addMessage(msg);
return ToutiaoUtil.getJSONString(msg.getId());
} catch (Exception e) {
logger.error("增加评论失败" + e.getMessage());
return ToutiaoUtil.getJSONString(1, "插入评论失败");
}
}
}
1)conversationId
发送那一方的id + 收到信息的那一方 id = 会话conversationId
即a发送给b 和 b 发送给a 的消息在a,b之间的站内信中心都能看见
4.6 NewsController
使用云:
- CDN
- 云实时缩图
@Controller
public class NewsController {
private static final Logger logger = LoggerFactory.getLogger(NewsController.class);
@Autowired
NewsService newsService;
@Autowired
QiniuService qiniuService;
@Autowired
HostHolder hostHolder;
@Autowired
UserService userService;
@Autowired
CommentService commentService;
@Autowired
LikeService likeService;
@RequestMapping(path = {"/news/{newsId}"}, method = {RequestMethod.GET})
//查看资讯详情页
public String newsDetail(@PathVariable("newsId") int newsId, Model model) {
News news = newsService.getById(newsId);
if (news != null) {
int localUserId = hostHolder.getUser() != null ? hostHolder.getUser().getId() : 0;
if (localUserId != 0) {
model.addAttribute("like", likeService.getLikeStatus(localUserId, EntityType.ENTITY_NEWS, news.getId()));
} else {
model.addAttribute("like", 0);
}
// 评论
List<Comment> comments = commentService.getCommentsByEntity(news.getId(), EntityType.ENTITY_NEWS);
List<ViewObject> commentVOs = new ArrayList<ViewObject>();
for (Comment comment : comments) {
ViewObject vo = new ViewObject();
vo.set("comment", comment);
vo.set("user", userService.getUser(comment.getUserId()));
commentVOs.add(vo);
}
model.addAttribute("comments", commentVOs);
}
model.addAttribute("news", news);
model.addAttribute("owner", userService.getUser(news.getUserId()));
return "detail";
}
@RequestMapping(path = {"/addComment"}, method = {RequestMethod.POST})
public String addComment(@RequestParam("newsId") int newsId,
@RequestParam("content") String content) {
try {
content = HtmlUtils.htmlEscape(content);
// 过滤content
Comment comment = new Comment();
comment.setUserId(hostHolder.getUser().getId());
comment.setContent(content);
comment.setEntityId(newsId);
comment.setEntityType(EntityType.ENTITY_NEWS);
comment.setCreatedDate(new Date());
comment.setStatus(0);
commentService.addComment(comment);
// 更新news里的评论数量
int count = commentService.getCommentCount(comment.getEntityId(), comment.getEntityType());
newsService.updateCommentCount(comment.getEntityId(), count);
// 怎么异步化
} catch (Exception e) {
logger.error("增加评论失败" + e.getMessage());
}
return "redirect:/news/" + String.valueOf(newsId);
}
@RequestMapping(path = {"/image"}, method = {RequestMethod.GET})//展示图片
@ResponseBody
public void getImage(@RequestParam("name") String imageName,
HttpServletResponse response) {
try {
response.setContentType("image/jpeg");
StreamUtils.copy(new FileInputStream(new
File(ToutiaoUtil.IMAGE_DIR + imageName)), response.getOutputStream());
} catch (Exception e) {
logger.error("读取图片错误" + imageName + e.getMessage());
}
}
@RequestMapping(path = {"/uploadImage/"}, method = {RequestMethod.POST})
//服务器上床数据一般都用post,用get 的话图片字段不知道存去了哪里
@ResponseBody
public String uploadImage(@RequestParam("file") MultipartFile file) {
try {
String fileUrl = newsService.saveImage(file);//调用
//String fileUrl = qiniuService.saveImage(file);
if (fileUrl == null) {
return ToutiaoUtil.getJSONString(1, "上传图片失败");
}
return ToutiaoUtil.getJSONString(0, fileUrl);
} catch (Exception e) {
logger.error("上传图片失败" + e.getMessage());
return ToutiaoUtil.getJSONString(1, "上传失败");
}
}
@RequestMapping(path = {"/user/addNews/"}, method = {RequestMethod.POST})
@ResponseBody
//发布资讯
public String addNews(@RequestParam("image") String image,
@RequestParam("title") String title,
@RequestParam("link") String link) {
try {
News news = new News();
news.setCreatedDate(new Date());
news.setTitle(title);
news.setImage(image);
news.setLink(link);
if (hostHolder.getUser() != null) {//是登陆的用户
news.setUserId(hostHolder.getUser().getId());
} else { // 设置一个匿名用户
news.setUserId(3);
}
newsService.addNews(news);
return ToutiaoUtil.getJSONString(0);
} catch (Exception e) {
logger.error("添加资讯失败" + e.getMessage());
return ToutiaoUtil.getJSONString(1, "发布失败");
}
}
}
1)StreamUtils
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/StreamUtils.html
public static void copy(byte[] in,
java.io.OutputStream out)
throws java.io.IOException
public static void copy(java.lang.String in,
java.nio.charset.Charset charset,
java.io.OutputStream out)
throws java.io.IOException
public static int copy(java.io.InputStream in,
java.io.OutputStream out)
throws java.io.IOException
Copy the contents of the given InputStream to the given OutputStream. Leaves both streams open when done.
2) 切换本地和云
String fileUrl = newsService.saveImage(file);
String fileUrl = qiniuService.saveImage(file);
4.7. SettingController
@Controller
public class SettingController {
@RequestMapping("/setting")
@ResponseBody
public String setting() {
return "Setting:OK";
}
}
1)@RequestBody
- 1.不使用@RequestBody注解
相当于使用该注解,并required默认为true
①当前端没有传参时,会报错400
②当前端传一个空{},对象会根据构造函数自动生成。 - 2.只使用@RequestBody注解
效果同1 - 3.使用@RequestBody(required = false)
可以不传参,但句柄会为null
2)@ResponseBody
- 作用:
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。 - 使用时机:
返回的数据不是html标签的页面
,而是其他某种格式的数据时(如json、xml等)使用;