SSM博客系统(新增博客以及博客类别的选择)

Blog

/**
 * 博客
 */
public class Blog implements Serializable {
	private static final long serialVersionUID = 1L;
	/**主键*/
	private Integer id;
	/**标题*/
	private String title;
	/**摘要*/
	private String summary;
	/**发表时间*/
	private Date releaseDate;
	/**点击数*/
	private Integer clickHit;
	/**评论数*/
	private Integer replyHit;
	/**内容*/
	private String content;
	/**所属博客类型*/
	private BlogType blogType;
	/**关键字*/
	private String keyWord;
	
	/**纯文本格式的内容*/
	private String contentNoTag; 
	/**发表时间*/
	private String releaseDateStr;//以便更改时间
	/**博客数量*/
	private Integer blogCount;
	//get set
}

BlogDao

package com.blog.dao;

import java.util.List;
import java.util.Map;

import javax.sound.sampled.LineListener;

import com.blog.entity.Blog;

public interface BlogDao {
	/**无参数查询博客列表(供首页使用)*/
	public List<Blog> countList();
	
	/**带参数查询博客列表*/
	public List<Blog> list(Map<String,Object> map);
	
	/**带参数查询博客数量*/
	public Long getTotal(Map<String,Object> map);
	
	/**根据主键查询一条博客信息*/
	public Blog findById(Integer id);
	
	/**添加一条博客*/
	public Integer add(Blog blog);
	
	/**修改一条博客*/
	public Integer update(Blog blog);
	
	/**根据主键删除一条博客*/
	public Integer delete(Integer id);
	
	/**根据类型查询博客数量*/
	public Integer getBlogByTypeId(Integer typeId);
	
	/**上一篇*/
	public Blog getLastBlog(Integer id);
	
	/**下一篇*/
	public Blog getNextBlog(Integer id);
	
}

BlogMapper

<?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.blog.dao.BlogDao">

<resultMap type="Blog" id="BlogResult">
	<result property="id" column="id"/>
	<result property="title" column="title"/>
	<result property="summary" column="summary"/>
	<result property="releaseDate" column="releaseDate"/>
	<result property="clickHit" column="clickHit"/>
	<result property="replyHit" column="replyHit"/>
	<result property="content" column="content"/>
	<result property="keyWord" column="keyWord"/>
	<association property="blogType" column="typeId" select="com.blog.dao.BlogTypeDao.findById"/>	
