亲宝软件园·资讯

展开

SpringBoot AJAX

LeBron Le 人气:0

1. AJAX

2. 功能描述

用户点击【发布帖子】按钮后,页面出现一个弹窗,此时后面的页面并没有刷新。

点击【发布帖子】按钮后,publishBtn 按钮会执行 index.js 中的 publish() 方法,跳转到:CONTEXT_PATH + “/discuss/add”;会执行控制器类 DiscussPostControlleraddDiscussPost()方法。里面调用Service: discussPostService,该service又调用了 discussPostMapper,通过其对应的 SQL 语句将帖子内容插进 discuss_post 表中。

3. 开发流程

4. 引入AJAX依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.58</version>
</dependency>

5. Util

util/CommunityUtil.java

在用户登录之前,不显示【发布帖子】按钮;

在用户登录之后,才显示【发布帖子】按钮,可以进行相关操作。

//得到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();
}
//得到JSON格式的字符串(重载1:无业务数据)
public static String getJSONString(int code, String msg){
    return getJSONString(code, msg, null);
}
//得到JSON格式的字符串(重载2:无提示、业务数据)
public static String getJSONString(int code){
    return getJSONString(code, null, null);
}

6. Mapper

dao/DiscussPostMapper.java

添加了 insertDiscussPost() 方法,功能为插入帖子

package com.nowcoder.community.dao;
import com.nowcoder.community.entity.DiscussPost;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface DiscussPostMapper {
    List<DiscussPost> selectDiscussPosts(int userId, int offset, int limit);
    // @Param注解用于给参数取别名
    // 如果只有一个参数,并且在<if>里使用,则必须加别名
    int selectDiscussPostRows(@Param("userId") int userId);
    int insertDiscussPost(DiscussPost discussPost);
}

mapper/discusspost-mapper.xml

编写对应的 SQL 语句

<insert id="insertDiscussPost" parameterType="DiscussPost">
	insert into discuss_post(<include refid="insertFields"></include>)
	values (#{userId},#{title},#{content},#{type},#{status},#{createTime},#{commentCount},#{score})
</insert>

7. Service

service/DiscussPostService.java

编写 addDiscussPost(),同时注入过滤器

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);
    }
}

8. Controller

package com.nowcoder.mycommunity.controller;
import com.nowcoder.mycommunity.entity.DiscussPost;
import com.nowcoder.mycommunity.entity.User;
import com.nowcoder.mycommunity.service.DiscussPostService;
import com.nowcoder.mycommunity.util.CommunityUtil;
import com.nowcoder.mycommunity.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("/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){
            // 403表示没有权限
            return CommunityUtil.getJSONString(403, "你还没有登录哦!");
        }
        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setTitle(title);
        post.setContent(content);
        post.setCreateTime(new Date());
        discussPostService.addDiscussPost(post);
        return CommunityUtil.getJSONString(0, "发布成功");
    }
}

9. JavaScript

index.js

在 js 文件中编写【发布按钮】对应的函数 publish()

$(function(){
	$("#publishBtn").click(publish);
});
function publish() {
	$("#publishModal").modal("hide");
	// 获取标题和内容
	var title = $("#recipient-name").val();
	var content = $("#message-text").val();
	// 发送异步请求(POST)
	$.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);
	    }
	);
}

加载全部内容

相关教程
猜你喜欢
用户评论