15-发布帖子

  • AJAX(异步请求,当前网页不刷新时访问服务器)
    • Asynchronous JavaScript and XML
    • 异步的JavaScript与XML,不是一门新技术,只是一个新的术语。
    • 使用AJAX,网页能够将增量更新呈现在页面上,而不需要刷新整个页面。
    • 虽然X代表XML,但目前JSON的使用比XML更加普遍。(XML不好解析)
    • https://developer.mozilla.org/zh-CN/docs/Web/Guide/AJAX。
  • 示例
    • 使用jQuery(js框架,更方便)发送AJAX请求。
  • 实践
    • 采用AJAX请求,实现发布帖子的功能。
  1. 引入新的FastJson依赖包
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>2.0.14</version>
</dependency>

  1. 开发工具方法处理json数据
  • 返回编码
  • 返回提示信息
  • 返回业务数据
    CommunityUtils里面
public static String getJSONString(int code, String msg, Map<String, Object> map) {
        //fastjson API
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("msg", msg);
        if (map != null) {//遍历map.存入json对象
            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);
    }

    //进行测试
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "zhangsan");
        map.put("age", 25);
        System.out.println(getJSONString(0, "ok", map));
    }
  1. json发布异步请求的示例
//ajax示例
    @RequestMapping(path = "/ajax",method = RequestMethod.POST)
    @ResponseBody//异步请求,返回字符串
    public String testAjax(String name,int age){//浏览器提交的数据name,age
        System.out.println(name);
        System.out.println(age);
        return CommunityUtil.getJSONString(0,"操作成功");
    }

ajax页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>
</head>
<body>
    <p>
        <input type="button" value="发送" onclick="send();">
    </p>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
    <script>
        function send(){
            $.post(
                "/community/alpha/ajax",
                {"name":"张三","age":23},
                function (data){
                    console.log(typeof (data));
                    console.log(data);
                    data=$.parseJSON(data);
                    console.log(typeof (data));
                    console.log(data.code);
                    console.log(data.msg);
                }<!--匿名函数,调用页面,浏览器获得响应后会访问此方法,将服务器返回的数据传给data,回调函数-->
            );
        }
    </script>
</body>
</html>

在这里插入图片描述

页面无刷新,但访问了服务器

正式编写发布帖子的功能
  1. DiscussPostMapper.java中追加方法
int insertDiscussPost(DiscussPost discussPost);//发布帖子
  1. discusspost-mapper.xml中追加方法
<sql id="insertFields">
        user_id, title, content, type, status, create_time, comment_count, score
    </sql>
<insert id="insertDiscussPost" parameterType="DiscussPost">
        insert into discuss_post(<include refid="insertFields"></include>)
        values(#{userId},#{title},#{content},#{type},#{status},#{createTime},#{commentCount},#{score})
    </insert>

3.在服务层写代码
DiscussPostService.java

@Autowired
    private SensitiveFilter sensitiveFilter;
	public int addDiscussPost(DiscussPost post) {
        if (post == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        // 转义HTML标记,将标签”<>“等处理
        post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));//springMVC提供的工具
        post.setContent(HtmlUtils.htmlEscape(post.getContent()));
        // 过滤敏感词
        post.setTitle(sensitiveFilter.filter(post.getTitle()));//只有title,contents需要过滤关键词
        post.setContent(sensitiveFilter.filter(post.getContent()));

        return discussPostMapper.insertDiscussPost(post);
    }

  1. 视图层(controller、html)
    DiscussPostController.java
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("/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) {//String title, String content页面闯入的值
        User user = hostHolder.getUser();
        if (user == null) {
            return CommunityUtil.getJSONString(403, "你还没有登录哦!");//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, "发布成功!");//给浏览器一个信息发布成功
    }

}

  1. 处理页面index.html
    在这里插入图片描述
    在这里插入图片描述
$(function(){
	$("#publishBtn").click(publish);
});

function publish() {
	$("#publishModal").modal("hide");//将输入帖子框先隐藏框
	//服务器获取标题和内容
	var title=$("#recipient-name").val();//jqueryID选择器,选中文本框得到文本框内的值
	var content =$("#message-text").val();
	//发送异步请求
	$.post(
		CONTEXT_PATH+"/discuss/add",
		{"title":title,"content":content},
		function(data){
			data=$.parseJSON(data);
			//在提示框中显示返回消息
			$("#hintModal").text(data.msg);
			//显示提示框
			$("#hintModal").modal("show");
			//2秒后自动隐藏提示框
			setTimeout(function(){
				$("#hintModal").modal("hide");
				//刷新页面,判断是否发布成功
				if(data.code==0){
					window.location.reload();
				}
			}, 2000);

		}
	);

}

在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值