由于前端一些控件的影响,所以自己就在后端获取ckeditor的textarea的值
Java去除html代码中含有的html、js、css标签,获取文字内容
前端
HTML:
<input id="errorMsg" th:value="${errorMsg}" class="hidden" readonly="readonly"></input>
JS:
$(document).ready(function () {
//错误提示
if($('#errorMsg').val().length>0)
layer.msg($('#errorMsg').val(), function(){
});
}
后端
Controller层:
@RequestMapping(value="/save", method = {RequestMethod.POST})
public String saveMilestone(Model model,@ModelAttribute("thisMilestone") @Valid Milestone thisMilestone, HttpServletRequest request) {
if(milestoneService.ckEdit(request)){
model.addAttribute("errorMsg", "描述最少500字");
return "add";
}else{
this.milestoneService.saveMilestone(thisMilestone);
return "redirect:/list";
}
}
Service层:
@Override
public boolean ckEdit(HttpServletRequest request) {
String description = request.getParameter("description");
DelTagsUtil text = new DelTagsUtil();
description = text.getTextFromHtml(description);
if(description.length()>10){
return false;
}else{
return true;
}
}
工具类:
package org.wts.projectadmin.common;
/**
* 去除页面代码里的HTML标签
* Created by MengMeng on 2018/8/3
*/
public class DelTagsUtil {
public static String delHtmlTags(String htmlStr) {
//定义script的正则表达式,去除js可以防止注入
String scriptRegex="<script[^>]*?>[\\s\\S]*?<\\/script>";
//定义style的正则表达式,去除style样式,防止css代码过多时只截取到css样式代码
String styleRegex="<style[^>]*?>[\\s\\S]*?<\\/style>";
//定义HTML标签的正则表达式,去除标签,只提取文字内容
String htmlRegex="<[^>]+>";
//定义空格,回车,换行符,制表符
String spaceRegex = "\\s*|\t|\r|\n";
htmlStr = htmlStr.replaceAll(scriptRegex, "");
htmlStr = htmlStr.replaceAll(styleRegex, "");
htmlStr = htmlStr.replaceAll(htmlRegex, "");
htmlStr = htmlStr.replaceAll(spaceRegex, "");
return htmlStr.trim(); // 返回文本字符串
}
public static String getTextFromHtml(String htmlStr){
htmlStr = delHtmlTags(htmlStr);
htmlStr = htmlStr.replaceAll(" ","");
return htmlStr;
}
}
相关学习链接: