1 实体创建
News(class)
package com.clubTest.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
/**
* 新闻实体
* @author Administrator
*
*/
@Entity
@Table(name="t_news")
public class News {
@Id
@GeneratedValue
private Integer id; // 编号
@Column(length=200)
private String name; // 新闻名称
@Column(length=500)
private String summary; // 摘要
@Lob
@Column(columnDefinition="TEXT")
private String content; // 帖子内容
@Column(length=300)
private String imageName; // 新闻图片
private Integer hot; // 是否热门新闻 1 热门 0 非热门
private Date publishDate; // 发布日期
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
public Integer getHot() {
return hot;
}
public void setHot(Integer hot) {
this.hot = hot;
}
@JsonSerialize(using=CustomDateTimeSerializer.class)
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
}
}
2repository创建,相当于Dao 创建接口 interface
NewsRepository (interface)
package com.clubTest.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import com.clubTest.entity.News;
public interface NewsRepository extends JpaRepository<News,Integer>,JpaSpecificationExecutor<News>{
/**
* 获取上一个新闻
* @param id
* @return
*/
@Query(value="SELECT * FROM t_news WHERE id<?1 ORDER BY id DESC LIMIT 1",nativeQuery=true)
public News getLast(Integer id);
/**
* 获取下一个新闻
* @param id
* @return
*/
@Query(value="select * from t_news where id>?1 order by id asc limit 1",nativeQuery=true)
public News getNext(Integer id);
}
3服务层
NewsService(Interface)
```java
package com.clubTest.service;
import java.util.List;
import com.clubTest.entity.News;
public interface NewsService {
public void save(News news) ;
/**
* 分页查询电影信息
* @param page
* @param pageSize
* @return
*/
public List<News> list(News news,Integer page,Integer pageSize);
/**
* 获取总记录数
* @return
*/
public Long getCount(News news);
/**
* 根据id查找实体
* @param id
* @return
*/
public News findById(Integer id);
/**
* 根据id删除电影
* @param id
*/
public void delete(Integer id);
/**
* 获取上一个新闻
* @param id
* @return
*/
public News getLast(Integer id);
/**
* 获取下一个新闻
* @param id
* @return
*/
public News getNext(Integer id);
}
4NewsServiceImpl
```java
package com.clubTest.service.impl;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import com.clubTest.entity.News;
import com.clubTest.repository.NewsRepository;
import com.clubTest.service.NewsService;
import com.clubTest.util.StringUtil;
@Service("newsService")
public class NewsServiceImpl implements NewsService{
@Resource
private NewsRepository newsRepository;
@Override
public void save(News news) {
newsRepository.save(news);
}
@Override
public List<News> list(News news, Integer page, Integer pageSize) {
Pageable pageable=new PageRequest(page, pageSize,Sort.Direction.DESC,"publishDate");
Page<News> pageWebSite=newsRepository.findAll(new Specification<News>() {
@Override
public Predicate toPredicate(Root<News> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Predicate predicate=cb.conjunction();
if(news!=null){
if(StringUtil.isNotEmpty(news.getName())){
predicate.getExpressions().add(cb.like(root.get("name"), "%"+news.getName().trim()+"%"));
}
if(news.getHot()!=null && news.getHot()==1){
predicate.getExpressions().add(cb.equal(root.get("hot"), 1));
}
}
return predicate;
}
}, pageable);
return pageWebSite.getContent();
}
@Override
public Long getCount(News news) {
Long count=newsRepository.count(new Specification<News>() {
@Override
public Predicate toPredicate(Root<News> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Predicate predicate=cb.conjunction();
if(news!=null){
if(StringUtil.isNotEmpty(news.getName())){
predicate.getExpressions().add(cb.like(root.get("name"), "%"+news.getName().trim()+"%"));
}
if(news.getHot()!=null && news.getHot()==1){
predicate.getExpressions().add(cb.equal(root.get("hot"), 1));
}
}
return predicate;
}
});
return count;
}
@Override
public News findById(Integer id) {
return newsRepository.findById(id).orElse(null);
}
@Override
public void delete(Integer id) {
newsRepository.deleteById(id);
}
@Override
public News getLast(Integer id) {
return newsRepository.getLast(id);
}
@Override
public News getNext(Integer id) {
return newsRepository.getNext(id);
}
}
5NewsController(class)
package com.clubTest.controller;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.clubTest.entity.News;
import com.clubTest.service.NewsService;
import com.clubTest.util.PageUtil;
@Controller
@RequestMapping("/news")
public class NewsController {
@Resource
private NewsService newsService;
/**
* 分页查询新闻信息
* @param page
* @return
* @throws Exception
*/
@RequestMapping("/list/{id}")
public ModelAndView list(@PathVariable(value="id",required=false)Integer page)throws Exception{
ModelAndView mav=new ModelAndView();
List<News> newsList=newsService.list(null, page-1, 6);
Long total=newsService.getCount(null);
mav.addObject("newsList", newsList);
mav.addObject("pageCode", PageUtil.genPagination("/news/list", total, page, 6));
mav.addObject("title", "新闻列表");
mav.addObject("mainPage", "news/list");
mav.addObject("mainPageKey", "#f");
mav.setViewName("newsIndexPage");
return mav;
}
/**
* 根据id获取新闻详细信息
* @param id
* @return
* @throws Exception
*/
@RequestMapping("/{id}")
public ModelAndView view(@PathVariable(value="id",required=false)Integer id)throws Exception{
ModelAndView mav=new ModelAndView();
News news=newsService.findById(id);
mav.addObject("news", news);
mav.addObject("title", news.getName());
mav.addObject("pageCode", this.getUpAndDownPageCode(newsService.getLast(id), newsService.getNext(id)));
mav.addObject("mainPage", "news/view");
mav.addObject("mainPageKey", "#f");
mav.setViewName("newsView");
return mav;
}
/**
* 获取下一个新闻你和上一个新闻
* @param lastNews
* @param nextNews
* @return
*/
private String getUpAndDownPageCode(News lastNews,News nextNews){
StringBuffer pageCode=new StringBuffer();
if(lastNews==null || lastNews.getId()==null){
pageCode.append("<p>上一篇:没有了</p>");
}else{
pageCode.append("<p>上一篇:<a href='/news/"+lastNews.getId()+"'>"+lastNews.getName()+"</a></p>");
}
if(nextNews==null || nextNews.getId()==null){
pageCode.append("<p>下一篇:没有了</p>");
}else{
pageCode.append("<p>下一篇:<a href='/news/"+nextNews.getId()+"'>"+nextNews.getName()+"</a></p>");
}
return pageCode.toString();
}
}
6 后台代码 NewsAdminController
package com.clubTest.controller.admin;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.clubTest.entity.News;
import com.clubTest.service.NewsService;
import com.clubTest.util.DateUtil;
@RestController
@RequestMapping("/admin/news")
public class NewsAdminController {
@Resource
private NewsService newsService;
@Value("${imageFilePath}")
private String imageFilePath;
@RequestMapping("/ckeditorUpload")
public String ckeditorUpload(@RequestParam("upload")MultipartFile file,String CKEditorFuncNum)throws Exception{
String fileName=file.getOriginalFilename(); // 获取文件名
String suffixName=fileName.substring(fileName.lastIndexOf(".")); // 获取文件的后缀
String newFileName=DateUtil.getCurrentDateStr()+suffixName;
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(imageFilePath+newFileName));
StringBuffer sb=new StringBuffer();
sb.append("<script type=\"text/javascript\">");
sb.append("window.parent.CKEDITOR.tools.callFunction("+ CKEditorFuncNum + ",'" +"/static/newsImage/"+ newFileName + "','')");
sb.append("</script>");
return sb.toString();
}
/**
* 添加或者修改电影信息
* @param film
* @param file
* @return
* @throws Exception
*/
@RequestMapping("/save")
public Map<String,Object> save(News news,@RequestParam("imageFile")MultipartFile file)throws Exception{
if(!file.isEmpty()){
String fileName=file.getOriginalFilename(); // 获取文件名
String suffixName=fileName.substring(fileName.lastIndexOf(".")); // 获取文件的后缀
String newFileName=DateUtil.getCurrentDateStr()+suffixName;
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(imageFilePath+newFileName));
news.setImageName(newFileName);
}
news.setPublishDate(new Date());
Map<String,Object> resultMap=new HashMap<String,Object>();
newsService.save(news);
resultMap.put("success", true);
return resultMap;
}
/**
* 分页查询新闻信息
* @param page
* @param rows
* @return
* @throws Exception
*/
@RequestMapping("/list")
public Map<String,Object> list(News news,@RequestParam(value="page",required=false)Integer page,@RequestParam(value="rows",required=false)Integer rows)throws Exception{
List<News> newsList=newsService.list(news,page-1, rows);
Long total=newsService.getCount(news);
Map<String,Object> resultMap=new HashMap<String,Object>();
resultMap.put("rows", newsList);
resultMap.put("total", total);
return resultMap;
}
/**
* 删除新闻信息
* @param ids
* @return
* @throws Exception
*/
@RequestMapping("/delete")
public Map<String,Object> delete(@RequestParam(value="ids")String ids)throws Exception{
String []idsStr=ids.split(",");
Map<String,Object> resultMap=new HashMap<String,Object>();
for(int i=0;i<idsStr.length;i++) {
newsService.delete(Integer.parseInt(idsStr[i]));
}
resultMap.put("success", true);
return resultMap;
}
/**
* 根据id查找实体
* @param id
* @return
* @throws Exception
*/
@RequestMapping("/findById")
public News findById(Integer id)throws Exception{
return newsService.findById(id);
}
}
7 后台管理
newsManage.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>电影信息管理页面</title>
<link rel="stylesheet" type="text/css" href="/static/jquery-easyui-1.3.3/themes/default/easyui.css" />
<link rel="stylesheet" type="text/css" href="/static/jquery-easyui-1.3.3/themes/icon.css" />
<script type="text/javascript" src="/static/jquery-easyui-1.3.3/jquery.min.js"></script>
<script type="text/javascript" src="/static/jquery-easyui-1.3.3/jquery.easyui.min.js"></script>
<script type="text/javascript" src="/static/jquery-easyui-1.3.3/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript">
var url;
function searchFilm(){
$("#dg").datagrid("load",{
"name":$("#s_name").val()
});
}
function formatHot(val,row){
if(val==1){
return "是";
}else{
return "不是";
}
}
function formatImageName(val,row){
return "<img width=100 height=100 src='/static/newsImage/"+val+"'/>";
}
function deleteFilm(){
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("/admin/news/delete",{ids:ids},function(result){
if(result.success){
$.messager.alert("系统提示","数据已成功删除!");
$("#dg").datagrid("reload");
}else{
$.messager.alert("系统提示",result.errorInfo);
}
},"json");
}
});
}
function openFilmModifyTab(){
var selectedRows=$("#dg").datagrid("getSelections");
if(selectedRows.length!=1){
$.messager.alert("系统提示","请选择一条要修改的新闻!");
return;
}
var row=selectedRows[0];
window.parent.openTab('修改新闻','modifyNews.html?id='+row.id,'icon-modifyFilm');
}
</script>
</head>
<body style="margin: 1px">
<table id="dg" title="新闻信息管理" class="easyui-datagrid"
fitColumns="true" pagination="true" rownumbers="true"
url="/admin/news/list" fit="true" toolbar="#tb">
<thead>
<tr>
<th field="cb" checkbox="true" align="center"></th>
<th field="id" width="20" align="center">编号</th>
<th field="imageName" width="50" align="center" formatter="formatImageName">新闻图片</th>
<th field="name" width="100" align="center">新闻名称</th>
<th field="summary" width="200" align="center">新闻摘要</th>
<th field="hot" width="50" align="center" formatter="formatHot">热门?</th>
<th field="publishDate" width="150" align="center">发布日期</th>
</thead>
</table>
<div id="tb">
<div>
<a href="javascript:openFilmModifyTab()" class="easyui-linkbutton" iconCls="icon-edit" plain="true">修改</a>
<a href="javascript:deleteFilm()" class="easyui-linkbutton" iconCls="icon-remove" plain="true">删除</a>
</div>
<div>
电影名称: <input type="text" id="s_name" size="20" onkeydown="if(event.keyCode==13) searchFilm()"/>
<a href="javascript:searchFilm()" class="easyui-linkbutton" iconCls="icon-search" plain="true">搜索</a>
</div>
</div>
</body>
</html>
8 页面展示 list.html
<meta charset="UTF-8"></meta>
<div id="f">
<!-- <div class="data_list">
<div class="data_list_title">
<img src="/static/images/list_icon.png"></img>
电影列表</div>
<div class="datas lImageDatas">
<ul class="imageUl">
<li class="imageLi" th:each="news:${newsList}">
<a target="_blank" th:href="'/news/'+${news.id}" th:title="${news.name}">
<img class="indexFilm" th:src="'/static/newsImage/'+${news.imageName}"></img>
<p th:text="${news.name}"></p>
</a>
</li>
</ul>
</div>
</div>
-->
<div class="data_list">
<div class="data_list_title">
<img src="/static/images/list_icon.png"></img>
新闻列表
</div>
<div class="newsBig">
<ul>
<li class="newsMiddle" th:each="news:${newsList}">
<div class="newsMiddle1">
<a target="_blank" th:href="'/news/'+${news.id}" th:title="${news.name}">
<div class="decrotion1">
<img class="newsImage" th:src="'/static/newsImage/'+${news.imageName}" ></img>
</div>
<div calss="decrotion2">
<p style="color:black;font-weight:bold;font-size:20px;" th:text="${news.name}"></p>
<p style="color:black;margin-left:20px;" th:text="${news.summary}"></p>
</div>
</a>
</div>
</li>
</ul>
</div>
</div>
<div style="margin-top:50px;">
<nav>
<ul class="pagination pagination-sm" th:utext="${pageCode}">
</ul>
</nav>
</div>
</div>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<title>新闻资讯</title>
<link rel="stylesheet" th:href="@{/static/bootstrap3/css/bootstrap.min.css}" />
<link rel="stylesheet" th:href="@{/static/bootstrap3/css/bootstrap-theme.min.css}" />
<link rel="stylesheet" th:href="@{/static/css/index.css}" />
<link rel="stylesheet" th:href="@{/static/css/news.css}" />
<link rel="stylesheet" th:href="@{/static/css/film.css}"/>
</head>
<body>
<!-- 公共页面,头部菜单抽取 -->
<div class="head">
<div class="row">
<div th:include="common/head::#h"></div>
</div>
</div>
<div class="newsBackgroundImage">
<div class="container">
<div class="row">
<div class="col-md-8" style="margin-top:200px;margin-left:50px;">
<h1 style="color:white;">服务项目</h1>
<div style="color:blue;font-size:30px;font-weight:bold;vertical-align:middle;">-----------</div>
<p style="margin-top:15px;color:white;">黑天鹅工作室致力于为您提供最优质的服务,黑天鹅工作室致力于为您</p>
<p style="margin-top:15px;color:white;">黑天鹅工作室致力于为您提</p>
</div>
</div>
</div>
</div>
<div class="container" style="margin-top:50px;">
<div class="row">
<div class="col-md-8">
<div th:include="${mainPage}::${mainPageKey}"></div>
</div>
<div class="col-md-4">
<div class="data_list">
<div class="data_list_title">
<img src="/static/images/hot_icon.png" />
最新热门新闻推荐
</div>
<div class="datas">
<ul>
<li th:each="newestHotNews:${application.newestHotNewsList}"><span><a target="_blank" th:href="'/news/'+${newestHotNews.id}" th:title="${newestHotNews.name}" th:text="${newestHotNews.name}"></a></span></li>
</ul>
</div>
</div>
<div class="data_list">
<div class="data_list_title">
<img src="/static/images/link_icon.png" />
友情链接
</div>
<div class="datas">
<ul>
<li th:each="link:${application.linkList}"><span><a target="_blank" th:href="${link.url}" th:title="${link.name}" th:text="${link.name}"></a></span></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="head" style="padding-top:30px;">
<div th:include="common/foot::#f"></div>
</div>
</body>
</html>