发布帖子
1、用jQuery发送AJAX请求的示例2、发布帖子2.1 DAO层增加插入帖子的方法2.2 编写service业务逻辑2.3 编写controller类 AJAX Asynchronous JavaScript and XML异步的JavaScript与XML,不是一门新技术,只是一个新的术语。使用AJAX,网页能够将增量更新呈现在页面上,而不需要刷新整个页面。虽然X代表XML,但目前JSON的使用比XML更加普遍。/zh-CN/docs/Web/Guide/AJAX 示例 使用jQuery发送AJAX请求。 实践 采用AJAX请求,实现发布帖子的功能。1、用jQuery发送AJAX请求的示例
1.1 先引入Fastjson jar包
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.58</version></dependency>
1.2 CommunityUtils下,getJSONString
public class CommunityUtil{// 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);}// 此处的main方法用来测试上面的方法类,没有直接编写在test类中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.3 编写前端页面接受值
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title></head><body><!-- 静态类static下的网页可以直接访问 --><p><input type="button" value="发送" onclick="send()"></p><script src="/jquery-3.3.1.min.js" crossorigin="anonymous"></script><script>// 此处调用的是异步的ajax请求function send() {$.post("/community/alpha/ajax",{"name":"张三", "age":18},// 回调完函数后,将服务器返回的数据传到data里function(data) {console.log(typeof(data));console.log(data);data = $.parseJSON(data);console.log(typeof(data));console.log(data.code);console.log(data.msg);})}</script></body></html>
1.4 编写controller,测试与前端ajax交互的正确性
public class AlphaController {// ajax示例@RequestMapping(path = "/ajax", method = RequestMethod.POST)@ResponseBody // 给页面返回的是字符串,而不是页面public String testAjax(String name, int age) {System.out.println(name);System.out.println(age);return CommunityUtil.getJSONString(0, "操作成功");}}
2、发布帖子
2.1 DAO层增加插入帖子的方法
@Mapperpublic interface DiscussPostMapper {// 增加帖子int insertDiscussPost(DiscussPost discussPost);}
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-////DTD Mapper 3.0//EN" "/dtd/mybatis-3-mapper.dtd"><mapper namespace="munity.dao.DiscussPostMapper"><insert id="insertDiscussPost" parameterType="DiscussPost">insert into discuss_post (<include refid="insertFields"></include>)values(#{userId}, #{title}, #{content}, #{type}, #{status}, #{createTime}, #{commentCount}, #{score} )</insert></mapper>
2.2 编写service业务逻辑
此处的业务逻辑主要是过滤敏感词。
public class DiscussPostService {public int addDiscussPost(DiscussPost post) {if (post == null) {throw new IllegalArgumentException("参数不能为空");}// title 和 content 部分需要过滤// 标签也要处理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);}}
2.3 编写controller类
@Controller@RequestMapping("/discuss")public class DiscussPostController implements CommunityConstant {@Autowiredprivate DiscussPostService discussPostService;@Autowiredprivate HostHolder hostHolder;@RequestMapping(path = "/add", method = RequestMethod.POST)@ResponseBodypublic 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());post.setTitle(title);post.setContent(content);post.setCreateTime(new Date());discussPostService.addDiscussPost(post);// 报错的情况,将来统一处理return CommunityUtil.getJSONString(0, "发布成功");} }
帖子标题可以重复,查看discuss_post的建表语句:
DROP TABLE IF EXISTS `discuss_post`;/*!40101 SET @saved_cs_client= @@character_set_client */;SET character_set_client = utf8mb4 ;CREATE TABLE `discuss_post` (`id` int(11) NOT NULL AUTO_INCREMENT,`user_id` varchar(45) DEFAULT NULL,`title` varchar(100) DEFAULT NULL,`content` text,`type` int(11) DEFAULT NULL COMMENT '0-普通; 1-置顶;',`status` int(11) DEFAULT NULL COMMENT '0-正常; 1-精华; 2-拉黑;',`create_time` timestamp NULL DEFAULT NULL,`comment_count` int(11) DEFAULT NULL,`score` double DEFAULT NULL,PRIMARY KEY (`id`),KEY `index_user_id` (`user_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;/*!40101 SET character_set_client = @saved_cs_client */;
id为discuss_post的主键且自增,在插入discusspost记录时,可以不填写id字段,MySQL会自动生成。
<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-发布帖子》对你有帮助,请点赞、收藏,并留下你的观点哦!