</resultMap>
	
	<select id="countList" resultMap="BlogResult">
		select date_format(releaseDate,'%Y年%m月') as releaseDateStr,count(*) as blogCount
		from t_blog group by date_format(releaseDate,'%Y年%m月')
		order by date_format(releaseDate,'%Y年%m月') desc
	</select>
	
	<select id="list" parameterType="Map" resultMap="BlogResult">
		select * from t_blog
		<where>
			<if test="title!=null and title!='' ">
				and title like #{title}
			</if>
			<if test="typeId!=null and typeId!='' ">
				and typeId = #{typeId}
			</if>
			<if test="releaseDateStr!=null and releaseDateStr!='' ">
				and date_format(releaseDate,'%Y年%m月')= #{releaseDateStr}
			</if>
		</where>
		order by releaseDate desc
		<if test="start!=null and size!=null">
			limit #{start},#{size}
		</if>
	</select>
	
	<select id="getTotal" parameterType="Map" resultType="Long">
		select count(*) from t_blog
		<where>
			<if test="title!=null and title!='' ">
				and title like #{title}
			</if>
			<if test="typeId!=null and typeId!='' ">
				and typeId = #{typeId}
			</if>
			<if test="releaseDateStr!=null and releaseDateStr!='' ">
				and date_format(releaseDate,'%Y年%m月')= #{releaseDateStr}
			</if>
		</where>
	</select>
	
	<select id="findById" parameterType="Integer" resultMap="BlogResult">
		select * from t_blog where id=#{id}
	</select>
	
	<insert id="add" useGeneratedKeys="true" keyProperty="id" parameterType="Blog">
		insert into t_blog values(null,#{title},#{summary},now(),0,0,#{content},#{blogType.id},#{keyWord})
	</insert>
	
	<update id="update" parameterType="Blog">
		update t_blog
		<set>
			<if test="title!=null and title!=''">
				title=#{title},
			</if>
			<if test="summary!=null and summary!=''">
				summary=#{summary},
			</if>
			<if test="content!=null and content!=''">
				content=#{content},
			</if>
			<if test="blogType.id!=null">
				typeId=#{blogType.id},
			</if>
			<if test="clickHit!=null">
				clickHit=#{clickHit},
			</if>
			<if test="replyHit!=null">
				replyHit=#{replyHit},
			</if>
			<if test="keyWord!=null and keyWord!=''">
				keyWord=#{keyWord},
			</if>			
		</set>
		where id=#{id}
	</update>
	
	<delete id="delete" parameterType="Integer">
		delete from t_blog where id=#{id}
	</delete>
	
	<select id="getBlogByTypeId" parameterType="Integer" resultType="Integer">
		select count(*) from t_blog where typeId=#{typeId}
	</select>
	
	<select id="getLastBlog" parameterType="Integer" resultMap="BlogResult">
		select * from t_blog where id&lt;#{id} order by id desc limit 1
	</select>
	
	<select id="getNextBlog" parameterType="Integer" resultMap="BlogResult">
		select * from t_blog where id&gt;#{id} order by id limit 1
	</select>
</mapper>

Association关联的结果查询,就是在查询出结果后,根据查询的列和resultMap定义的对应关系,来创建对象并写入值。

  1. select:下一条要执行的sql语句
  2. property:注入给当前实体类的某个属性
  3. column:在上一次查询的结果集中,用那些列值去执行下一条sql语句

嵌入结果映射 – 结果映射自身的关联,或者参考一个(注:“参考一个”,这里参考一个是通过对象的Key来唯一确定的,如果Key值一样,就直接用已经存在的这个对象)

useGeneratedKeys=“true” keyProperty=“id”
useGeneratedKeys设置为 true 时,表示如果插入的表id以自增列为主键,则允许 JDBC 支持自动生成主键,并可将自动生成的主键id返回。
useGeneratedKeys参数只针对 insert 语句生效,默认为 false;

BlogService

public interface BlogService {
	/**无参数查询博客列表(供首页使用)*/
	public List<Blog> countList();
	
	/**带参数查询博客列表*/
	public List<Blog> list(Map<String,Object> map);
	
	/**带参数查询博客数量*/
	public Long getTotal(Map<String,Object> map);
	
	/**根据主键查询一条博客信息*/
	public Blog findById(Integer id);
	
	/**添加一条博客*/
	public Integer add(Blog blog);
	
	/**修改一条博客*/
	public Integer update(Blog blog);
	
	/**根据主键删除一条博客*/
	public Integer delete(Integer id);
	
	/**根据类型查询博客数量*/
	public Integer getBlogByTypeId(Integer typeId);
	
	/**上一篇*/
	public Blog getLastBlog(Integer id);
	
	/**下一篇*/
	public Blog getNextBlog(Integer id);
	
}

BlogServiceImpl(service的实现类)

@Service("blogService")
public class BlogServiceImpl implements BlogService {
	//实现dao
	@Resource
	private BlogDao blogDao;
	public List<Blog> countList() {
		// TODO Auto-generated method stub
		return blogDao.countList();
	}

	public List<Blog> list(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return blogDao.list(map);
	}

	public Long getTotal(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return blogDao.getTotal(map);
	}

	public Blog findById(Integer id) {
		// TODO Auto-generated method stub
		return blogDao.findById(id);
	}

	public Integer add(Blog blog) {
		// TODO Auto-generated method stub
		return blogDao.add(blog);
	}

	public Integer update(Blog blog) {
		// TODO Auto-generated method stub
		return blogDao.update(blog);
	}

	public Integer delete(Integer id) {
		// TODO Auto-generated method stub
		return blogDao.delete(id);
	}

	public Integer getBlogByTypeId(Integer typeId) {
		// TODO Auto-generated method stub
		return null;
	}

	public Blog getLastBlog(Integer id) {
		// TODO Auto-generated method stub
		return null;
	}

	public Blog getNextBlog(Integer id) {
		// TODO Auto-generated method stub
		return null;
	}


}

启动项目发现登录错误,但是用户名密码是对的这里肯定是刚刚写的代码错误了

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aiYqM67y-1649503321464)(C:\Users\love yourself\AppData\Roaming\Typora\typora-user-images\image-20220403110835515.png)]

###看看控制台( Could not find result map com.blog.dao.BlogDao.Long-找不到结果映射com.blog.dao.BlogDao.Long)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lT3boBmG-1649503321466)(C:\Users\love yourself\AppData\Roaming\Typora\typora-user-images\image-20220403111032108.png)][外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-W7ja1Kg5-1649503321467)(C:\Users\love yourself\AppData\Roaming\Typora\typora-user-images\image-20220403111314143.png)]

富文本编辑器乱码

引入文件 加上 charset=“gbk” 清楚浏览器缓存 刷新一下

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4dnyAicp-1649503321467)(C:\Users\love yourself\AppData\Roaming\Typora\typora-user-images\image-20220403132305749.png)]

BlogAdminController(新增博客)

