diff --git a/src/main/java/cc/iteachyou/cms/common/BaseController.java b/src/main/java/cc/iteachyou/cms/common/BaseController.java index 03e50ed..b5fde03 100644 --- a/src/main/java/cc/iteachyou/cms/common/BaseController.java +++ b/src/main/java/cc/iteachyou/cms/common/BaseController.java @@ -1,110 +1,113 @@ package cc.iteachyou.cms.common; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.Serializable; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import org.springframework.web.bind.annotation.ModelAttribute; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; - -import org.springframework.web.bind.annotation.ModelAttribute; - -import com.alibaba.fastjson.JSONObject; -import com.alibaba.fastjson.serializer.SerializerFeature; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.Serializable; /** - * * controller基类,实现将JSON格式结果的输出方法 */ @SuppressWarnings("unchecked") public class BaseController implements Serializable { - private static final long serialVersionUID = -1206237575319606156L; - - protected HttpServletRequest request; - protected HttpServletResponse response; + private static final long serialVersionUID = -1206237575319606156L; + + protected HttpServletRequest request; + protected HttpServletResponse response; protected HttpSession session; - @ModelAttribute - public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){ + @ModelAttribute + public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; this.session = request.getSession(); - } - - - - /** - * 从Session中取得用户信息 - * @return 用户信息 - */ - public Object getLoginUser() { - HttpSession session = this.getRequest().getSession(); - Object obj = session.getAttribute(Constant.SESSION_USER); - if(null == obj){ - throw new RuntimeException("PlatSysUser为空,登陆出错!"); - } - return obj; - } - - /** - * 取得HttpServletRequest对象 - * @return HttpServletRequest对象 - */ - public HttpServletRequest getRequest() { - return request; - } + } - /** - * 取得Response对象 - * @return - */ - public HttpServletResponse getResponse() { - return response; - } - /** - * 转换字符串为json 格式 - * @param str 普通字符串 - */ - public void outJsonString(String str) { - getResponse().setContentType("text/html;charset=UTF-8"); - outString(str); - } - - /** - * 转换字符串为json 格式,并设置ContentType为text/html - * @param str 普通字符串 - */ - public void outJson(Object obj) { - getResponse().setContentType("text/html;charset=UTF-8"); - outJsonString(JSONObject.toJSONString(obj,SerializerFeature.WriteMapNullValue)); - } + /** + * 从Session中取得用户信息 + * + * @return 用户信息 + */ + public Object getLoginUser() { + HttpSession session = this.getRequest().getSession(); + Object obj = session.getAttribute(Constant.SESSION_USER); + if (null == obj) { + throw new RuntimeException("PlatSysUser为空,登陆出错!"); + } + return obj; + } - /** - * 输出字符串到页面 - * @param str 字符 - */ - public void outString(String str) { - try { - getResponse().setHeader("Cache-Control", "no-cache"); - getResponse().setHeader("Cache-Control", "no-store"); - getResponse().setDateHeader("Expires", 0L); - getResponse().setHeader("Pragma", "no-cache"); - PrintWriter out = getResponse().getWriter(); - out.write(str); - getResponse().flushBuffer(); - } catch (IOException e) { - } - } + /** + * 取得HttpServletRequest对象 + * + * @return HttpServletRequest对象 + */ + public HttpServletRequest getRequest() { + return request; + } - /** - * 输出xml文本串到页面 - * @param xmlStr xml串 - */ - public void outXMLString(String xmlStr) { - getResponse().setContentType("application/xml;charset=UTF-8"); - outString(xmlStr); - } + /** + * 取得Response对象 + * + * @return + */ + public HttpServletResponse getResponse() { + return response; + } + + /** + * 转换字符串为json 格式 + * + * @param str 普通字符串 + */ + public void outJsonString(String str) { + getResponse().setContentType("text/html;charset=UTF-8"); + outString(str); + } + + /** + * 转换字符串为json 格式,并设置ContentType为text/html + * + * @param str 普通字符串 + */ + public void outJson(Object obj) { + getResponse().setContentType("text/html;charset=UTF-8"); + outJsonString(JSONObject.toJSONString(obj, SerializerFeature.WriteMapNullValue)); + } + + /** + * 输出字符串到页面 + * + * @param str 字符 + */ + public void outString(String str) { + try { + getResponse().setHeader("Cache-Control", "no-cache"); + getResponse().setHeader("Cache-Control", "no-store"); + getResponse().setDateHeader("Expires", 0L); + getResponse().setHeader("Pragma", "no-cache"); + PrintWriter out = getResponse().getWriter(); + out.write(str); + getResponse().flushBuffer(); + } catch (IOException e) { + } + } + + /** + * 输出xml文本串到页面 + * + * @param xmlStr xml串 + */ + public void outXMLString(String xmlStr) { + getResponse().setContentType("application/xml;charset=UTF-8"); + outString(xmlStr); + } } diff --git a/src/main/java/cc/iteachyou/cms/controller/FrontController.java b/src/main/java/cc/iteachyou/cms/controller/FrontController.java index 63e153a..04aa0aa 100644 --- a/src/main/java/cc/iteachyou/cms/controller/FrontController.java +++ b/src/main/java/cc/iteachyou/cms/controller/FrontController.java @@ -1,674 +1,646 @@ package cc.iteachyou.cms.controller; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletResponse; - -import cn.hutool.core.util.StrUtil; -import org.apache.commons.io.FileUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; - -import com.wf.captcha.ArithmeticCaptcha; -import com.wf.captcha.utils.CaptchaUtil; - -import cc.iteachyou.cms.common.BaseController; -import cc.iteachyou.cms.common.ExceptionEnum; -import cc.iteachyou.cms.common.ResponseResult; -import cc.iteachyou.cms.common.SearchEntity; -import cc.iteachyou.cms.common.StateCodeEnum; -import cc.iteachyou.cms.entity.Archives; -import cc.iteachyou.cms.entity.Attachment; -import cc.iteachyou.cms.entity.Category; -import cc.iteachyou.cms.entity.Field; -import cc.iteachyou.cms.entity.Form; -import cc.iteachyou.cms.entity.SearchRecord; +import cc.iteachyou.cms.common.*; import cc.iteachyou.cms.entity.System; -import cc.iteachyou.cms.entity.Theme; -import cc.iteachyou.cms.exception.AdminGeneralException; -import cc.iteachyou.cms.exception.CmsException; -import cc.iteachyou.cms.exception.FormParameterException; -import cc.iteachyou.cms.exception.TemplateNotFoundException; -import cc.iteachyou.cms.exception.TemplateReadException; -import cc.iteachyou.cms.exception.TransactionException; -import cc.iteachyou.cms.service.ArchivesService; -import cc.iteachyou.cms.service.AttachmentService; -import cc.iteachyou.cms.service.CategoryService; -import cc.iteachyou.cms.service.FieldService; -import cc.iteachyou.cms.service.FormService; -import cc.iteachyou.cms.service.SearchRecordService; -import cc.iteachyou.cms.service.SystemService; -import cc.iteachyou.cms.service.ThemeService; +import cc.iteachyou.cms.entity.*; +import cc.iteachyou.cms.exception.*; +import cc.iteachyou.cms.service.*; import cc.iteachyou.cms.taglib.ParseEngine; import cc.iteachyou.cms.taglib.utils.URLUtils; import cc.iteachyou.cms.utils.FileConfiguration; import cc.iteachyou.cms.utils.StringUtil; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.StrUtil; +import com.wf.captcha.ArithmeticCaptcha; +import com.wf.captcha.utils.CaptchaUtil; +import org.apache.commons.io.FileUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.text.SimpleDateFormat; +import java.util.*; @Controller @Scope("prototype") @RequestMapping("/") public class FrontController extends BaseController { - @Autowired - private ArchivesService archivesService; - @Autowired - private CategoryService categoryService; - @Autowired - private ThemeService themeService; - @Autowired - private FormService formService; - @Autowired - private FieldService fieldService; - @Autowired - private SearchRecordService searchRecordService; - @Autowired - private FileConfiguration fileConfiguration; - @Autowired - private SystemService systemService; - @Autowired - private AttachmentService attachmentService; - @Autowired - private ParseEngine parseEngine; - - /** - * 首页方法 - * @throws CmsException - * @throws IOException - */ - @RequestMapping("/index") - public void index() throws CmsException, IOException { - System system = systemService.getSystem(); - String staticdir = system.getStaticdir(); - if(staticdir.startsWith("/")) { - staticdir = staticdir.substring(1); - } - //如果为静态浏览,则重写向到静态文件 - if(2 == system.getBrowseType()) { - String url = fileConfiguration.getResourceDir() + staticdir + "/index.html"; - File staticFile = new File(url); - if(!staticFile.exists()) { - throw new TemplateNotFoundException( - ExceptionEnum.HTTP_NOT_FOUND.getCode(), - ExceptionEnum.HTTP_NOT_FOUND.getMessage(), - "当前浏览方式为静态浏览,您所浏览的静态文件不存在,请先静态化网站后再继续。"); - } - response.sendRedirect("/" + staticdir + "/index.html"); - return; - } - - Theme theme = themeService.getCurrentTheme(); - String templatePath = theme.getThemePath() + "/index.html"; - String templateDir = fileConfiguration.getResourceDir() + "templates/"; - - String path = templateDir + templatePath; - File template = new File(path); - if(!template.exists()) { - throw new TemplateNotFoundException( - ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(), - ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(), - "请仔细检查" + template.getAbsolutePath() + "文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); - } - String newHtml = ""; - try { - String html = FileUtils.readFileToString(template, "UTF-8"); - newHtml = parseEngine.parse(html); - outHtml(newHtml); - } catch (IOException e) { - throw new TemplateReadException( - ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(), - ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(), - "请仔细检查模版文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); - } - } - - /** - * 封面方法 - * @param typeid 栏目编码 - * @param visitUrl 访问URL - * @throws CmsException - * @throws IOException - */ - @RequestMapping("cover-{typeid}/{visitUrl}") - public void cover(@PathVariable String typeid - , @PathVariable String visitUrl) throws CmsException, IOException { - System system = systemService.getSystem(); - //查询栏目 - Category category = categoryService.queryCategoryByCode(typeid); - //如果为静态浏览,则重写向到静态文件 - if(2 == system.getBrowseType()) { - String url = URLUtils.parseURL(system, category, "S"); - String fileUrl = fileConfiguration.getResourceDir() + url; - File staticFile = new File(fileUrl); - if(!staticFile.exists()) { - throw new TemplateNotFoundException( - ExceptionEnum.HTTP_NOT_FOUND.getCode(), - ExceptionEnum.HTTP_NOT_FOUND.getMessage(), - "当前浏览方式为静态浏览,您所浏览的静态文件不存在,请先静态化网站后再继续。"); - } - response.sendRedirect(url); - return; - } - - Theme theme = themeService.getCurrentTheme(); - String templateDir = fileConfiguration.getResourceDir() + "templates/"; - if(theme == null) { - - } - if(!visitUrl.startsWith("/")) { - visitUrl = "/" + visitUrl; - } - StringBuffer templatePath = new StringBuffer(); - templatePath.append(theme.getThemePath()); - - if(category.getCatModel() == 1) { - templatePath.append(category.getCoverTemp()); - }else if(category.getCatModel() == 2) { - templatePath.append(category.getListTemp()); - }else if(category.getCatModel() == 3) { - templatePath.append(category.getLinkUrl()); - } - - try { - String path = templateDir + templatePath; - File template = new File(path); - if(!template.exists()) { - throw new TemplateNotFoundException( - ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(), - ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(), - "请仔细检查" + template.getAbsolutePath() + "文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); - } - String newHtml = ""; - String html = FileUtils.readFileToString(template, "UTF-8"); - newHtml = parseEngine.parse(html); - newHtml = parseEngine.parseCategory(newHtml,typeid); - outHtml(newHtml); - } catch (IOException e) { - throw new TemplateReadException( - ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(), - ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(), - "请仔细检查模版文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); - } - } - - /** - * 列表方法 - * @param typeid 栏目编码 - * @param visitUrl 访问URL - * @param pageNum 当前页 - * @param pageSize 分页大小 - * @throws CmsException - * @throws IOException - */ - @RequestMapping("list-{typeid}/{visitUrl}/{pageNum}/{pageSize}") - public void list(@PathVariable String typeid - , @PathVariable String visitUrl - , @PathVariable Integer pageNum - , @PathVariable Integer pageSize) throws CmsException, IOException { - System system = systemService.getSystem(); - String staticdir = system.getStaticdir(); - if(staticdir.startsWith("/")) { - staticdir = staticdir.substring(1); - } - //查询栏目 - Category category = categoryService.queryCategoryByCode(typeid); - //如果为静态浏览,则重写向到静态文件 - if(2 == system.getBrowseType()) { - String url = staticdir + URLUtils.parseFileName(category, pageNum); - String fileUrl = fileConfiguration.getResourceDir() + url; - File staticFile = new File(fileUrl); - if(!staticFile.exists()) { - throw new TemplateNotFoundException( - ExceptionEnum.HTTP_NOT_FOUND.getCode(), - ExceptionEnum.HTTP_NOT_FOUND.getMessage(), - "当前浏览方式为静态浏览,您所浏览的静态文件不存在,请先静态化网站后再继续。"); - } - response.sendRedirect("/" + url); - return; - } - - Theme theme = themeService.getCurrentTheme(); - String templateDir = fileConfiguration.getResourceDir() + "templates/"; - if(theme == null) { - - } - if(!visitUrl.startsWith("/")) { - visitUrl = "/" + visitUrl; - } - StringBuffer templatePath = new StringBuffer(); - templatePath.append(theme.getThemePath()); - - if(category.getCatModel() == 1) { - templatePath.append(category.getCoverTemp()); - }else if(category.getCatModel() == 2) { - templatePath.append(category.getListTemp()); - }else if(category.getCatModel() == 3) { - templatePath.append(category.getLinkUrl()); - } - try { - String path = templateDir + templatePath; - File template = new File(path); - if(!template.exists()) { - throw new TemplateNotFoundException( - ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(), - ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(), - "请仔细检查" + template.getAbsolutePath() + "文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); - } - String newHtml = ""; - String html = FileUtils.readFileToString(template, "UTF-8"); - newHtml = parseEngine.parse(html); - newHtml = parseEngine.parseCategory(newHtml, typeid); - newHtml = parseEngine.parsePageList(newHtml, typeid, pageNum, pageSize); - outHtml(newHtml); - } catch (IOException e) { - throw new TemplateReadException( - ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(), - ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(), - "请仔细检查模版文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); - } - } - - /** - * 文章详情方法 - * @param id 文章ID - * @throws CmsException - * @throws IOException - */ - @RequestMapping("/article/{id}") - public void article(@PathVariable String id) throws CmsException, IOException{ - System system = systemService.getSystem(); - String staticdir = system.getStaticdir(); - if(staticdir.startsWith("/")) { - staticdir = staticdir.substring(1); - } - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); - Archives archives = archivesService.selectByPrimaryKey(id); - //如果为静态浏览,则重写向到静态文件 - if(2 == system.getBrowseType()) { - Category temp = null; - if(!"-1".equals(archives.getCategoryId())) { - temp = categoryService.selectById(archives.getCategoryId()); - }else {//顶级分类走该模版 - temp = new Category(); - temp.setId("-1"); - temp.setCnname("顶级分类"); - } - String catDir = URLUtils.getCategoryDir(temp); - - Date createTime = archives.getCreateTime(); - String dateDir = sdf.format(createTime); - - File staticFile = new File(fileConfiguration.getResourceDir() + staticdir + catDir + "/" + dateDir + "/" + archives.getId() + ".html"); - if(!staticFile.exists()) { - throw new TemplateNotFoundException( - ExceptionEnum.HTTP_NOT_FOUND.getCode(), - ExceptionEnum.HTTP_NOT_FOUND.getMessage(), - "当前浏览方式为静态浏览,您所浏览的静态文件不存在,请先静态化网站后再继续。"); - } - response.sendRedirect("/" + system.getStaticdir() + catDir + "/" + dateDir + "/" + archives.getId() + ".html"); - return; - } - - - StringBuffer templatePath = new StringBuffer(); - Theme theme = themeService.getCurrentTheme(); - String templateDir = fileConfiguration.getResourceDir() + "templates/"; - if(theme == null) { - - } - templatePath.append(theme.getThemePath()); + @Autowired + private ArchivesService archivesService; + @Autowired + private CategoryService categoryService; + @Autowired + private ThemeService themeService; + @Autowired + private FormService formService; + @Autowired + private FieldService fieldService; + @Autowired + private SearchRecordService searchRecordService; + @Autowired + private FileConfiguration fileConfiguration; + @Autowired + private SystemService systemService; + @Autowired + private AttachmentService attachmentService; + @Autowired + private ParseEngine parseEngine; - - Category category = null; - if(!"-1".equals(archives.getCategoryId())) { - category = categoryService.selectById(archives.getCategoryId()); - //构建路径 - templatePath.append("/" + category.getArticleTemp()); - }else {//顶级分类走该模版 - templatePath.append("/article.html"); - category = new Category(); - category.setId("-1"); - category.setCnname("顶级分类"); - } - try { - String path = templateDir + templatePath; - File template = new File(path); - if(!template.exists()) { - throw new TemplateNotFoundException( - ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(), - ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(), - "请仔细检查" + template.getAbsolutePath() + "文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); - } - String newHtml = ""; - String html = FileUtils.readFileToString(template, "UTF-8"); - newHtml = parseEngine.parse(html); - newHtml = parseEngine.parseCategory(newHtml, category.getCode()); - newHtml = parseEngine.parseArticle(newHtml, id); - newHtml = parseEngine.parsePrevAndNext(newHtml, id); - - //更新点击数 - Archives temp = new Archives(); - temp.setId(id); - temp.setClicks(archives.getClicks() + 1); - archivesService.update(temp); - - //输出HTML - outHtml(newHtml); - } catch (IOException e) { - throw new TemplateReadException( - ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(), - ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(), - "请仔细检查模版文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); - } - } + /** + * 首页方法 + * + * @throws CmsException + * @throws IOException + */ + @RequestMapping("/index") + public void index() throws CmsException, IOException { + System system = systemService.getSystem(); + String staticdir = system.getStaticdir(); + if (staticdir.startsWith("/")) { + staticdir = staticdir.substring(1); + } + //如果为静态浏览,则重写向到静态文件 + if (2 == system.getBrowseType()) { + String url = fileConfiguration.getResourceDir() + staticdir + "/index.html"; + File staticFile = new File(url); + if (!staticFile.exists()) { + throw new TemplateNotFoundException( + ExceptionEnum.HTTP_NOT_FOUND.getCode(), + ExceptionEnum.HTTP_NOT_FOUND.getMessage(), + "当前浏览方式为静态浏览,您所浏览的静态文件不存在,请先静态化网站后再继续。"); + } + response.sendRedirect("/" + staticdir + "/index.html"); + return; + } - /** - * 文章详情方法 - * @param id 文章ID - * @throws CmsException - * @throws IOException - */ - @RequestMapping("/clicks/{id}") - public void clicks(@PathVariable String id, HttpServletResponse response) throws CmsException, IOException{ - response.setContentType("text/javascript"); - if(StrUtil.isBlank(id)){ - throw new TemplateReadException( - ExceptionEnum.ARTICLE_NOTFOUND_EXCEPTION.getCode(), - ExceptionEnum.ARTICLE_NOTFOUND_EXCEPTION.getMessage(), - "指定的文章不存在。"); - } - // 查询文章 - Archives archives = archivesService.selectByPrimaryKey(id); - // 对点击量加1 - Archives temp = new Archives(); - temp.setId(id); - temp.setClicks(archives.getClicks() == null ? 1 : archives.getClicks() + 1); - archivesService.update(temp); - // 输出点击量 - response.getWriter().print("document.write(" + archives.getClicks() + ")"); - } - - /** - * 附件下载 - * @param id - * @throws AdminGeneralException - */ - @RequestMapping("/download/{id}") - public void download(@PathVariable String id) throws AdminGeneralException { - try { - System system = systemService.getSystem(); - Attachment attachment = attachmentService.queryAttachmentById(id); - //设置响应头和客户端保存文件名 - response.setCharacterEncoding("utf-8"); - response.setContentType("multipart/form-data"); - response.setHeader("Content-Disposition", "attachment;fileName=" + attachment.getFilename()); - //打开本地文件流 - String filePath = fileConfiguration.getResourceDir() + system.getUploaddir() + "/" + attachment.getFilepath(); - InputStream inputStream = new FileInputStream(filePath); - //激活下载操作 - OutputStream os = response.getOutputStream(); - //循环写入输出流 - byte[] b = new byte[1024]; - int length; - while ((length = inputStream.read(b)) > 0) { - os.write(b, 0, length); - } + Theme theme = themeService.getCurrentTheme(); + String templatePath = theme.getThemePath() + "/index.html"; + String templateDir = fileConfiguration.getResourceDir() + "templates/"; - // 这里主要关闭。 - os.close(); - inputStream.close(); - }catch (Exception e) { - throw new AdminGeneralException( - ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getCode(), - ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getMessage(), - e.getMessage()); - } - } - - /** - * 搜索 - * @param params - * @throws CmsException - */ - @RequestMapping(value = "/search") - public void search(SearchEntity params) throws CmsException { - System system = systemService.getSystem(); - StringBuffer templatePath = new StringBuffer(); - Theme theme = themeService.getCurrentTheme(); - String templateDir = fileConfiguration.getResourceDir() + "templates/"; - if(theme == null) { - - } - templatePath.append(theme.getThemePath()); - templatePath.append("/search.html"); + String path = templateDir + templatePath; + File template = new File(path); + if (!template.exists()) { + throw new TemplateNotFoundException( + ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(), + ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(), + "请仔细检查" + template.getAbsolutePath() + "文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); + } + String newHtml = ""; + try { + String html = FileUtils.readFileToString(template, "UTF-8"); + newHtml = parseEngine.parse(html); + outHtml(newHtml); + } catch (IOException e) { + throw new TemplateReadException( + ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(), + ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(), + "请仔细检查模版文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); + } + } - if(params.getPageNum() == null) - params.setPageNum(1); - if(params.getPageSize() == null) - params.setPageSize(10); - - try { - Map entity = params.getEntity(); - if(entity == null || entity.size() <= 0) { - throw new FormParameterException( - ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), - ExceptionEnum.FORM_PARAMETER_EXCEPTION.getMessage(), - "请仔细检查Form表单参数结构,正确参数格式应该包含entity['keywords']、pageNum、pageSize。"); - } - String keywords = ""; - if(entity.containsKey("keywords")) { - keywords = params.getEntity().get("keywords").toString(); + /** + * 封面方法 + * + * @param typeid 栏目编码 + * @param visitUrl 访问URL + * @throws CmsException + * @throws IOException + */ + @RequestMapping("cover-{typeid}/{visitUrl}") + public void cover(@PathVariable String typeid + , @PathVariable String visitUrl) throws CmsException, IOException { + System system = systemService.getSystem(); + //查询栏目 + Category category = categoryService.queryCategoryByCode(typeid); + //如果为静态浏览,则重写向到静态文件 + if (2 == system.getBrowseType()) { + String url = URLUtils.parseURL(system, category, "S"); + String fileUrl = fileConfiguration.getResourceDir() + url; + File staticFile = new File(fileUrl); + if (!staticFile.exists()) { + throw new TemplateNotFoundException( + ExceptionEnum.HTTP_NOT_FOUND.getCode(), + ExceptionEnum.HTTP_NOT_FOUND.getMessage(), + "当前浏览方式为静态浏览,您所浏览的静态文件不存在,请先静态化网站后再继续。"); + } + response.sendRedirect(url); + return; + } - if(keywords.getBytes("GBK").length < 3) { - throw new FormParameterException( - ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), - ExceptionEnum.FORM_PARAMETER_EXCEPTION.getMessage(), - "搜索关键字不能少于5个字符,请重新输入后进行搜索。"); - } - } - - String path = templateDir + templatePath; - File template = new File(path); - if(!template.exists()) { - throw new TemplateNotFoundException( - ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(), - ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(), - "请仔细检查" + template.getAbsolutePath() + "文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); - } - String newHtml = ""; - String html = FileUtils.readFileToString(template, "UTF-8"); - //如果为静态浏览,则生成页面 - if(2 == system.getBrowseType()) { - newHtml = parseEngine.generate(html); - }else { - newHtml = parseEngine.parse(html); - } - newHtml = parseEngine.parsePageList(newHtml, params); - - //记录搜索关键词 - SearchRecord sr = new SearchRecord(); - sr.setId(IdUtil.getSnowflakeNextIdStr()); - sr.setKeywords(keywords); - sr.setCreateTime(new Date()); - searchRecordService.add(sr); - - //输出HTML - outHtml(newHtml); - } catch (IOException e) { - throw new TemplateReadException( - ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(), - ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(), - "请仔细检查模版文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); - } - } - - /** - * 前端投稿 - * @param params - * @return - * @throws CmsException - */ - @ResponseBody - @RequestMapping(value = "/input",method = RequestMethod.POST) - public ResponseResult input(@RequestParam Map params) throws CmsException { - // 验证码校验 - if(!params.containsKey("captcha") || StringUtil.isBlank(params.get("captcha"))) { - return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "缺少验证码参数,请添加该参数后重试。"); - } - if(!CaptchaUtil.ver(params.get("captcha").toString(), request)) { - return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "验证码输入错误或已超时,请仔细检查后再试。"); - } - if(!params.containsKey("typeid") || StringUtil.isBlank(params.get("typeid"))) { - return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "缺少[typeid]参数,请添加该参数后重试。"); - } - if(!params.containsKey("formkey") || StringUtil.isBlank(params.get("formkey"))) { - return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "缺少[formkey]参数,请添加该参数后重试。"); - } - - // 清除验证码 - CaptchaUtil.clear(request); - - String typeid = params.get("typeid").toString(); - String formkey = params.get("formkey").toString(); - - Category categoryWithBLOBs = categoryService.queryCategoryByCode(typeid); - if(categoryWithBLOBs == null) { - return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "栏目不存在,请仔细检查[typeid]参数是否有误,核实后重试。"); - } - - if(categoryWithBLOBs.getIsInput() != 1) { - return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "栏目不允许投稿,请仔细检查栏目的详情并设置是否允许投稿为是后重试。"); - } - - Form form = formService.queryFormByCode(formkey); - if(form == null) { - return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "表单模型不存在,请仔细检查[formkey]参数是否有误,核实后重试。"); - } - - Archives archives = new Archives(); - archives.setId(IdUtil.getSnowflakeNextIdStr()); - archives.setCreateTime(new Date()); - archives.setStatus(1);//未发布 - - archives.setTitle(StringUtil.isBlank(params.get("title")) ? "" : params.get("title").toString()); - archives.setTag(StringUtil.isBlank(params.get("tag")) ? "" : params.get("tag").toString()); - archives.setCategoryId(categoryWithBLOBs.getId()); - archives.setCategoryIds(categoryWithBLOBs.getCatSeq()); - archives.setImagePath(StringUtil.isBlank(params.get("imagePath")) ? "" : params.get("imagePath").toString()); - archives.setWeight(StringUtil.isBlank(params.get("weight")) ? 0 : Integer.parseInt(params.get("weight").toString())); - archives.setClicks(StringUtil.isBlank(params.get("clicks")) ? 0 : Integer.parseInt(params.get("clicks").toString())); - archives.setDescription(StringUtil.isBlank(params.get("description")) ? "" : params.get("description").toString()); - archives.setComment(StringUtil.isBlank(params.get("comment")) ? 0 : Integer.parseInt(params.get("comment").toString())); - archives.setSubscribe(StringUtil.isBlank(params.get("subscribe")) ? 0 : Integer.parseInt(params.get("subscribe").toString())); - - - List fields = fieldService.queryFieldByFormId(form.getId()); - Map additional = new LinkedHashMap(); - additional.put("id", IdUtil.getSnowflakeNextIdStr()); - additional.put("aid", archives.getId()); - for(int i = 0;i < fields.size();i++) { - Field field = fields.get(i); - additional.put(field.getFieldName(), params.get(field.getFieldName())); - //用MAP接收参数,checkbox需要特殊处理 - if("checkbox".equals(field.getDataType())) { - String[] arr = request.getParameterValues(field.getFieldName()); - if(arr != null && arr.length > 0) { - StringBuffer checkboxVal = new StringBuffer(); - for (String string : arr) { - checkboxVal.append(string + ","); - } - additional.put(field.getFieldName(), checkboxVal.substring(0, checkboxVal.length() - 1)); - } - } - } - String tableName = "system_" + form.getTableName(); - - try { - archivesService.save(archives,tableName,additional); - } catch (TransactionException e) { - return ResponseResult.Factory.newInstance(Boolean.TRUE, ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getCode(), null, ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getMessage()); - } - - return ResponseResult.Factory.newInstance(Boolean.TRUE, StateCodeEnum.HTTP_SUCCESS.getCode(), null, StateCodeEnum.HTTP_SUCCESS.getDescription()); - } - - @RequestMapping("sitemap.xml") - public void sitemap() throws IOException { - System system = systemService.getSystem(); - - Map entity = new HashMap<>(); - entity.put("isShow", "1"); - entity.put("parentId", "-1"); - List list = categoryService.getTreeList(entity); - - StringBuilder xml = new StringBuilder(); - - xml.append("") - .append(""); - xml.append(""); - xml.append("" + system.getWebsite() + ""); - xml.append("" + 1.0 + ""); - xml.append("" + DateUtil.format(new Date(), "yyyy-MM-dd") + ""); - xml.append("always"); - xml.append(""); - - URLUtils.parseSiteMap(system, archivesService, list, xml); - - xml.append(""); - HttpServletResponse httpServletResponse = getResponse(); - httpServletResponse.setCharacterEncoding("UTF-8"); - httpServletResponse.setContentType("text/xml;charset=utf-8"); - httpServletResponse.setHeader("Cache-Control", "no-cache"); - httpServletResponse.setHeader("Cache-Control", "no-store"); - httpServletResponse.setHeader("Pragma", "no-cache"); - httpServletResponse.setDateHeader("Expires", 0L); - httpServletResponse.getWriter().write(xml.toString()); - httpServletResponse.flushBuffer(); - } - - // 产生验证码 - @RequestMapping("getKaptcha") - public void getKaptcha() throws IOException { - ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48); + Theme theme = themeService.getCurrentTheme(); + String templateDir = fileConfiguration.getResourceDir() + "templates/"; + if (theme == null) { + + } + if (!visitUrl.startsWith("/")) { + visitUrl = "/" + visitUrl; + } + StringBuffer templatePath = new StringBuffer(); + templatePath.append(theme.getThemePath()); + + if (category.getCatModel() == 1) { + templatePath.append(category.getCoverTemp()); + } else if (category.getCatModel() == 2) { + templatePath.append(category.getListTemp()); + } else if (category.getCatModel() == 3) { + templatePath.append(category.getLinkUrl()); + } + + try { + String path = templateDir + templatePath; + File template = new File(path); + if (!template.exists()) { + throw new TemplateNotFoundException( + ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(), + ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(), + "请仔细检查" + template.getAbsolutePath() + "文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); + } + String newHtml = ""; + String html = FileUtils.readFileToString(template, "UTF-8"); + newHtml = parseEngine.parse(html); + newHtml = parseEngine.parseCategory(newHtml, typeid); + outHtml(newHtml); + } catch (IOException e) { + throw new TemplateReadException( + ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(), + ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(), + "请仔细检查模版文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); + } + } + + /** + * 列表方法 + * + * @param typeid 栏目编码 + * @param visitUrl 访问URL + * @param pageNum 当前页 + * @param pageSize 分页大小 + * @throws CmsException + * @throws IOException + */ + @RequestMapping("list-{typeid}/{visitUrl}/{pageNum}/{pageSize}") + public void list(@PathVariable String typeid + , @PathVariable String visitUrl + , @PathVariable Integer pageNum + , @PathVariable Integer pageSize) throws CmsException, IOException { + System system = systemService.getSystem(); + String staticdir = system.getStaticdir(); + if (staticdir.startsWith("/")) { + staticdir = staticdir.substring(1); + } + //查询栏目 + Category category = categoryService.queryCategoryByCode(typeid); + //如果为静态浏览,则重写向到静态文件 + if (2 == system.getBrowseType()) { + String url = staticdir + URLUtils.parseFileName(category, pageNum); + String fileUrl = fileConfiguration.getResourceDir() + url; + File staticFile = new File(fileUrl); + if (!staticFile.exists()) { + throw new TemplateNotFoundException( + ExceptionEnum.HTTP_NOT_FOUND.getCode(), + ExceptionEnum.HTTP_NOT_FOUND.getMessage(), + "当前浏览方式为静态浏览,您所浏览的静态文件不存在,请先静态化网站后再继续。"); + } + response.sendRedirect("/" + url); + return; + } + + Theme theme = themeService.getCurrentTheme(); + String templateDir = fileConfiguration.getResourceDir() + "templates/"; + if (theme == null) { + + } + if (!visitUrl.startsWith("/")) { + visitUrl = "/" + visitUrl; + } + StringBuffer templatePath = new StringBuffer(); + templatePath.append(theme.getThemePath()); + + if (category.getCatModel() == 1) { + templatePath.append(category.getCoverTemp()); + } else if (category.getCatModel() == 2) { + templatePath.append(category.getListTemp()); + } else if (category.getCatModel() == 3) { + templatePath.append(category.getLinkUrl()); + } + try { + String path = templateDir + templatePath; + File template = new File(path); + if (!template.exists()) { + throw new TemplateNotFoundException( + ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(), + ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(), + "请仔细检查" + template.getAbsolutePath() + "文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); + } + String newHtml = ""; + String html = FileUtils.readFileToString(template, "UTF-8"); + newHtml = parseEngine.parse(html); + newHtml = parseEngine.parseCategory(newHtml, typeid); + newHtml = parseEngine.parsePageList(newHtml, typeid, pageNum, pageSize); + outHtml(newHtml); + } catch (IOException e) { + throw new TemplateReadException( + ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(), + ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(), + "请仔细检查模版文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); + } + } + + /** + * 文章详情方法 + * + * @param id 文章ID + * @throws CmsException + * @throws IOException + */ + @RequestMapping("/article/{id}") + public void article(@PathVariable String id) throws CmsException, IOException { + System system = systemService.getSystem(); + String staticdir = system.getStaticdir(); + if (staticdir.startsWith("/")) { + staticdir = staticdir.substring(1); + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + Archives archives = archivesService.selectByPrimaryKey(id); + //如果为静态浏览,则重写向到静态文件 + if (2 == system.getBrowseType()) { + Category temp = null; + if (!"-1".equals(archives.getCategoryId())) { + temp = categoryService.selectById(archives.getCategoryId()); + } else {//顶级分类走该模版 + temp = new Category(); + temp.setId("-1"); + temp.setCnname("顶级分类"); + } + String catDir = URLUtils.getCategoryDir(temp); + + Date createTime = archives.getCreateTime(); + String dateDir = sdf.format(createTime); + + File staticFile = new File(fileConfiguration.getResourceDir() + staticdir + catDir + "/" + dateDir + "/" + archives.getId() + ".html"); + if (!staticFile.exists()) { + throw new TemplateNotFoundException( + ExceptionEnum.HTTP_NOT_FOUND.getCode(), + ExceptionEnum.HTTP_NOT_FOUND.getMessage(), + "当前浏览方式为静态浏览,您所浏览的静态文件不存在,请先静态化网站后再继续。"); + } + response.sendRedirect("/" + system.getStaticdir() + catDir + "/" + dateDir + "/" + archives.getId() + ".html"); + return; + } + + + StringBuffer templatePath = new StringBuffer(); + Theme theme = themeService.getCurrentTheme(); + String templateDir = fileConfiguration.getResourceDir() + "templates/"; + if (theme == null) { + + } + templatePath.append(theme.getThemePath()); + + + Category category = null; + if (!"-1".equals(archives.getCategoryId())) { + category = categoryService.selectById(archives.getCategoryId()); + //构建路径 + templatePath.append("/" + category.getArticleTemp()); + } else {//顶级分类走该模版 + templatePath.append("/article.html"); + category = new Category(); + category.setId("-1"); + category.setCnname("顶级分类"); + } + try { + String path = templateDir + templatePath; + File template = new File(path); + if (!template.exists()) { + throw new TemplateNotFoundException( + ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(), + ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(), + "请仔细检查" + template.getAbsolutePath() + "文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); + } + String newHtml = ""; + String html = FileUtils.readFileToString(template, "UTF-8"); + newHtml = parseEngine.parse(html); + newHtml = parseEngine.parseCategory(newHtml, category.getCode()); + newHtml = parseEngine.parseArticle(newHtml, id); + newHtml = parseEngine.parsePrevAndNext(newHtml, id); + + //更新点击数 + Archives temp = new Archives(); + temp.setId(id); + temp.setClicks(archives.getClicks() + 1); + archivesService.update(temp); + + //输出HTML + outHtml(newHtml); + } catch (IOException e) { + throw new TemplateReadException( + ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(), + ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(), + "请仔细检查模版文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); + } + } + + /** + * 文章详情方法 + * + * @param id 文章ID + * @throws CmsException + * @throws IOException + */ + @RequestMapping("/clicks/{id}") + public void clicks(@PathVariable String id, HttpServletResponse response) throws CmsException, IOException { + response.setContentType("text/javascript"); + if (StrUtil.isBlank(id)) { + throw new TemplateReadException( + ExceptionEnum.ARTICLE_NOTFOUND_EXCEPTION.getCode(), + ExceptionEnum.ARTICLE_NOTFOUND_EXCEPTION.getMessage(), + "指定的文章不存在。"); + } + // 查询文章 + Archives archives = archivesService.selectByPrimaryKey(id); + // 对点击量加1 + Archives temp = new Archives(); + temp.setId(id); + temp.setClicks(archives.getClicks() == null ? 1 : archives.getClicks() + 1); + archivesService.update(temp); + // 输出点击量 + response.getWriter().print("document.write(" + archives.getClicks() + ")"); + } + + /** + * 附件下载 + * + * @param id + * @throws AdminGeneralException + */ + @RequestMapping("/download/{id}") + public void download(@PathVariable String id) throws AdminGeneralException { + try { + System system = systemService.getSystem(); + Attachment attachment = attachmentService.queryAttachmentById(id); + //设置响应头和客户端保存文件名 + response.setCharacterEncoding("utf-8"); + response.setContentType("multipart/form-data"); + response.setHeader("Content-Disposition", "attachment;fileName=" + attachment.getFilename()); + //打开本地文件流 + String filePath = fileConfiguration.getResourceDir() + system.getUploaddir() + "/" + attachment.getFilepath(); + InputStream inputStream = new FileInputStream(filePath); + //激活下载操作 + OutputStream os = response.getOutputStream(); + //循环写入输出流 + byte[] b = new byte[1024]; + int length; + while ((length = inputStream.read(b)) > 0) { + os.write(b, 0, length); + } + + // 这里主要关闭。 + os.close(); + inputStream.close(); + } catch (Exception e) { + throw new AdminGeneralException( + ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getCode(), + ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getMessage(), + e.getMessage()); + } + } + + /** + * 搜索 + * + * @param params + * @throws CmsException + */ + @RequestMapping(value = "/search") + public void search(SearchEntity params) throws CmsException { + System system = systemService.getSystem(); + StringBuffer templatePath = new StringBuffer(); + Theme theme = themeService.getCurrentTheme(); + String templateDir = fileConfiguration.getResourceDir() + "templates/"; + if (theme == null) { + + } + templatePath.append(theme.getThemePath()); + templatePath.append("/search.html"); + + if (params.getPageNum() == null) + params.setPageNum(1); + if (params.getPageSize() == null) + params.setPageSize(10); + + try { + Map entity = params.getEntity(); + if (entity == null || entity.size() <= 0) { + throw new FormParameterException( + ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), + ExceptionEnum.FORM_PARAMETER_EXCEPTION.getMessage(), + "请仔细检查Form表单参数结构,正确参数格式应该包含entity['keywords']、pageNum、pageSize。"); + } + String keywords = ""; + if (entity.containsKey("keywords")) { + keywords = params.getEntity().get("keywords").toString(); + + if (keywords.getBytes("GBK").length < 3) { + throw new FormParameterException( + ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), + ExceptionEnum.FORM_PARAMETER_EXCEPTION.getMessage(), + "搜索关键字不能少于5个字符,请重新输入后进行搜索。"); + } + } + + String path = templateDir + templatePath; + File template = new File(path); + if (!template.exists()) { + throw new TemplateNotFoundException( + ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(), + ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(), + "请仔细检查" + template.getAbsolutePath() + "文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); + } + String newHtml = ""; + String html = FileUtils.readFileToString(template, "UTF-8"); + //如果为静态浏览,则生成页面 + if (2 == system.getBrowseType()) { + newHtml = parseEngine.generate(html); + } else { + newHtml = parseEngine.parse(html); + } + newHtml = parseEngine.parsePageList(newHtml, params); + + //记录搜索关键词 + SearchRecord sr = new SearchRecord(); + sr.setId(IdUtil.getSnowflakeNextIdStr()); + sr.setKeywords(keywords); + sr.setCreateTime(new Date()); + searchRecordService.add(sr); + + //输出HTML + outHtml(newHtml); + } catch (IOException e) { + throw new TemplateReadException( + ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(), + ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(), + "请仔细检查模版文件,或检查application.yml中的资源目录配置项(web.resource-path)。"); + } + } + + /** + * 前端投稿 + * + * @param params + * @return + * @throws CmsException + */ + @ResponseBody + @RequestMapping(value = "/input", method = RequestMethod.POST) + public ResponseResult input(@RequestParam Map params) throws CmsException { + // 验证码校验 + if (!params.containsKey("captcha") || StringUtil.isBlank(params.get("captcha"))) { + return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "缺少验证码参数,请添加该参数后重试。"); + } + if (!CaptchaUtil.ver(params.get("captcha").toString(), request)) { + return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "验证码输入错误或已超时,请仔细检查后再试。"); + } + if (!params.containsKey("typeid") || StringUtil.isBlank(params.get("typeid"))) { + return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "缺少[typeid]参数,请添加该参数后重试。"); + } + if (!params.containsKey("formkey") || StringUtil.isBlank(params.get("formkey"))) { + return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "缺少[formkey]参数,请添加该参数后重试。"); + } + + // 清除验证码 + CaptchaUtil.clear(request); + + String typeid = params.get("typeid").toString(); + String formkey = params.get("formkey").toString(); + + Category categoryWithBLOBs = categoryService.queryCategoryByCode(typeid); + if (categoryWithBLOBs == null) { + return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "栏目不存在,请仔细检查[typeid]参数是否有误,核实后重试。"); + } + + if (categoryWithBLOBs.getIsInput() != 1) { + return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "栏目不允许投稿,请仔细检查栏目的详情并设置是否允许投稿为是后重试。"); + } + + Form form = formService.queryFormByCode(formkey); + if (form == null) { + return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "表单模型不存在,请仔细检查[formkey]参数是否有误,核实后重试。"); + } + + Archives archives = new Archives(); + archives.setId(IdUtil.getSnowflakeNextIdStr()); + archives.setCreateTime(new Date()); + archives.setStatus(1);//未发布 + + archives.setTitle(StringUtil.isBlank(params.get("title")) ? "" : params.get("title").toString()); + archives.setTag(StringUtil.isBlank(params.get("tag")) ? "" : params.get("tag").toString()); + archives.setCategoryId(categoryWithBLOBs.getId()); + archives.setCategoryIds(categoryWithBLOBs.getCatSeq()); + archives.setImagePath(StringUtil.isBlank(params.get("imagePath")) ? "" : params.get("imagePath").toString()); + archives.setWeight(StringUtil.isBlank(params.get("weight")) ? 0 : Integer.parseInt(params.get("weight").toString())); + archives.setClicks(StringUtil.isBlank(params.get("clicks")) ? 0 : Integer.parseInt(params.get("clicks").toString())); + archives.setDescription(StringUtil.isBlank(params.get("description")) ? "" : params.get("description").toString()); + archives.setComment(StringUtil.isBlank(params.get("comment")) ? 0 : Integer.parseInt(params.get("comment").toString())); + archives.setSubscribe(StringUtil.isBlank(params.get("subscribe")) ? 0 : Integer.parseInt(params.get("subscribe").toString())); + + + List fields = fieldService.queryFieldByFormId(form.getId()); + Map additional = new LinkedHashMap(); + additional.put("id", IdUtil.getSnowflakeNextIdStr()); + additional.put("aid", archives.getId()); + for (int i = 0; i < fields.size(); i++) { + Field field = fields.get(i); + additional.put(field.getFieldName(), params.get(field.getFieldName())); + //用MAP接收参数,checkbox需要特殊处理 + if ("checkbox".equals(field.getDataType())) { + String[] arr = request.getParameterValues(field.getFieldName()); + if (arr != null && arr.length > 0) { + StringBuffer checkboxVal = new StringBuffer(); + for (String string : arr) { + checkboxVal.append(string + ","); + } + additional.put(field.getFieldName(), checkboxVal.substring(0, checkboxVal.length() - 1)); + } + } + } + String tableName = "system_" + form.getTableName(); + + try { + archivesService.save(archives, tableName, additional); + } catch (TransactionException e) { + return ResponseResult.Factory.newInstance(Boolean.TRUE, ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getCode(), null, ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getMessage()); + } + + return ResponseResult.Factory.newInstance(Boolean.TRUE, StateCodeEnum.HTTP_SUCCESS.getCode(), null, StateCodeEnum.HTTP_SUCCESS.getDescription()); + } + + @RequestMapping("sitemap.xml") + public void sitemap() throws IOException { + System system = systemService.getSystem(); + + Map entity = new HashMap<>(); + entity.put("isShow", "1"); + entity.put("parentId", "-1"); + List list = categoryService.getTreeList(entity); + + StringBuilder xml = new StringBuilder(); + + xml.append("") + .append(""); + xml.append(""); + xml.append("" + system.getWebsite() + ""); + xml.append("" + 1.0 + ""); + xml.append("" + DateUtil.format(new Date(), "yyyy-MM-dd") + ""); + xml.append("always"); + xml.append(""); + + URLUtils.parseSiteMap(system, archivesService, list, xml); + + xml.append(""); + HttpServletResponse httpServletResponse = getResponse(); + httpServletResponse.setCharacterEncoding("UTF-8"); + httpServletResponse.setContentType("text/xml;charset=utf-8"); + httpServletResponse.setHeader("Cache-Control", "no-cache"); + httpServletResponse.setHeader("Cache-Control", "no-store"); + httpServletResponse.setHeader("Pragma", "no-cache"); + httpServletResponse.setDateHeader("Expires", 0L); + httpServletResponse.getWriter().write(xml.toString()); + httpServletResponse.flushBuffer(); + } + + // 产生验证码 + @RequestMapping("getKaptcha") + public void getKaptcha() throws IOException { + ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48); captcha.getArithmeticString(); // 获取运算的公式:3+2=? captcha.text(); // 获取运算的结果:5 - CaptchaUtil.out(captcha, request, response); - } - - /** - * 输出字符串到页面 - * @param html 字符 - */ - public void outHtml(String html) { - try { - HttpServletResponse httpServletResponse = getResponse(); - httpServletResponse.setCharacterEncoding("UTF-8"); - httpServletResponse.setContentType("text/html;charset=utf-8"); - httpServletResponse.setHeader("Cache-Control", "no-cache"); - httpServletResponse.setHeader("Cache-Control", "no-store"); - httpServletResponse.setHeader("Pragma", "no-cache"); - httpServletResponse.setDateHeader("Expires", 0L); - httpServletResponse.getWriter().write(html); - httpServletResponse.flushBuffer(); - } catch (IOException e) { - - } - } + CaptchaUtil.out(captcha, request, response); + } + + /** + * 输出字符串到页面 + * + * @param html 字符 + */ + public void outHtml(String html) { + try { + HttpServletResponse httpServletResponse = getResponse(); + httpServletResponse.setCharacterEncoding("UTF-8"); + httpServletResponse.setContentType("text/html;charset=utf-8"); + httpServletResponse.setHeader("Cache-Control", "no-cache"); + httpServletResponse.setHeader("Cache-Control", "no-store"); + httpServletResponse.setHeader("Pragma", "no-cache"); + httpServletResponse.setHeader("Cache-Control", "public"); + httpServletResponse.setDateHeader("Expires", 0L); + httpServletResponse.getWriter().write(html); + httpServletResponse.flushBuffer(); + } catch (IOException e) { + + } + } }