置顶、加精、删除

1.导包thymeleaf和springsecurity5的整合

     <dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity5</artifactId></dependency>

功能实现

  • 点击“置顶”、“加精”、“删除”,修改帖子的状态

    在DiscussPostMapper增加修改方法

      //置顶帖子 加精帖子的方法int updateType(int id, int type);int updateStatus(int id, int status);
    

    DiscussPostService、DiscussPostController相应增加方法,注意在Es中同步变化

        <update id="updateType">update discuss_post set type = #{type} where id = #{id}</update><update id="updateStatus">update discuss_post set status = #{status} where id = #{id}</update>------------------------//置顶public int updateType(int id, int type){return discussPostMapper.updateType(id, type);}public int updateStatus(int id, int status){return discussPostMapper.updateType(id, status);}--------------------------//置顶/**** @param id 帖子id* @return*/@RequestMapping(path = "/top",method = RequestMethod.POST)@ResponseBodypublic String setTop(int id){discussPostService.updateType(id,1);//将帖子数据同步到esEvent event = new Event().setTopic(TOPIC_PUBLISH).setEntityType(ENTITY_TYPE_POST).setEntityId(id).setUserId(hostHolder.getUser().getId());eventProducer.fireEvent(event);return CommunityUtil.getJSONString(0);}//加精@RequestMapping(path = "/wonderful",method = RequestMethod.POST)@ResponseBodypublic String setWonderful(int id){discussPostService.updateStatus(id,1);//将帖子数据同步到esEvent event = new Event().setTopic(TOPIC_PUBLISH).setEntityType(ENTITY_TYPE_POST).setEntityId(id).setUserId(hostHolder.getUser().getId());eventProducer.fireEvent(event);return CommunityUtil.getJSONString(0);}//删除@RequestMapping(path = "/delete",method = RequestMethod.POST)@ResponseBodypublic String setDelete(int id){discussPostService.updateStatus(id,2);//从es删除帖子Event event = new Event().setTopic(TOPIC_DELETE).setEntityType(ENTITY_TYPE_POST).setEntityId(id).setUserId(hostHolder.getUser().getId());eventProducer.fireEvent(event);return CommunityUtil.getJSONString(0);}
    
    • 要在EventConsumer增加消费删帖事件
        //消费者发帖的方法//监听主题为TOPIC_PUBLISH的事件@KafkaListener(topics = {TOPIC_PUBLISH})public void handlePublishMessage(ConsumerRecord record){//判断是否为空if (record == null || record.value() == null){logger.error("消息的内容为空");return;}//获取生产者的event,通过获得的json字符串转换为Event对象Event event = JSONObject.parseObject(record.value().toString(), Event.class);if (event == null){logger.error("消息格式错误");return;}//查询帖子信息DiscussPost discussPost = discussPostService.findDiscussPostById(event.getEntityId());//存入eselasticsearchService.saveDiscussPost(discussPost);}//删除帖子@KafkaListener(topics = {TOPIC_DELETE})public void handleDeleteMessage(ConsumerRecord record){//判断是否为空if (record == null || record.value() == null){logger.error("消息的内容为空");return;}//获取生产者的event,通过获得的json字符串转换为Event对象Event event = JSONObject.parseObject(record.value().toString(), Event.class);if (event == null){logger.error("消息格式错误");return;}//删除eselasticsearchService.deleteDiscussPost(event.getEntityId());}
    

    修改html和js文件

    discusspost-detail.html

    <!-- 添加 thymeleaf和spring-security整合的信息-->
    <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security"><!-- 标题 -->
    <div class="float-right"><input type="hidden" id="postId" th:value="${post.id}"><button type="button" class="btn btn-danger btn-sm" id="topBtn"th:disabled="${post.type==1}" sec:authorize="hasAnyAuthority('moderator')">置顶</button><button type="button" class="btn btn-danger btn-sm" id="wonderfulBtn"     th:disabled="${post.status==1}" sec:authorize="hasAnyAuthority('moderator')">加精 </button><button type="button" class="btn btn-danger btn-sm" id="deleteBtn"th:disabled="${post.status==2}" sec:authorize="hasAnyAuthority('admin')">删除</button>
    </div>
    

    discuss.js

    /*在加载静态页面后调用以下3个方法:置顶 加精 删除*/
    $(function () {$("#topBtn").click(setTop);$("#wonderfulBtn").click(setWonderful);$("#deleteBtn").click(setDelete);
    });//点赞
    function like(btn, entityType, entityId, entityUserId, postId) {$.post(CONTEXT_PATH + "/like",{"entityType":entityType,"entityId":entityId,"entityUserId":entityUserId,"postId":postId},function(data) {data = $.parseJSON(data);if(data.code == 0) {$(btn).children("i").text(data.likeCount);$(btn).children("b").text(data.likeStatus==1?'已赞':"赞");} else {alert(data.msg);}});
    }
    //置顶
    function setTop() {$.post(CONTEXT_PATH + "/discuss/top",  {"id":$("#postId").val()},function (data) {data = $.parseJSON(data);if (data.code==0){$("#topBtn").attr("disabled","disabled");}else {alert(data.msg);}});
    }//加精
    function setWonderful() {$.post(CONTEXT_PATH + "/discuss/wonderful",{"id":$("#postId").val()},function (data) {data = $.parseJSON(data);if (data.code==0){$("#wonderfulBtn").attr("disabled","disabled");}else {alert(data.msg);}});
    }//删除
    function setDelete() {$.post(CONTEXT_PATH + "/discuss/delete",{"id":$("#postId").val()},function (data) {data = $.parseJSON(data);if (data.code==0){location.href = CONTEXT_PATH + "/index";}else {alert(data.msg);}});
    }
    

