发布资讯
一 需求描述
1 点击分享,可以分部咨询news。一条news包括图片,资讯标题,资讯链接;
2. 资讯发布完会跳到首页home.html:
3 点击具体资讯可以查看资讯详情页detail.html,并进行评论 :
二 具体代码实现:
1 DB设计:
DROP TABLE IF EXISTS `news`; CREATE TABLE `news` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(128) NOT NULL DEFAULT '', `link` varchar(256) NOT NULL DEFAULT '', `image` varchar(256) NOT NULL DEFAULT '', `like_count` int NOT NULL, `comment_count` int NOT NULL, `created_date` datetime NOT NULL, `user_id` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2 Model: News.java
package com.nowcoder.model; import java.util.Date; /** * Created by rainday on 16/6/30. */ public class News { private int id; private String title; private String link; private String image; private int likeCount; private int commentCount; private Date createdDate; private int userId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public int getLikeCount() { return likeCount; } public void setLikeCount(int likeCount) { this.likeCount = likeCount; } public int getCommentCount() { return commentCount; } public void setCommentCount(int commentCount) { this.commentCount = commentCount; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } }
3 Dao:
int addNews(News news); 发布资讯
News selectById(int id); 点击详情页时根据newsId查询资讯
int updateCommentCount(@Param("id") int id, @Param("commentCount") int commentCount); 资讯详情页时改评论数量
List<News> selectByUserIdAndOffset(@Param("userId") int userId,
@Param("offset") int offset,
@Param("limit") int limit); 点击具体用户头像可查询该用户发布的所有资讯。
package com.nowcoder.dao; import com.nowcoder.model.News; import org.apache.ibatis.annotations.*; import java.util.List; /** * Created by Administrator on 2017/4/6. */ @Mapper public interface NewsDao { String TABLE_NAME = "news"; String INSERT_FIELDS = "title, link, image, like_count, comment_count," + "created_date, user_id"; String SELECT_FIELDS = "id," + INSERT_FIELDS; @Insert({"insert into ", TABLE_NAME, "(", INSERT_FIELDS ,") " + " values(#{title}," + " #{link}, " + "#{image}, " + "#{likeCount}," + "#{commentCount}," + "#{createdDate}," + "#{userId})"}) int addNews(News news); @Select({"select", SELECT_FIELDS, "from", TABLE_NAME, " where id = #{id}"}) News selectById(int id); @Update({"update", TABLE_NAME, "set comment_count=#{commentCount} where id=#{id}"}) int updateCommentCount(@Param("id") int id, @Param("commentCount") int commentCount); List<News> selectByUserIdAndOffset(@Param("userId") int userId, @Param("offset") int offset, @Param("limit") int limit); }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.nowcoder.dao.NewsDao"> <sql id="table">news</sql> <sql id="selectFields"> id,title,link,image,like_count,comment_count,created_date,user_id </sql> <select id="selectByUserIdAndOffset" resultType="com.nowcoder.model.News"> SELECT <include refid="selectFields"/> FROM <include refid="table"/> <if test="userId != 0"> WHERE user_id = #{userId} </if> ORDER BY id DESC LIMIT #{offset}, #{limit} </select> </mapper>
4 Service:
package com.nowcoder.service; import com.nowcoder.dao.NewsDao; import com.nowcoder.dao.UserDao; import com.nowcoder.model.News; import com.nowcoder.model.User; import com.nowcoder.util.ToutiaoUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.List; import java.util.UUID; /** * Created by Administrator on 2017/4/8. */ @Service public class NewsService { @Autowired NewsDao newsDao; public List<News> getLatestNews(int userId, int offset, int limit){ return newsDao.selectByUserIdAndOffset(userId, offset, limit); } public News getById(int newsId){ return newsDao.selectById(newsId); } public int addNews(News news){ newsDao.addNews(news); return news.getId(); } public int updateCommentCount(int newsId, int commentCount){ return newsDao.updateCommentCount(newsId, commentCount); } }
5 Controller :
(1)发布资讯:
/** * 点击分享,分享头条 * @param image 分享内容的图片 * @param title 分享内容标题 * @param link 分享内容链接 * @return */ @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(); if(hostHolder.getUser() != null){ news.setUserId(hostHolder.getUser().getId()); }else { //设置一个匿名用户 news.setUserId(3); } news.setCreatedDate(new Date()); news.setLink(link); news.setImage(image); news.setTitle(title); newsService.addNews(news); return ToutiaoUtil.getJSONString(0); }catch (Exception ex){ logger.error("资讯发布失败:" + ex.getMessage()); return ToutiaoUtil.getJSONString(1, "资讯发布失败"); } }
(2)查看资讯详情页:
/** * 查看资讯详情页 * @param newsId * @param model * @return */ @RequestMapping(path = {"/news/{newsId}"}, method = {RequestMethod.GET}) public String newsDetail(@PathVariable("newsId") int newsId, Model model){ News news = newsService.getById(newsId); //显示评论内容 if(news != null){ List<Comment> commentList = commentService.getCommentsByEntity(news.getId(), EntityType.ENTITY_NEWS); List<ViewObject> commentVOs = new ArrayList<>(); for(Comment comment : commentList){ 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"; }
detail.html:
#parse("header.html") <div id="main"> <div class="container"> <div class="post detail"> <div class="votebar"> #if($like>0) <button class="click-like up pressed" data-id="$!{news.id}" title="赞同"><i class="vote-arrow"></i><span class="count">$!{news.likeCount}</span></button> #else <button class="click-like up" data-id="$!{news.id}" title="赞同"><i class="vote-arrow"></i><span class="count">$!{news.likeCount}</span></button> #end #if($like<0) <button class="click-dislike down pressed" data-id="$!{news.id}" title="反对"><i class="vote-arrow"></i></button> #else <button class="click-dislike down" data-id="$!{news.id}" title="反对"><i class="vote-arrow"></i></button> #end </div> <div class="content"> <div class="content-img"> <img src="$!{news.image}?imageView2/2/w/100" alt=""> </div> <div class="content-main"> <h3 class="title"> <a target="_blank" rel="external nofollow" href="$!{news.link}">$!{news.title}</a> </h3> <div class="meta"> $!{news.link} <span> <i class="fa icon-comment"></i> $!{news.commentCount} </span> </div> </div> </div> <div class="user-info"> <div class="user-avatar"> <a href="/user/$!{owner.id}"><img width="32" class="img-circle" src="$!{owner.headUrl}"></a> </div> </div> <div class="subject-name">来自 <a href="/user/$!{owner.id}">$!{owner.name}</a></div> </div> <div class="post-comment-form"> #if($user) <span>评论 ($!{news.commentCount})</span> <form method="post" action="/addComment"> <input name="newsId" type="hidden" value="$!{news.id}"> <div class="form-group text required comment_content"> <label class="text required sr-only"> <abbr title="required">*</abbr> 评论</label> <textarea rows="5" class="text required comment-content form-control" name="content" id="content"></textarea> </div> <div class="text-right"> <input type="submit" name="commit" value="提 交" class="btn btn-default btn-info"> </div> </form> #else <div class="login-actions"> <a class="btn btn-success" href="/?pop=1">登录后评论</a> </div> #end </div> <div id="comments" class="comments"> #foreach($commentvo in $comments) <div class="media"> <a class="media-left" href="/user/$!{commentvo.user.id}"> <img src="$!{commentvo.user.headUrl}"> </a> <div class="media-body"> <h4 class="media-heading"> <small class="date">$date.format('yyyy-MM-dd HH:mm:ss', $!{commentvo.comment.createdDate}) </small> </h4> <div>$!{commentvo.comment.content}</div> </div> </div> #end </div> </div> <script type="text/javascript"> $(function(){ // If really is weixin $(document).on('WeixinJSBridgeReady', function() { $('.weixin-qrcode-dropdown').show(); var options = { "img_url": "", "link": "http://nowcoder.com/j/wt2rwy", "desc": "", "title": "读《Web 全栈工程师的自我修养》" }; WeixinJSBridge.on('menu:share:appmessage', function (argv){ WeixinJSBridge.invoke('sendAppMessage', options, function (res) { // _report('send_msg', res.err_msg) }); }); WeixinJSBridge.on('menu:share:timeline', function (argv) { WeixinJSBridge.invoke('shareTimeline', options, function (res) { // _report('send_msg', res.err_msg) }); }); // $(window).on('touchmove scroll', function() { // if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) { // $('div.backdrop').show(); // $('div.share-help').show(); // } else { // $('div.backdrop').hide(); // $('div.share-help').hide(); // } // }); }); }) </script> <script type="text/javascript" src="/scripts/main/site/detail.js"></script> </div> #parse("footer.html")