基于javaweb+mysql的springboot美食菜谱分享平台系统设计和实现(java+springboot+mysql+ssm+thymeleaf+html)
运行环境
Java≥8、MySQL≥5.7
开发工具
eclipse/idea/myeclipse/sts等均可配置运行
适用
课程设计,大作业,毕业设计,项目练习,学习演示等
功能说明
基于javaweb+mysql的SpringBoot美食菜谱分享平台系统设计和实现(java+springboot+mysql+ssm+thymeleaf+html)
主要技术实现:spring、 springmvc、 springboot、mybatis 、session、 jquery 、 md5 、bootstarp.js tomcat、拦截器等。
具体主要功能模块如下:
1.用户模块管理:用户登录、用户注册、用户的查询、添加、删除操作、 2.美食分享笔记管理:分享笔记列表的展示、添加、修改、删除操作、 3.美食笔记详情管理:美食笔记详情列表的查看、添加、删除等操作、 4.管理员信息管理:管理员信息的查看、修改、 5.公告信息管理:公告信息的查看、添加、修改、删除操作、 6.用户模块管理:用户列表查询、添加、删除、 7.用户评论模块管理:用户评论查询、添加、删除、 8.注销退出登录管理
给大家截一部分效果图吧 系统首页主要功能:
分类查看没事菜谱信息以及智能推荐:
美食分享笔记详情信息查看、用户登录后可以进行评论、浏览量会增加、用户可以收藏当前文档信息、可以点击查看作者信息、可以对作者进行关注等操作:
用户评论操作:
富文本编辑器添加美食分享笔记:
个人中心我的收藏 我的关注等:
关注用户信息以及具体功能操作等:
后台管理主要功能:用户管理、美食菜谱笔记管理、美食菜谱详情发布以及评论等管理
response.setContentType("text/html;charset=utf-8");
try {
response.sendRedirect(new Oauth().getAuthorizeURL(request));
} catch (QQConnectException e) {
// TODO Auto-generated catch block
new QQConnectException("跳转到QQ登录页面异常");
}
}
/**
* QQ登录回调
* @param session
* @return
* @throws QQConnectException
*/
@RequestMapping(value="QQCallBack")
public String qqcallback(HttpServletRequest request,HttpServletResponse response,HttpSession session) throws QQConnectException{
response.setContentType("text/html;charset=utf-8");
AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
String accessToken = null,
openID = null;
try {
String code = request.getParameter("code");
String state = request.getParameter("state");
String session_state= (String) session.getAttribute("qq_connect_state");
if(StringUtil.isNotEmpty(session_state) && session_state.equals(state)){
accessToken = accessTokenObj.getAccessToken();
session.setAttribute("accessToken", accessToken);
if (StringUtil.isEmpty(accessToken)) {
System.out.println("没有获取到响应参数");
}else{
OpenID openIDObj = new OpenID(accessToken);
openID = openIDObj.getUserOpenID();
UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
if(userInfoBean != null && userInfoBean.getRet() == 0 && StringUtil.isEmpty(userInfoBean.getMsg())){
//获取用户成功
User user=userService.findByOpenId(openID);
if(null != user){
//已经注册过,更新用户信息,直接将信息存入session 然后跳转
user.setNickname(userInfoBean.getNickname());
user.setHeadPortrait(userInfoBean.getAvatar().getAvatarURL100());
user.setSex(userInfoBean.getGender());
user.setLatelyLoginTime(new Date());
userService.save(user);
}else{
//该用户第一次登录 先注册
user = new User();
user.setOpenId(openID);
user.setNickname(userInfoBean.getNickname());
user.setHeadPortrait(userInfoBean.getAvatar().getAvatarURL100());
user.setSex(userInfoBean.getGender());
mav.addObject("flag", flag);
}
}
mav.addObject("article", article);
mav.setViewName("/foreground/detail");
return mav;
}
/**
* 文章详情
*
* @return
*/
@RequestMapping("/myDetail/{id}")
public ModelAndView myDetail(@PathVariable(value = "id", required = false) Integer id, HttpSession session) {
ModelAndView mav = new ModelAndView();
articleService.increaseClick(id);
Article article = articleService.findById(id);
Article tempArticle = new Article();
tempArticle.setClassify(article.getClassify());
session.setAttribute("similarityList", articleService.list(tempArticle, null, null, 0, 10));
session.setAttribute("RandomArticleList", articleService.getRandomArticle(10)); // 10条随机文章
// 判断该文章是否收藏
boolean flag = false;
User user = (User) session.getAttribute("user");
if (user != null && user.getArticleIds() != null) {
String artIds = user.getArticleIds();
List<String> idsList = Arrays.asList(artIds.split(","));
if (idsList.contains(id.toString())) {
mav.addObject("flag", true);
} else {
mav.addObject("flag", flag);
}
}
List<Classify> list = classifyService.findAll();
mav.addObject("list", list);
mav.addObject("article", article);
mav.setViewName("/myDetail");
return mav;
}
@RequestMapping("/otherPerson/{id}")
public ModelAndView otherPerson(@PathVariable(value = "id", required = false) Integer id, HttpSession session) {
ModelAndView mav = new ModelAndView();
User user = userService.findById(id);
User curUser = (User) session.getAttribute("user");
if (curUser == null) {
mav.setViewName("redirect:/webLogin");
return mav;
}
/**
* 文章控制器
*
*/
@RestController
@RequestMapping("/admin/article")
public class ArticleAdminController {
@Resource
private ArticleService articleService;
@Resource
private StartupRunner startupRunner;
@Resource
private ArticleIndex articleIndex;
@Resource
private UserService userService;
private String imageFilePath = System.getProperty("user.dir") + "\\src\\main\\webapp\\static\\images\\"; // 图片上传路径
/**
* 生成所有帖子索引(审核通过的资源帖子)
*
* @return
*/
@ResponseBody
@RequestMapping(value = "/genAllIndex")
}else{
OpenID openIDObj = new OpenID(accessToken);
openID = openIDObj.getUserOpenID();
UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
if(userInfoBean != null && userInfoBean.getRet() == 0 && StringUtil.isEmpty(userInfoBean.getMsg())){
//获取用户成功
User user=userService.findByOpenId(openID);
if(null != user){
//已经注册过,更新用户信息,直接将信息存入session 然后跳转
user.setNickname(userInfoBean.getNickname());
user.setHeadPortrait(userInfoBean.getAvatar().getAvatarURL100());
user.setSex(userInfoBean.getGender());
user.setLatelyLoginTime(new Date());
userService.save(user);
}else{
//该用户第一次登录 先注册
user = new User();
user.setOpenId(openID);
user.setNickname(userInfoBean.getNickname());
user.setHeadPortrait(userInfoBean.getAvatar().getAvatarURL100());
user.setSex(userInfoBean.getGender());
user.setRegistrationDate(new Date());
user.setLatelyLoginTime(new Date());
userService.save(user);
}
//存储用户信息
session.setAttribute("currentUser", user);
}
}
}else{
System.out.println("非法请求");
}
}catch (Exception e) {
e.printStackTrace();
}
return "redirect:/";
}
@RequestMapping("/loginOut")
public String loginOut(HttpSession session,HttpServletResponse response) throws IOException{
session.removeAttribute("currentUser");
return "redirect:/";
}
}
// User user = (User) request.getSession().getAttribute("user");
// if (user == null) {
// return "webLogin";
// }
// List<Classify> list = classifyService.findAll();
// model.addAttribute("list", list);
// return "one";
// }
@RequestMapping("notePage")
public ModelAndView notePage(HttpServletRequest request) {
ModelAndView mav = new ModelAndView();
User user = (User) request.getSession().getAttribute("user");
if (user == null) {
mav.setViewName("/webLogin");
return mav;
}
List<Classify> list = classifyService.findAll();
mav.addObject("list", list);
mav.setViewName("/one");
return mav;
}
/**
* 保存笔记
*
* @param article
* @param request
* @return
*/
@RequestMapping("addNote")
public ModelAndView addNote(Article article, HttpServletRequest request) {
ModelAndView mav = new ModelAndView();
// 获取当前用户信息
User user = (User) request.getSession().getAttribute("user");
article.setUserId(user.getUserId());
article.setPublishDate(new Date());
article.setClick(0);
article.setCommentNum(0);
article.setContentNoTag(StringUtil.Html2Text(article.getContent()));
articleService.save(article);
mav.setViewName("/index");
return mav;
}
@RequestMapping("saveNote")
public ModelAndView saveNote(Article article, HttpServletRequest request) {
ModelAndView mav = new ModelAndView();
Article a = articleService.findById(article.getArticleId());
article.setPublishDate(a.getPublishDate());
// 获取当前用户信息
articleService.save(article);
mav.setViewName("/index");
/**
* 取消关注
* @param request
* @param userId
* @return
*/
@RequestMapping("/removeFocusUser")
public ModelAndView removeFocusUser(HttpServletRequest request, String userId) {
ModelAndView mav = new ModelAndView();
User user = (User) request.getSession().getAttribute("user");// 当前登录用户
String userIds = user.getUserIds();
List<String> tempList = Arrays.asList(userIds.split(","));
List<String> lineIdList = new ArrayList<>(tempList);
lineIdList.remove(userId);
String ret = StringUtils.join(lineIdList, ",");
user.setUserIds(ret);
userService.save(user);
mav.setViewName("redirect:/viewFocusUser");
return mav;
}
/**
* 关注用户
* @param request
* @param userId
* @return
*/
@RequestMapping("/addFocusUser")
public ModelAndView addFocusUser(HttpServletRequest request, String userId) {
ModelAndView mav = new ModelAndView();
User user = (User) request.getSession().getAttribute("user");// 当前登录用户
String userIds = user.getUserIds();
List<String> tempList = Arrays.asList(userIds.split(","));
List<String> lineIdList = new ArrayList<>(tempList);
lineIdList.add(userId);
String ret = StringUtils.join(lineIdList, ",");
user.setUserIds(ret);
userService.save(user);
@Resource
private UserService userService;
@Resource
private ReplyService replyService;
@Resource
private ArticleService articleService;
/**
* 分页查询评论
* @Title: list
* @param comment 评论实体
* @param commentDates 时间段 (搜索用到)
* @param page 当前页
* @param limit 每页记录数
* @param trueName 昵称
* @return 参数说明
* @return Map<String,Object> 返回类型
* @throws
*/
@RequestMapping("/list")
public Map<String, Object> list(Comment comment,
@RequestParam(value = "commentDates", required = false) String commentDates,
@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "pageSize", required = false) Integer pageSize,
@RequestParam(value = "nickname", required = false) String nickname) {
String s_bCommentDate = null; // 开始时间
String s_eCommentDate = null; // 结束时间
if (StringUtil.isNotEmpty(commentDates)) {
String[] strs = commentDates.split(" - "); // 拆分时间段
s_bCommentDate = strs[0];
s_eCommentDate = strs[1];
}
Integer userId = null;
Map<String, Object> resultMap = new HashMap<String, Object>();
if (StringUtil.isNotEmpty(nickname)) {
User user = userService.findByTrueName(nickname);
if (user != null) {
userId = user.getUserId();
}
resultMap.put("errorNo", 0);
resultMap.put("data", 1);
startupRunner.loadData();
return resultMap;
}
/**
* 新闻内容图片上传处理
*
* @param file
* @param CKEditorFuncNum
* @return
*/
@RequestMapping("/ckeditorUpload")
public String ckeditorUpload(@RequestParam("upload") MultipartFile file, String CKEditorFuncNum) {
String fileName = file.getOriginalFilename(); // 获取文件名
String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 获取文件的后缀
String newFileName = "";
try {
newFileName = DateUtil.getCurrentDateStr() + suffixName; // 生成新的文件名
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(imageFilePath + newFileName)); // 上传
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 回调到页面
StringBuffer sb = new StringBuffer();
sb.append("<script type=\"text/javascript\">");
sb.append("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",'" + "/static/images/" + newFileName
+ "','')");
sb.append("</script>");
return sb.toString();
}
}
/**
* 文章类别控制器
*
*/
@RestController
@RequestMapping("/admin/classify")
public class ClassifyController {
@Resource
private ClassifyService classifyService;
@Resource
private StartupRunner startupRunner;
@RequestMapping("list")
public Map<String, Object> list(@RequestParam(value="page",required=false)Integer page,@RequestParam(value="pageSize",required=false)Integer pageSize){
Map<String, Object> resultMap=new HashMap<>();
resultMap.put("errorNo", 0);
resultMap.put("data", classifyService.list(page-1, pageSize));
resultMap.put("total", classifyService.getCount());
return resultMap;
}
/**
* 根据Id查找文章类别
* @param classifyId
* @return
*/
@RequestMapping("findById")
public Map<String, Object> findById(Integer classifyId){
Map<String, Object> resultMap=new HashMap<>();
resultMap.put("errorNo", 0);
resultMap.put("data", classifyService.findById(classifyId));
return resultMap;
}
/**
* 添加或修改文章类别
* @param classify
* @return
*/
Map<String, Object> jsonMap = new LinkedHashMap<String, Object>();
for (Timeline map : maps) {
Map<String, Object> yearMap = (Map<String, Object>) jsonMap.get(map.getYear());
if (null == yearMap) {
yearMap = new LinkedHashMap<String, Object>();
yearMap.put("year", map.getYear());
}
Map<String, Object> monthMap = (Map<String, Object>) yearMap.get("month");
if (null == monthMap) {
monthMap = new LinkedHashMap<String, Object>();
}
List<Map<String, Object>> monthList = (List<Map<String, Object>>) monthMap.get(map.getMonth());
if (null == monthList) {
monthList = new ArrayList<>();
}
monthMap.remove(map.getMonth());
Map<String, Object> obj = new HashMap<>();
obj.put("create_time", DateUtil.formatDate(map.getPublishDate(), "MM月dd日 hh:mm"));
obj.put("content", map.getContent());
monthList.add(obj);
monthMap.put(map.getMonth(), monthList);
yearMap.remove("month");
yearMap.put("month", monthMap);
jsonMap.remove(map.getYear());
jsonMap.put(map.getYear(), yearMap);
}
List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
datas.add((Map<String, Object>) entry.getValue());
}
resultMap.put("datas", datas);
resultMap.put("result", 1);
}else {
resultMap.put("data", "还没有时光轴数据!");
}
return resultMap;
}
}
/**
* 前台页面请求
*
*/
@Controller
@RequestMapping("/foreground")
public class ForegroundController {
@Resource
private ArticleService articleService;
@Resource
private MusicService musicService;
@Resource
private ArticleIndex articleIndex;
@Resource
private UserService userService;
@Resource
private ClassifyService classifyService;
private String downloadImagePath = System.getProperty("user.dir") + "\\src\\main\\webapp"; // 图片下载路径
/**
* 文章专栏
*
* @return
*/
@RequestMapping("/article")
public String article() {
return "/foreground/article";
}
@RequestMapping("/mixed_pic")
public String mixed_pic() {
return "/foreground/mixed_pic";
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
//根据网卡取本机配置的IP
InetAddress inet=null;
try {
inet = InetAddress.getLocalHost();
} catch (Exception e) {
e.printStackTrace();
}
ipAddress= inet.getHostAddress();
}
}
//对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
if(ipAddress.indexOf(",")>0){
ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
}
}
return ipAddress;
}
/**
* 获取IP信息
* @Title: getAdd
* @param request
* @return 参数说明
* @return String 返回类型
* @throws
*/
public static String getAdd(HttpServletRequest request) {
//淘宝IP地址库:http://ip.taobao.com/instructions.php
String add = null;
String ip = getIpAddr(request);
try {
//URL U = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=114.111.166.72");
URL U = new URL("http://ip.taobao.com/service/getIpInfo.php?ip="+ip);
URLConnection connection = U.openConnection();
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String result = "";
String line;
while ((line = in.readLine())!= null){
result += line;
}
in.close();
JSONObject jsonObject = JSONObject.fromObject(result);
Map<String, Object> map = (Map) jsonObject;
String code = String.valueOf(map.get("code"));//0:成功,1:失败。
if("1".equals(code)){//失败
}
/**
* 添加或者修改文章
*
* @param article
* @return
*/
@RequestMapping("/save")
public Map<String, Object> save(Article article, @RequestParam(value = "_mode", required = false) String mode)
throws Exception {
Map<String, Object> resultMap = new HashMap<String, Object>();
if (article.getIsTop() == null) {
article.setIsTop(0);
}
if (article.getIsOriginal() == null) {
article.setIsOriginal(0);
}
if (article.getClick() == null) {
article.setClick(0);
}
if (article.getCommentNum() == null) {
article.setCommentNum(0);
}
if (StringUtil.isEmpty(article.getImageName())) {
article.setImageName("jzytp.JPG");
}
article.setPublishDate(new Date());
article.setContentNoTag(StringUtil.Html2Text(article.getContent()));
articleService.save(article);
if ("add".equals(mode)) {
articleIndex.addIndex(article);
} else if ("edit".equals(mode)) {
articleIndex.updateIndex(article);
}
resultMap.put("errorNo", 0);
resultMap.put("data", 1);
startupRunner.loadData();
return resultMap;
}
/**
* 批量删除文章
*
* @param ids
* @return
*/
@RequestMapping("/delete")
public Map<String, Object> delete(@RequestParam(value = "articleId") String ids) throws Exception {
Map<String, Object> resultMap = new HashMap<String, Object>();
String[] idsStr = ids.split(",");
for (int i = 0; i < idsStr.length; i++) {
a.setIsOriginal(article.getIsOriginal());
a.setIsTop(article.getIsTop());
}
int total = articleList.size();
int totalPage = (int) (total % pageSize == 0 ? total / pageSize : total / pageSize + 1); // 总页数
Integer toIndex = articleList.size() >= Integer.parseInt(page) * pageSize ? Integer.parseInt(page) * pageSize
: articleList.size();
resultMap.put("data", articleList.subList((Integer.parseInt(page) - 1) * pageSize, toIndex));
resultMap.put("q", q);
resultMap.put("totalPage", totalPage);
resultMap.put("total", total);
return resultMap;
}
/**
* 查询音乐
*
* @return
*/
@RequestMapping("/musicList")
@ResponseBody
public Map<String, Object> list() {
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("data", musicService.list(null, 0, 20));
resultMap.put("success", 1);
return resultMap;
}
@RequestMapping(value = "/downloadImage", method = RequestMethod.GET)
public void testDownload(HttpServletResponse res, String fileName) throws Exception {
res.setHeader("content-type", "application/octet-stream");
res.setContentType("application/octet-stream");
String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 获取文件的后缀
res.setHeader("Content-Disposition", "attachment;filename=" + DateUtil.getCurrentDateStr() + suffixName);
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = res.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(new File(downloadImagePath + fileName)));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
return resultMap;
}
@RequestMapping(value = "/downloadImage", method = RequestMethod.GET)
public void testDownload(HttpServletResponse res, String fileName) throws Exception {
res.setHeader("content-type", "application/octet-stream");
res.setContentType("application/octet-stream");
String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 获取文件的后缀
res.setHeader("Content-Disposition", "attachment;filename=" + DateUtil.getCurrentDateStr() + suffixName);
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = res.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(new File(downloadImagePath + fileName)));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("success");
}
}
/**
* 分页查询音乐
* @param music
* @param page
* @param pageSize
* @return
*/
@RequestMapping("/list")
public Map<String, Object> list(Music music,@RequestParam(value="page",required=false)Integer page,@RequestParam(value="pageSize",required=false)Integer pageSize){
Map<String, Object> resultMap=new HashMap<String, Object>();
resultMap.put("errorNo", 0);
resultMap.put("data", musicService.list(music,page-1, pageSize));
resultMap.put("total", musicService.getCount(music));
return resultMap;
}
/**
* 根据ID查找音乐
* @param musicId
* @return
*/
@RequestMapping("/findById")
public Map<String, Object> findById(Integer musicId) {
Map<String, Object> resultMap=new HashMap<String, Object>();
resultMap.put("errorNo", 0);
resultMap.put("data", musicService.findById(musicId));
return resultMap;
}
/**
* 添加或者修改音乐
* @param music
* @return
*/
@RequestMapping("/save")
public Map<String, Object> save(Music music){
Map<String, Object> resultMap=new HashMap<String, Object>();
musicService.save(music);
resultMap.put("errorNo", 0);
resultMap.put("data", 1);
startupRunner.loadData();
return resultMap;
}
/**
String area = String.valueOf(data.get("area"));//
String city = String.valueOf(data.get("city"));//省(自治区或直辖市)
String region = String.valueOf(data.get("region"));//市(县)
add = country+"-"+region+"-"+city;
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return add;
}
}
/**
* QQ登录控制器