权限管理

  • 版主可以执行“置顶”、“加精”操作。管理员可以执行“删除”操作。

    • 在SecurityConfig类下配置,置顶、加精、删除的访问权限。

按钮显示

  • 版主可以看到“置顶”、“加精”按钮。管理员可以看到“删除“按钮。

    • 导包:thymeleaf-extras-springsecurity5,thymeleaf对security的支持。
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;//Security的配置类
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {//忽略静态资源,不对静态资源进行拦截@Overridepublic void configure(WebSecurity web) throws Exception {web.ignoring().antMatchers("/resources/**");}//授权@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests()// 对于以下列出的所有路径.antMatchers("/user/setting",// 用户设置"/user/upload",// 用户文件上传"/discuss/add",// 帖子发布"/comment/add/**",// 评论发布"/letter/**",// 私信相关内容"/notice/**",// 通知相关内容"/like",// 点赞"/follow",// 加关注"/unfollow"// 取消关注)// 只要有以下相关权限,都可以访问.hasAnyAuthority(AUTHORITY_USER,// 权限: 普通用户AUTHORITY_ADMIN,// 权限: 管理员AUTHORITY_MODERATOR// 权限: 版主)// 对于以下列出的所有路径.antMatchers("/discuss/top","/discuss/wonderful")// 只有具有以下列出的权限才可以访问.hasAnyAuthority(AUTHORITY_MODERATOR// 权限: 版主)// 对于以下列出的所有路径.antMatchers("/discuss/delete","/data/**")// 只有具有以下列出的权限才可以访问.hasAnyAuthority(AUTHORITY_ADMIN)// 除了以上列出的权限限制约定外,其他请求路径都放行.anyRequest().permitAll()//.and().csrf().disable();//权限不够时// 如果权限不够时的处理http.exceptionHandling()// 没有登录时的处理.authenticationEntryPoint(new AuthenticationEntryPoint() {// 没有登录时的处理方法@Overridepublic void commence(HttpServletRequest request,HttpServletResponse response,AuthenticationException e)throws IOException, ServletException {// 如果请求x-requested-with 中头包含XMLHttpRequest 说明是异步请求String xRequestedWith = request.getHeader("x-requested-with");if ("XMLHttpRequest".equals(xRequestedWith)) {// 设置响应体是json 格式(因为是异步请求,所以返回内容要是json格式)response.setContentType("application/plain;charset=utf-8");// 拿到输出流,输出返回内容给前端页面PrintWriter writer = response.getWriter();writer.write(CommunityUtil.getJSONString(403, "你还没有登录哦!"));} else {// 不是异步请求// 重定向到登录页面response.sendRedirect(request.getContextPath() + "/login");}}})// 拒绝访问(权限不足时的处理).accessDeniedHandler(new AccessDeniedHandler() {// 权限不足@Overridepublic void handle(HttpServletRequest request,HttpServletResponse response,AccessDeniedException e)throws IOException, ServletException {String xRequestedWith = request.getHeader("x-requested-with");if ("XMLHttpRequest".equals(xRequestedWith)) {// 设置响应体是json 格式(因为是异步请求,所以返回内容要是json格式)response.setContentType("application/plain;charset=utf-8");// 拿到输出流,输出返回内容给前端页面PrintWriter writer = response.getWriter();writer.write(CommunityUtil.getJSONString(403, "你没有访问此功能的权限!"));} else {// 不是异步请求// 重定向到没有权限页面response.sendRedirect(request.getContextPath() + "/denied");}}});// Security底层默认会拦截/logout请求,进行退出处理.// 覆盖它默认的逻辑,才能执行我们自己的退出代码.http.logout().logoutUrl("/securitylogout");}
}

