2、发布帖子前端页面
通过点击我要发布按钮进入发帖界面,填写标题和内容,点击“发布”,触发ajax异步发送帖子请求,先将帖子框隐藏,然后获取标题和内容,$.post{url,json,function(data){data = $.parseJSON(data);}},post方式提交接json格式数据给目标URL,controller层接收到请求后,处理/add请求,前端根据返回的状态码以及提示信息判断是否添加成功。
3、发布帖子/add处理
若没有登录,返回403状态,wei't并提示未登录。封装discussPost对象,传给service层,处理帖子内容,敏感词过滤后,调用dao层添加帖子的方法,将帖子添加到数据库中。
同时controller层触发事件event,设置主体,ID等信息,生产者发送到kafka队列中。
新发的帖子,要将分数缓存到Redis中,以便后续进行热帖排名。
---------------------------------------------------------------------------------------------------------------------------------
1.DiscussPostMapper:
import com.nowcoder.community.entity.DiscussPost;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface DiscussPostMapper {
List selectDiscussPosts(int userId,int offset,int limit);
//@Param注解用于给参数取别名
//如果只有一个参数,并且在里使用,则必须加别名
int selectDiscussPostRows(@Param("userId") int userId);
int insertDiscussPost(DiscussPost discussPost);
DiscussPost selectDiscussPostById(int id);
int updateCommentCount(int id,int commentCount);
}
2.编写DiscussPostMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.nowcoder.community.mapper.DiscussPostMapper">
<select id="selectDiscussPosts" resultType="DiscussPost">
select * from discuss_post
where status!=2
<if test="userId!=0">
and user_id=#{userId}
</if>
order by type desc,create_time desc
limit #{offset},#{limit};
</select>
<select id="selectDiscussPostRows" resultType="int">
select count(id) from discuss_post
where status!=2
<if test="userId!=0">
and user_id=#{userId}
</if>
</select>
<insert id="insertDiscussPost" parameterType="DiscussPost" keyProperty="id">
insert into discuss_post(user_id, title, content, type, status, create_time, comment_count, score) VALUES (#{userId},#{title},#{content},#{type},#{status},#{createTime},#{commentCount},#{score});
</insert>
<select id="selectDiscussPostById" resultType="DiscussPost">
select * from discuss_post where id=#{id};
</select>
<update id="updateCommentCount">
update discuss_post set comment_count=#{commentCount} where id=#{id};
</update>
</mapper>
3.DiscussPostService:
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.mapper.DiscussPostMapper;
import com.nowcoder.community.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;
import java.util.List;
@Service
public class DiscussPostServiceImpl implements DiscussPostService{
@Autowired
private DiscussPostMapper discussPostMapper;
@Autowired
private SensitiveFilter sensitiveFilter;
@Override
public List selectDiscussPosts(int userId, int offset, int limit) {
return discussPostMapper.selectDiscussPosts(userId, offset, limit);
}
@Override
public int selectDiscussPostRows(int userId) {
return discussPostMapper.selectDiscussPostRows(userId);
}
@Override
public int insertDiscussPost(DiscussPost discussPost) {
return discussPostMapper.insertDiscussPost(discussPost);
}
@Override
public DiscussPost selectDiscussPostById(int id) {
return discussPostMapper.selectDiscussPostById(id);
}
@Override
public int updateCommentCount(int id, int commentCount) {
return discussPostMapper.updateCommentCount(id, commentCount);
}
public int addDiscussPost(DiscussPost discussPost){
if (discussPost==null){
throw new IllegalArgumentException("参数不能为空!");
}
//转移HTML标记
discussPost.setTitle(HtmlUtils.htmlEscape(discussPost.getTitle()));
discussPost.setContent(HtmlUtils.htmlEscape(discussPost.getContent()));
//过滤敏感词
discussPost.setTitle(sensitiveFilter.filter(discussPost.getTitle()));
discussPost.setContent(sensitiveFilter.filter(discussPost.getContent()));
return discussPostMapper.insertDiscussPost(discussPost);
}
}
4.DiscussPostController:
@PostMapping("/add")
@ResponseBody
public String addDiscussPost(String title,String content){
User user = hostHolder.getUser();
if (user==null){
return CommunityUtil.getJSONString(403,"你还没有登陆");
}
DiscussPost discussPost = new DiscussPost();
discussPost.setUserId(user.getId());
discussPost.setTitle(title);
discussPost.setContent(content);
discussPost.setCreateTime(new Date());
discussPostService.addDiscussPost(discussPost);
return CommunityUtil.getJSONString(0,"发布成功");
}
5.index.html:
<button type="button" class="btn btn-primary btn-sm position-absolute rt-0" data-toggle="modal" data-target="#publishModal" th:if="${loginUser!=null}">我要发布</button>
6.index.js:
$(function(){
$("#publishBtn").click(publish);
});
function publish() {
$("#publishModal").modal("hide");
//获取标题内容
var title=$("#recipient-name").val();
var content=$("#message-text").val();
//发送异步请求
$.post(
CONTEXT_PATH+"/discuss/add",
{"title":title,"content":content},
function (data) {
data=$.parseJSON(data);
//在提示框中显示返回消息
$("#hintBody").text(data.msg);
//显示提示框
$("#hintModal").modal("show");
//2秒后,自动隐藏提示框
setTimeout(function(){
$("#hintModal").modal("hide");
//刷新页面
if (data.code==0){
window.location.reload();
}
}, 2000);
}
);
}
7.编写一个工具类CommunityUtil,用于转换为json字符串:
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;
import java.util.Map;
import java.util.UUID;
public class CommunityUtil {
//生成随机字符串
public static String generateUUID()
{
return UUID.randomUUID().toString().replaceAll("-","");
}
//MD5加密
public static String md5(String key){
if (StringUtils.isBlank(key)){
return null;
}
return DigestUtils.md5DigestAsHex(key.getBytes());
}
//转换为json字符串
public static String getJSONString(int code, String msg, Map<String,Object> map){
JSONObject json = new JSONObject();
json.put("code",code);
json.put("msg",msg);
if (map!=null){
for (String key : map.keySet()) {
json.put(key,map.get(key));
}
}
return json.toJSONString();
}
public static String getJSONString(int code, String msg){
return getJSONString(code, msg,null);
}
public static String getJSONString(int code){
return getJSONString(code, null,null);
}
}