private BlogService blogService;
	
	/**
	 * 保存博客
	 * @throws Exception 
	 */
	@RequestMapping("/save")
	public  String save(Blog blog,HttpServletResponse response) throws Exception {
		int resultTotal=blogService.add(blog);
		JSONObject result=new JSONObject();
		if(resultTotal>0) {
			result.put("success", Boolean.valueOf(true));
		}else {
			result.put("success", Boolean.valueOf(false));
		}
		ResponseUtil.write(response, result);
		return null;
	}

新增博客列表writeBlog

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>写博客页面</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/jquery-easyui-1.3.3/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/jquery-easyui-1.3.3/themes/icon.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/static/jquery-easyui-1.3.3/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/jquery-easyui-1.3.3/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/jquery-easyui-1.3.3/locale/easyui-lang-zh_CN.js"></script>

<script type="text/javascript" charset="gbk" src="${pageContext.request.contextPath}/static/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="gbk" src="${pageContext.request.contextPath}/static/ueditor/ueditor.all.min.js"></script>
<!-- 手动加载语言,避免在IE下有时因为加载语言导致编辑器加载失败 -->
<!-- 在这里加载的语言会覆盖在配置项目里添加的语言类型,比如在配置项目里配置的是英文,这里加载的是中文,那最后就是中文  -->
<script type="text/javascript" charset="gbk" src="${pageContext.request.contextPath}/static/ueditor/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript">

/**发布博客*/
 function submitData(){
	var title=$("#title").val();
	var blogTypeId=$("#blogTypeId").val();
	var content=UE.getEditor('editor').getContent();
	var keyWord=$("#keyWord").val();
	
	if(title==null || title==''){
		$.messager.alert("系统提示","请输入标题!");
	}else if(blogTypeId==null || blogTypeId==''){
		$.messager.alert("系统提示","请输入博客类别!");
	}else if(content==null || content==''){
		$.messager.alert("系统提示","请输入内容!");
	}else{
		$.post("${pageContext.request.contextPath}/admin/blog/save.do",
			{'title':title,'blogType.id':blogTypeId,'content':content,
			'contentNoTag':UE.getEditor('editor').getContentTxt(),
			'summary':UE.getEditor('editor').getContentTxt().substr(0,155),'keyWord':keyWord},
			function(result){
				if(result.success){
					$.messager.alert("系统提示","博客发布成功!");
				}else{
					$.messager.alert("系统提示","博客发布失败!");
				}
		},"json");
	}
}
</script>
</head>
<body style="margin: 10px">
<div id="p" class="easyui-panel" title="编写博客" style="padding: 10px">
<table cellspacing="20px">
	<tr>
		<td width="80px">博客标题:</td>
		<td><input type="text" id="title" name="title" style="width: 400px;"/></td>
	</tr>
	<tr>
			<!-- 这里不用再设置宽度 他回继承上面的宽度 -->
			<td >所属类别:</td>
			<td> <input type="text" id="blogTypeId" name="blogType.id" style="width:400px;" /></td>
		</tr>
	<tr>
		<td>博客内容:</td>
		<td>
			<script id="editor" type="text/plain" style="width:100%;height:500px;"></script>
		</td>
	</tr>
	<tr>
		<td>关键字:</td>
		<td><input type="text" id="keyWord" name="keyWord" style="width: 400px;"/>
			&nbsp;(多个关键字中间用空格隔开)</td>
	</tr>
	<tr>
		<td></td>
		<td><a href="javascript:submitData()" class="easyui-linkbutton" data-options="iconCls:'icon-submit'">发布博客</a></td>
	</tr>
</table>
</div>
<script type="text/javascript">
	//实例化编辑器
	var ue = UE.getEditor("editor");
</script>
</body>
</html>
		
		

SQLError

**[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-C7JHF1QV-1649503321468)(C:\Users\love yourself\AppData\Roaming\Typora\typora-user-images\image-20220403141658992.png)]

BlogMapper里面的SQL语句写错

BlogAdminController(博客列表)

/**
	 * 查询博客信息列表
	 */
	@RequestMapping({"/list"})
	public String list(@RequestParam(value="page",required=false)String page,
			@RequestParam(value="rows",required=false)String rows,Blog blog,
			HttpServletResponse response) throws Exception {
		PageBean pageBean = new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("start", pageBean.getStart());
		map.put("size",pageBean.getPageSize());
		map.put("title", StringUtil.formatLike(blog.getTitle()));
		//分页查询博客信息列表
		List<Blog> list = blogService.list(map);
		//获取共有多少条博客信息
		Long total = blogService.getTotal(map);
		
		//封装到json
		JSONObject result = new JSONObject();
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(list,config);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
		return null;
	}

博客管理jsp

<title>博客管理页面</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/jquery-easyui-1.3.3/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/jquery-easyui-1.3.3/themes/icon.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/static/jquery-easyui-1.3.3/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/jquery-easyui-1.3.3/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/jquery-easyui-1.3.3/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript">