项目-22-置顶、加精、删除相关推荐

  1. [置顶]       加载事件js代码

    1 /*加载事件代码*/ 2 function addLoadEvent(func) { 3 var oldonload = window. 4 if (typeof window.onload != ...

  2. 项目1在线交流平台-7.构建安全高效的企业服务-3. Security整合Kafka,ES,Thymeleaf实例-对帖子置顶、加精、删除

    文章目录 功能需求 一.置顶.加精.删除帖子功能的实现 1. dao层处理数据 接口定义 sal语句定义 2. service层业务处理 3. Controller层处理按钮事件异步请求 异步请求及k ...

  3. Android项目:仿微信聊天的删除,置顶。

    首先我们要重写上下文菜单方法onCreateContextMenu,从这个方法可以添加需要的条目按钮,我们要在res/menu目录下建议个weixin.xml文件: <?xml version= ...

  4. android环信删除会话列表,关于会话列表的置顶聊天

    最近搞完了置顶聊天,来写篇文章分享下经验. 其实刚刚开始 ,我自己在想,我是不是要去做出类似于QQ那种的滑动,然后显示置顶和删除. 图1 我就开始写,写完了之后然后去置顶,取消置顶,其实是有用的,但是 ...

  5. 仿QQ对话列表滑动删除与置顶的原理及实现

    接下来,我们将完成QQ聊天界面的ListView滑动效果,大家可能都用过ListView,知道ListView是上下滑动的,并不会产生左右滑动的效果,如果想让ListView变成左右滑动的效果,必须对 ...

  6. Android的SwipeToDismiss第三方开源框架模拟QQ对话列表侧滑删除,置顶,将头像图片圆形化处理。...

      <Android SwipeToDismiss:左右滑动删除ListView条目Item> Android的SwipeToDismiss是github上一个第三方开源框架(github ...

  7. Android仿ios微信左划条目删除、置顶的实现,代码简洁,更容易理解使用

    <span style="font-family:Arial, Helvetica, sans-serif;"><span style="backgro ...

  8. 如何在项目中实现类似于微信的置顶与取消置顶的功能?

    - 借鉴微信的置顶与取消置顶的实现思路: 会看到这个微信的聊天记录的排序规则是以时间降序来进行排序的,如果要实现置顶与取消置顶? 一下子是想不到的,需要思路 由此可以确信的是,我们平时使用微信时,最新 ...

  9. 转:[置顶] 从头到尾彻底理解KMP(2014年8月22日版)

    [置顶] 从头到尾彻底理解KMP(2014年8月22日版) 转载于:https://www.cnblogs.com/kira2will/p/4111564.html

最新文章

  1. [case19]聊聊eureka的TaskDispatcher
  2. c# 再次尝试 连接失败_修复破裂婚姻,如何重新建立情感连接
  3. python统计词频_Python统计四六级考试的词频
  4. HDU1048 The Hardest Problem Ever
  5. net.sz.framework 框架 ORM 消消乐超过亿条数据排行榜分析 天王盖地虎
  6. select下拉选择框
  7. Windows 新建文本文档快捷键设置
  8. vue2.x+antd-vue搭建后管项目
  9. 2014校园招聘_腾讯2014校园招聘
  10. 电路课组(一)电路原理 Review 1 线性电路分析基础
  11. 安卓android+rom定制,移植,安卓Android ROM定制移植教程.doc
  12. PIL库 : 居中对齐写入文本(英文 / 中文)
  13. Mac上挂载移动硬盘出现Read-only file system问题
  14. 计算机组成原理-错题本
  15. VS2019 无法登录 许可证已过期 无法下载许可证
  16. HTML5 布局标签
  17. html首页问候语,每日一条问候语
  18. 应届生昆山offer和上海户口offer要如何选择?
  19. java计算机毕业设计高校实习实训管理系统(附源码、数据库)
  20. JSS-22 DC220V【时间继电器】

热门文章

  1. 查看mysql数据库的用户名
  2. 页面滑动长弹窗,如何阻止页面滚动?
  3. 将uniAPP项目导入到微信开发者工具中保姆级教程
  4. Python—飞机大作战游戏(附源代码及素材)
  5. 放开那个水果!让我来!使用飞桨高层API轻松实现智能果蔬分类系统
  6. 如何查看百度百家号审核进度
  7. 全方面了解接口自动化,看完还不会你锤我
  8. java字符串与变量拼接_Java 字符串比较、拼接问题
  9. 新世代潮流酒店Cook’s Club品牌在中国正式发布
  10. 学人工智能有什么好处?学AI的优势