• 【Java Web】使用ajax在论坛中发布帖子


    • AJAX
      • 异步的JavaScript与XML,不是一门新技术,只是一个新术语;
      • 使用AJAX,网页能增量更新在页面上,不需要刷新整个页面;
      • JSON的使用比XML使用更加普遍;
    • 示例
      • 使用jQuery发送AJAX请求;
    • 实践
      • 采用AJAX请求,实现发布帖子功能。

    1. DiscussPost类

    package com.nowcoder.community.entity;
    
    import java.util.Date;
    
    public class DiscussPost {
    
        private int id;
        private int userId;
        private String title;
        private String content;
        private int type;
        private int status;
        private Date createTime;
        private int commentCount;
        private double score;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public int getUserId() {
            return userId;
        }
    
        public void setUserId(int userId) {
            this.userId = userId;
        }
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public String getContent() {
            return content;
        }
    
        public void setContent(String content) {
            this.content = content;
        }
    
        public int getType() {
            return type;
        }
    
        public void setType(int type) {
            this.type = type;
        }
    
        public int getStatus() {
            return status;
        }
    
        public void setStatus(int status) {
            this.status = status;
        }
    
        public Date getCreateTime() {
            return createTime;
        }
    
        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }
    
        public int getCommentCount() {
            return commentCount;
        }
    
        public void setCommentCount(int commentCount) {
            this.commentCount = commentCount;
        }
    
        public double getScore() {
            return score;
        }
    
        public void setScore(double score) {
            this.score = score;
        }
    
        @Override
        public String toString() {
            return "DiscussPost{" +
                    "id=" + id +
                    ", userId=" + userId +
                    ", title='" + title + '\'' +
                    ", content='" + content + '\'' +
                    ", type=" + type +
                    ", status=" + status +
                    ", createTime=" + createTime +
                    ", commentCount=" + commentCount +
                    ", score=" + score +
                    '}';
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104

    2. mapper

    <?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.community.dao.DiscussPostMapper">
    
        <sql id="selectFields">
            id, user_id, title, content, type, status, create_time, comment_count, score
        </sql>
    
        <sql id="insertFields">
            user_id, title, content, type, status, create_time, comment_count, score
        </sql>
    
        <select id="selectDiscussPosts" resultType="DiscussPost">
            select <include refid="selectFields"></include>
            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">
            insert into discuss_post (<include refid="insertFields"></include>)
            values (#{userId},#{title},#{content},#{type},#{status},#{createTime},#{commentCount},#{score})
        </insert>
    
    
    </mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    3. Service

    package com.nowcoder.community.service;
    
    import com.nowcoder.community.dao.DiscussPostMapper;
    import com.nowcoder.community.entity.DiscussPost;
    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 DiscussPostService {
    
        @Autowired
        private DiscussPostMapper discussPostMapper;
    
        @Autowired
        private SensitiveFilter sensitiveFilter;
    
        public List<DiscussPost> findDiscussPosts(int userId, int offset, int limit) {
            return discussPostMapper.selectDiscussPosts(userId, offset, limit);
        }
    
        public int findDiscussPostRows(int userId) {
            return discussPostMapper.selectDiscussPostRows(userId);
        }
    
        public int addDiscussPost(DiscussPost post){
            if(post == null){
                throw new IllegalArgumentException("参数不能为空");
            }
    
            // 转义HTML标记
            post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));
            post.setContent(HtmlUtils.htmlEscape(post.getContent()));
            // 过滤敏感词
            post.setTitle(sensitiveFilter.filter(post.getTitle()));
            post.setContent(sensitiveFilter.filter(post.getContent()));
    
            return discussPostMapper.insertDiscussPost(post);
        };
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    4. Controller

    package com.nowcoder.community.controller;
    
    import com.nowcoder.community.entity.DiscussPost;
    import com.nowcoder.community.entity.User;
    import com.nowcoder.community.service.DiscussPostService;
    import com.nowcoder.community.util.CommunityUtil;
    import com.nowcoder.community.util.HostHolder;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.Date;
    
    @Controller
    @RequestMapping(path = "/discuss")
    public class DiscussPostController {
    
        @Autowired
        private DiscussPostService discussPostService;
    
        @Autowired
        private HostHolder hostHolder;
    
        @RequestMapping(path="/add", method = RequestMethod.POST)
        @ResponseBody
        public String addDiscussPost(String title, String content){
            User user = hostHolder.getUser();
            if(user == null){  // 未登录
                return CommunityUtil.getJSONString(403,"当前用户未登录!");
            }
            DiscussPost post = new DiscussPost();
            post.setUserId(user.getId());
            System.out.println(user.getId());
            post.setTitle(title);
            post.setContent(content);
            post.setCreateTime(new Date());
            discussPostService.addDiscussPost(post);
    
            // 报错的情况将来统一处理
            return CommunityUtil.getJSONString(0,"发布成功!");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    5. 前端jquery

    $(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);
    			// 显示提示框,2秒后自动关闭
    			$("#hintModal").modal("show");
    			setTimeout(function(){
    				$("#hintModal").modal("hide");
    				// 刷新页面
    				if(data.code == 0){
    					window.location.reload();
    				}
    			}, 2000);
    		}
    	)
    
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
  • 相关阅读:
    node的文件系统和数据流
    一个基于Java线程池管理的开源框架Hippo4j实践
    数据库(18)——DCL权限控制
    ELK学习笔记1:简介及安装
    【.Net实用方法总结】 整理并总结System.IO中Stream类及其方法介绍
    MySQL数据库——MySQL GRANT:用户授权
    RK开发板的USB连接(Ubuntu)
    Leetcode Daily Challenge 1845. Seat Reservation Manager
    一个简单的基于Qt的MVC框架
    操作系统绪论习题
  • 原文地址:https://blog.csdn.net/qq_42251120/article/details/132605488