/**返回该行的博客类型名称*/
function formatBlogType(val,row){
	return val.typeName;
}

/**点击标题弹出用户预览页面*/
function formatTitle(val,row){
	return "<a target='_blank' href='${pageContext.request.contextPath}/blog/articles/"+row.id+".html'>"+val+"</a>";
}

/**
 * 根据标题查询
 */
 function searchBlog(){
	$("#dg").datagrid('load',{"title":$("#s_title").val()});
}

/**
 * 修改一条博客信息
 */
 function openBlogModifyTab(){
	var selectedRows=$("#dg").datagrid("getSelections");
	if(selectedRows.length!=1){
		$.messager.alert("系统提示","请选择一个要修改的博客!");
		return;
	}
	var row=selectedRows[0];
	window.parent.openTab("修改博客","modifyBlog.jsp?id="+row.id,"icon-writeBlog");
}

/**
 * 删除博客信息
 */
 function deleteBlog(){
	 var selectedRows=$("#dg").datagrid("getSelections");
	 if(selectedRows.length==0){
		 $.messager.alert("系统提示","请选择要删除的博客");
		 return;
	 }
	 var strIds=[];
	 for(var i=0;i<selectedRows.length;i++){
		 strIds.push(selectedRows[i].id);
	 }
	 var ids = strIds.join(",");
	 $.messager.confirm("系统提示","您确定要删除这<font color=red>"+selectedRows.length+"</font>条数据吗?",function(r){
		 if(r){
			 $.post("${pageContext.request.contextPath}/admin/blog/delete.do",{ids:ids},function(result){
				 if(result.success){
					 $.messager.alert("系统提示","数据已成功删除!");
					 $("#dg").datagrid("reload");
				 }else{
					 $.messager.alert("系统提示","数据删除失败!"); 
				 }
			 },"json");
		 }
	 });
}
</script>
</head>
<body style="margin: 10px">
	<table id="dg" title="博客管理" class="easyui-datagrid" fitcolumns="true"
		pagination="true" rownumbers="true" fit="true" toolbar="#tb"
		url="${pageContext.request.contextPath}/admin/blog/list.do">
		<thead>
			<tr>
				<th field="cb" checkbox="true" align="center"></th>
				<th field="id" width="20" align="center">编号</th>
				<th field="title" width="200" align="center" formatter="formatTitle">标题</th>
				<th field="releaseDate" width="50" align="center">发布日期</th>
				<th field="blogType" width="50" align="center" formatter="formatBlogType">博客类别</th>
			</tr>
		</thead>
	</table>
	
	<div id="tb">
		<div>
			<a href="javascript:openBlogModifyTab()" class="easyui-linkbutton" iconCls="icon-edit" plain="true">修改</a>
			<a href="javascript:deleteBlog()" class="easyui-linkbutton" iconCls="icon-remove" plain="true">删除</a>
		</div>
		<div>
			&nbsp;标题:&nbsp;<input type="text" id="s_title" size="20" οnkeydοwn="if(event.keyCode=13) searchBlog()"/>
			<a href="javascript:searchBlog()" class="easyui-linkbutton" iconCls="icon-search" plain="true">搜索</a>
		</div>
	</div>
</body>
</html>

## [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TdckaOIG-1649503321469)(C:\Users\love yourself\AppData\Roaming\Typora\typora-user-images\image-20220403232012261.png)]

InitComponent 实现的编写 一运行就可获取到类别信息 并保存到缓存中

ServletContext

ServletContext官方叫servlet上下文。服务器会为每一个工程创建一个对象,这个对象就是ServletContext对象。这个对象全局唯一,而且工程内部的所有servlet都共享这个对象。所以叫全局应用程序共享对象。

作用

  1. 是一个域对象

  2. 可以读取全局配置参数

  3. 可以搜索当前工程目录下面的资源文件

  4. 可以获取当前工程名字(了解)

InitComponent

package com.blog.service.impl;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.blog.entity.Blog;
import com.blog.entity.BlogType;
import com.blog.entity.Blogger;

import com.blog.service.BlogService;
import com.blog.service.BlogTypeService;
import com.blog.service.BloggerService;

/**
 * 项目初始化,查询到项目类别信息
 * @author love yourself
 *
 */
@Component
@Service
public class InitComponent implements ServletContextListener,ApplicationContextAware {
	private ApplicationContext applicationContext;
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext=applicationContext;
		
	}
	/**
	 * 项目启动会	执行
	 */
	public void contextInitialized(ServletContextEvent sce) {
		ServletContext application=sce.getServletContext();
		BlogTypeService blogTypeService=(BlogTypeService) applicationContext.getBean("blogTypeService");
		List<BlogType> blogTypeList=blogTypeService.countList();
		application.setAttribute("blogTypeCountList", blogTypeList);
	}

	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值