Java Code Examples for org.springframework.web.util.HtmlUtils

The following examples show how to use org.springframework.web.util.HtmlUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: SpringSecurity-JWT-Vue-Deom   Source File: JwtLoginFilter.java    License: MIT License 6 votes vote down vote up
/**
 * 提取用户账号密码进行验证
 * */
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
    // 判断是否要抛出 登陆请求过快的异常
    loginCountService.judgeLoginCount(httpServletRequest);
    // 获取 User 对象
    // readValue 第一个参数 输入流,第二个参数 要转换的对象
    User user = new ObjectMapper().readValue(httpServletRequest.getInputStream(), User.class);
    // 验证码验证
    verifyCodeService.verify(httpServletRequest.getSession().getId(), user.getVerifyCode());
    // 对 html 标签进行转义,防止 XSS 攻击
    String username = user.getUsername();
    username = HtmlUtils.htmlEscape(username);
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
            username,
            user.getPassword(),
            user.getAuthorities()
    );
    // 添加验证的附加信息
    // 包括验证码信息和是否记住我
    token.setDetails(new LoginDetails(user.getRememberMe(), user.getVerifyCode()));
    // 进行登陆验证
    return getAuthenticationManager().authenticate(token);
}
 
Example 2
Source Project: MyCommunity   Source File: CommentServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
public int addComment(Comment comment) {
    if (comment == null) {
        throw new IllegalArgumentException("参数不能为空!");
    }

    comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
    comment.setContent(sensitiveFilter.filter(comment.getContent()));
    comment.setStatus(0);
    comment.setCreateTime(new Date());
    int rows = commentMapper.insertComment(comment);

    // 更新帖子的评论数
    if (comment.getEntityType() == Const.entityType.ENTITY_TYPE_POST) {
        int count  = commentMapper.selectCountByEntity(comment.getEntityType(), comment.getEntityId());
        discussPostMapper.updateCommentCount(comment.getEntityId(), count);
    }

    return rows;
}
 
Example 3
protected TableCell buildNote(PreferenceGroup prefGroup, boolean isEditable, UserContext user){
	TableCell cell = null;
	if (prefGroup instanceof Class_) {
		Class_ c = (Class_) prefGroup;
		if (c.getNotes() != null && !c.getNotes().trim().isEmpty()) {
			if (CommonValues.NoteAsShortText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
				String note = (c.getNotes().length() <= 20 ? c.getNotes() : c.getNotes().substring(0, 20) + "...");
				cell = initNormalCell(note.replaceAll("\n","<br>"), isEditable);
    			cell.setAlign("left");
			} else if (CommonValues.NoteAsFullText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
				cell = initNormalCell(c.getNotes().replaceAll("\n","<br>"), isEditable);
    			cell.setAlign("left");
			} else {
	    		cell = initNormalCell("<IMG border='0' alt='" + MSG.altHasNoteToMgr() + "' title='" + HtmlUtils.htmlEscape(c.getNotes()) + "' align='absmiddle' src='images/note.png'>", isEditable);
	    		cell.setAlign("center");
			}
		} else { 
    		cell = this.initNormalCell("&nbsp;" ,isEditable);
    	}
	} else { 
		cell = this.initNormalCell("&nbsp;" ,isEditable);
	}
    return(cell);
}
 
Example 4
Source Project: feiqu-opensource   Source File: StringEscapeEditor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (text == null) {
            setValue(null);
        } else {
            String value = text;
            if (escapeHTML) {
                value = HtmlUtils.htmlEscape(value);
//                logger.info("escapeHTML > value:" + value);
            }
            if (escapeJavaScript) {
                value = StringEscapeUtils.escapeJavaScript(value);
//                logger.info("escapeJavaScript > value:" + value);
            }
            setValue(value);
        }
    }
 
Example 5
/**
 * 更新ApiDocInterface页面
 */
@RequestMapping("/debug/{apiDocInterfaceId}")
public Object debug(@PathVariable Long apiDocInterfaceId, Model model) {
    ApiDocInterface apiDocInterface = apiDocInterfaceService.selectByPrimaryKey(apiDocInterfaceId);
    apiDocInterface.setTrueexam(HtmlUtils.htmlUnescape(apiDocInterface.getTrueexam()));
    apiDocInterface.setFalseexam(HtmlUtils.htmlUnescape(apiDocInterface.getFalseexam()));
    model.addAttribute("apiDocInterface", JSON.toJSON(apiDocInterface));
    ApiDocModuleExample example = new ApiDocModuleExample();
    example.createCriteria().andProjectIdEqualTo(apiDocInterface.getProjectid());
    List<ApiDocModule> modules = apiDocModuleService.selectByExample(example);
    List<KeyValue> keyValues = Lists.newArrayList();
    if(CollectionUtil.isNotEmpty(modules)){
        modules.forEach(module -> {
            KeyValue keyValue = new KeyValue(module.getId().toString(),module.getModuleName());
            keyValues.add(keyValue);
        });
    }
    model.addAttribute("modules", keyValues);
    model.addAttribute("apiDocInterfaceId", apiDocInterfaceId);
    return "/apiDocInterface/debug.html";
}
 
Example 6
Source Project: feiqu-opensource   Source File: ArticleController.java    License: Apache License 2.0 6 votes vote down vote up
@GetMapping("caiji")
public void caiji(){
    String result = HttpUtil.get("http://hd.zt.raiyi.com/v9/private/682265b8574104c64c262c1b3f7a3eb771f01e126687b1a14b048025a9b639918ae7d834f2c3158c646add7a52ab8e78/weibo/theme/list?appCode=other_browser&tag=hot");
    AllDataRes allDataRes = JSON.parseObject(result, AllDataRes.class);
    List<SingleData> data = allDataRes.getData();
    for(SingleData singleData : data){
        String content = singleData.getContent();
        String html = singleData.getHtml();
        String htmlUn = HtmlUtils.htmlUnescape(html);
        Article article = new Article();
        article.setArticleTitle(content);
        article.setCreateTime(new Date());
        article.setArticleContent(htmlUn);
        article.setUserId(22);
        articleService.insert(article);
    }

}
 
Example 7
Source Project: feiqu-opensource   Source File: JobController.java    License: Apache License 2.0 6 votes vote down vote up
@ResponseBody
@PostMapping(value = "postTalk")
public Object writeArticle(HttpServletRequest request, HttpServletResponse response, Model model, @RequestBody JobTalk jobTalk) {
    BaseResult result = new BaseResult();
    FqUserCache user = webUtil.currentUser(request,response);
    if(user == null || user.getId() == null){
        result.setResult(ResultEnum.USER_NOT_LOGIN);
        return result;
    }
    if(!user.getId().equals(jobTalk.getUserId())){
        result.setResult(ResultEnum.FAIL);
        return result;
    }
    jobTalk.setTitle(HtmlUtils.htmlEscape(jobTalk.getTitle()));
    jobTalk.setDelFlag(YesNoEnum.NO.getValue());
    jobTalk.setCreateTime(new Date());
    jobTalkService.insert(jobTalk);
    result.setResult(ResultEnum.SUCCESS);
    return result;
}
 
Example 8
Source Project: bbs   Source File: HtmlEscape.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 转义
 * @param data
 * @return
 */
public static String escape(String data){
	//  &:&amp; 
	//  " :&quot; 
	//  < :&lt; 
	//  > :&gt; 
	data = HtmlUtils.htmlEscape(data);
	//  ' :\' 
	//  " :\" 
	//  \ :\\ 
	//  走纸换页: \f 
	//  换行:\n 
	//  换栏符:\t 
	//  回车:\r 
	//  回退符:\b 
//	data = JavaScriptUtils.javaScriptEscape(data);
	return data;
}
 
Example 9
private TableCell buildNote(InstructionalOffering offering, boolean isEditable, UserContext user){
  	TableCell cell = null;
if (offering.getNotes() != null && !offering.getNotes().trim().isEmpty()) {
	if (CommonValues.NoteAsShortText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
		String note = (offering.getNotes().length() <= 20 ? offering.getNotes() : offering.getNotes().substring(0, 20) + "...");
		cell = initNormalCell(note.replaceAll("\n","<br>"), isEditable);
  			cell.setAlign("left");
	} else if (CommonValues.NoteAsFullText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
		cell = initNormalCell(offering.getNotes().replaceAll("\n","<br>"), isEditable);
  			cell.setAlign("left");
	} else {
   		cell = initNormalCell("<IMG border='0' alt='" + MSG.altHasNoteToMgr() + "' title='" + HtmlUtils.htmlEscape(offering.getNotes()) + "' align='absmiddle' src='images/note.png'>", isEditable);
   		cell.setAlign("center");
	}
} else { 
  		cell = this.initNormalCell("&nbsp;" ,isEditable);
  	}
      return(cell);
  }
 
Example 10
Source Project: oauth-boot   Source File: BootOAuthExceptionJacksonSerializer.java    License: MIT License 6 votes vote down vote up
@Override
public void serialize(BootOAuth2Exception value, JsonGenerator jgen, SerializerProvider serializerProvider) throws IOException {
    jgen.writeStartObject();
    jgen.writeObjectField("status", value.getHttpErrorCode());
    String errorMessage = value.getOAuth2ErrorCode();
    if (errorMessage != null) {
        errorMessage = HtmlUtils.htmlEscape(errorMessage);
    }
    jgen.writeStringField("msg", errorMessage);
    if (value.getAdditionalInformation()!=null) {
        for (Map.Entry<String, String> entry : value.getAdditionalInformation().entrySet()) {
            String key = entry.getKey();
            String add = entry.getValue();
            jgen.writeStringField(key, add);
        }
    }
    jgen.writeEndObject();
}
 
Example 11
Source Project: lams   Source File: GradebookService.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
    * Returns the lesson status string which is a reference to an image
    *
    * @param learnerProgress
    * @return
    */
   private String getLessonStatusStr(LearnerProgress learnerProgress) {
String status = "-";

final String IMAGES_DIR = Configuration.get(ConfigurationKeys.SERVER_URL) + "images";
if (learnerProgress != null) {
    if (learnerProgress.isComplete()) {
	status = "<i class='fa fa-check text-success'></i>";

    } else if ((learnerProgress.getAttemptedActivities() != null)
	    && (learnerProgress.getAttemptedActivities().size() > 0)) {

	String currentActivityTitle = learnerProgress.getCurrentActivity() == null ? ""
		: HtmlUtils.htmlEscape(learnerProgress.getCurrentActivity().getTitle());
	status = "<i class='fa fa-cog' title='" + currentActivityTitle + "'></i>";
    }
}
return status;
   }
 
Example 12
Source Project: lams   Source File: GradebookService.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
    * Returns the activity status string which is a reference to an image
    *
    * @param learnerProgress
    * @param activity
    * @return
    */
   private String getActivityStatusStr(Object learnerProgress, Activity activity) {

final String IMAGES_DIR = Configuration.get(ConfigurationKeys.SERVER_URL) + "images";
if (learnerProgress != null) {
    // this construct looks bad but see LDEV-4609 commit for explanation
    byte statusByte = learnerProgress instanceof LearnerProgressArchive
	    ? ((LearnerProgressArchive) learnerProgress).getProgressState(activity)
	    : ((LearnerProgress) learnerProgress).getProgressState(activity);
    Activity currentActivity = learnerProgress instanceof LearnerProgressArchive
	    ? ((LearnerProgressArchive) learnerProgress).getCurrentActivity()
	    : ((LearnerProgress) learnerProgress).getCurrentActivity();
    if (statusByte == LearnerProgress.ACTIVITY_ATTEMPTED && currentActivity != null) {
	return "<i class='fa fa-cog' title='" + HtmlUtils.htmlEscape(currentActivity.getTitle()) + "'></i>";
    } else if (statusByte == LearnerProgress.ACTIVITY_COMPLETED) {
	return "<i class='fa fa-check text-success'></i>";
    }
}
return "-";
   }
 
Example 13
Source Project: lams   Source File: PeerreviewServiceImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
   public StyledCriteriaRatingDTO getUsersRatingsCommentsByCriteriaIdDTO(Long toolContentId, Long toolSessionId,
    RatingCriteria criteria, Long currentUserId, boolean skipRatings, int sorting, String searchString,
    boolean getAllUsers, boolean getByUser) {

if (skipRatings) {
    return ratingService.convertToStyledDTO(criteria, currentUserId, getAllUsers, null);
}

List<Object[]> rawData = peerreviewUserDao.getRatingsComments(toolContentId, toolSessionId, criteria,
	currentUserId, null, null, sorting, searchString, getByUser, ratingService, userManagementService);

for (Object[] raw : rawData) {
    raw[raw.length - 2] = HtmlUtils.htmlEscape((String) raw[raw.length - 2]);
}
// if !getByUser -> is get current user's ratings from other users ->
// convertToStyledJSON.getAllUsers needs to be true otherwise current user (the only one in the set!) is dropped
return ratingService.convertToStyledDTO(criteria, currentUserId, !getByUser || getAllUsers, rawData);
   }
 
Example 14
Source Project: MyCommunity   Source File: DiscussPostServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int addDiscussPost(DiscussPost post) {

    // 转义html标签
    post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));
    post.setContent(HtmlUtils.htmlEscape(post.getContent()));
    // 过滤敏感词
    post.setTitle(sensitiveFilter.filter(post.getTitle()));
    post.setContent(sensitiveFilter.filter(post.getContent()));

    return discussPostMapper.insertDiscussPost(post);
}
 
Example 15
Source Project: lams   Source File: HtmlEscapingAwareTag.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * HTML-encodes the given String, only if the "htmlEscape" setting is enabled.
 * <p>The response encoding will be taken into account if the
 * "responseEncodedHtmlEscape" setting is enabled as well.
 * @param content the String to escape
 * @return the escaped String
 * @since 4.1.2
 * @see #isHtmlEscape()
 * @see #isResponseEncodedHtmlEscape()
 */
protected String htmlEscape(String content) {
	String out = content;
	if (isHtmlEscape()) {
		if (isResponseEncodedHtmlEscape()) {
			out = HtmlUtils.htmlEscape(content, this.pageContext.getResponse().getCharacterEncoding());
		}
		else {
			out = HtmlUtils.htmlEscape(content);
		}
	}
	return out;
}
 
Example 16
Source Project: herd   Source File: HerdUiControllerAdvice.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets a "displayErrorMessage" model and view.
 *
 * @param message An optional error message to include in the model. If null, it won't be included in the model. The message will be automatically HTML
 *            escaped.
 *
 * @return the model and view.
 */
public static ModelAndView getDisplayErrorMessageModelAndView(String message)
{
    String viewName = UiConstants.DISPLAY_ERROR_MESSAGE_PAGE;
    if (message == null)
    {
        return new ModelAndView(viewName);
    }
    else
    {
        return new ModelAndView(viewName, UiConstants.MODEL_KEY_MESSAGE, HtmlUtils.htmlEscape(message));
    }
}
 
Example 17
Source Project: lams   Source File: PeerreviewServiceImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
   public List<Object[]> getUserNotebookEntriesForTablesorter(Long toolSessionId, int page, int size, int sorting,
    String searchString) {
List<Object[]> rawData = peerreviewUserDao.getUserNotebookEntriesForTablesorter(toolSessionId, page, size,
	sorting, searchString, coreNotebookService, userManagementService);

for (Object[] raw : rawData) {
    StringBuilder description = new StringBuilder((String) raw[1]).append(" ").append((String) raw[2]);
    raw[2] = HtmlUtils.htmlEscape(description.toString());
}

return rawData;
   }
 
Example 18
Source Project: roncoo-jui-springboot   Source File: WebXssFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String[] getParameterValues(String name) {
	String[] values = super.getParameterValues(name);
	if (values != null) {
		int length = values.length;
		String[] escapseValues = new String[length];
		for (int i = 0; i < length; i++) {
			// 防xss攻击和过滤前后空格
			escapseValues[i] = HtmlUtils.htmlEscape(values[i]).trim();
		}
		return escapseValues;
	}
	return super.getParameterValues(name);
}
 
Example 19
Source Project: feiqu-opensource   Source File: ArticleController.java    License: Apache License 2.0 5 votes vote down vote up
@GetMapping("/edit/{articleId}")
public String edit(@PathVariable Integer articleId, Model model){
    try {
        FqUserCache user = getCurrentUser();
        if(user == null){
            return USER_LOGIN_REDIRECT_URL;
        }
        Article article = articleService.selectByPrimaryKey(articleId);
        if(article == null){
            return GENERAL_NOT_FOUNF_404_URL;
        }
        if(!user.getId().equals(article.getUserId())){
            return "/unauthed.html";
        }
        if(article.getContentType() == 2){
            article.setArticleContent(HtmlUtils.htmlUnescape(article.getArticleContent()));
        }
        model.addAttribute("article",article);
        FqLabelExample example = new FqLabelExample();
        example.createCriteria().andTypeEqualTo(TopicTypeEnum.ARTICLE_TYPE.getValue());
        List<FqLabel> labels = fqLabelService.selectByExample(example);
        model.addAttribute("labels",labels);
    } catch (Exception e) {
        _log.error("article edit error",e);
    }
    return "/article/edit.html";
}
 
Example 20
Source Project: feiqu-opensource   Source File: ArticleController.java    License: Apache License 2.0 5 votes vote down vote up
@PostMapping("/manage/htmlUnescape/{articleId}")
@ResponseBody
public Object htmlUnescape(@PathVariable Integer articleId){
    BaseResult result = new BaseResult();
    try {
        FqUserCache currentUser = getCurrentUser();
        if(currentUser == null){
            result.setResult(ResultEnum.USER_NOT_LOGIN);
            return result;
        }
        if(currentUser.getRole() != 1){
            result.setResult(ResultEnum.USER_NOT_AUTHORIZED);
            return result;
        }
        Article article = articleService.selectByPrimaryKey(articleId);
        if(article == null){
            result.setResult(ResultEnum.PARAM_NULL);
            return result;
        }
        FqUser fqUser = fqUserService.selectByPrimaryKey(article.getUserId());
        if(fqUser == null){
            result.setResult(ResultEnum.PARAM_NULL);
            return result;
        }
        Article toUpdate = new Article();
        toUpdate.setId(article.getId());
        toUpdate.setArticleContent(HtmlUtils.htmlUnescape(article.getArticleContent()));
        articleService.updateByPrimaryKeySelective(toUpdate);
        _log.info("反转义文章,当前用户:{},被转义文章用户:{}",currentUser.getId(),article.getUserId());
    } catch (Exception e) {
        _log.error("文章反转义出错",e);
        result.setCode("1");
        result.setMessage("文章反转义出错");
    }
    return result;
}
 
Example 21
private String createNotifierErrorMessage( Throwable throwable )
{
    StringBuilder sb = new StringBuilder( "GML import failed: " );

    Throwable rootThrowable = ExceptionUtils.getRootCause( throwable );

    if ( rootThrowable == null )
    {
        rootThrowable = throwable;
    }

    if ( rootThrowable instanceof SAXParseException )
    {
        SAXParseException e = (SAXParseException) rootThrowable;
        sb.append( e.getMessage() );

        if ( e.getLineNumber() >= 0 )
        {
            sb.append( " On line " ).append( e.getLineNumber() );

            if ( e.getColumnNumber() >= 0 )
            {
                sb.append( " column " ).append( e.getColumnNumber() );
            }
        }
    }
    else
    {
        sb.append( rootThrowable.getMessage() );
    }

    if ( sb.charAt( sb.length() - 1 ) != '.' )
    {
        sb.append( '.' );
    }

    return HtmlUtils.htmlEscape( sb.toString() );
}
 
Example 22
Source Project: jeecg-cloud   Source File: HTMLUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取HTML内的文本,不包含标签
 *
 * @param html HTML 代码
 */
public static String getInnerText(String html) {
    if (StringUtils.isNotBlank(html)) {
        //去掉 html 的标签
        String content = html.replaceAll("</?[^>]+>", "");
        // 将多个空格合并成一个空格
        content = content.replaceAll("(&nbsp;)+", "&nbsp;");
        // 反向转义字符
        content = HtmlUtils.htmlUnescape(content);
        return content.trim();
    }
    return "";
}
 
Example 23
Source Project: White-Jotter   Source File: UserService.java    License: MIT License 5 votes vote down vote up
public int register(User user) {
    String username = user.getUsername();
    String name = user.getName();
    String phone = user.getPhone();
    String email = user.getEmail();
    String password = user.getPassword();

    username = HtmlUtils.htmlEscape(username);
    user.setUsername(username);
    name = HtmlUtils.htmlEscape(name);
    user.setName(name);
    phone = HtmlUtils.htmlEscape(phone);
    user.setPhone(phone);
    email = HtmlUtils.htmlEscape(email);
    user.setEmail(email);
    user.setEnabled(true);

    if (username.equals("") || password.equals("")) {
        return 0;
    }

    boolean exist = isExist(username);

    if (exist) {
        return 2;
    }

    // 默认生成 16 位盐
    String salt = new SecureRandomNumberGenerator().nextBytes().toString();
    int times = 2;
    String encodedPassword = new SimpleHash("md5", password, salt, times).toString();

    user.setSalt(salt);
    user.setPassword(encodedPassword);

    userDAO.save(user);

    return 1;
}
 
Example 24
Source Project: es   Source File: SearchBindStatus.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getDisplayValue() {
    if (this.value instanceof String) {
        return (String) this.value;
    }
    if (this.value != null) {
        return (this.htmlEscape ? HtmlUtils.htmlEscape(this.value.toString()) : this.value.toString());
    }
    return "";
}
 
Example 25
Source Project: java-technology-stack   Source File: HtmlEscapingAwareTag.java    License: MIT License 5 votes vote down vote up
/**
 * HTML-encodes the given String, only if the "htmlEscape" setting is enabled.
 * <p>The response encoding will be taken into account if the
 * "responseEncodedHtmlEscape" setting is enabled as well.
 * @param content the String to escape
 * @return the escaped String
 * @since 4.1.2
 * @see #isHtmlEscape()
 * @see #isResponseEncodedHtmlEscape()
 */
protected String htmlEscape(String content) {
	String out = content;
	if (isHtmlEscape()) {
		if (isResponseEncodedHtmlEscape()) {
			out = HtmlUtils.htmlEscape(content, this.pageContext.getResponse().getCharacterEncoding());
		}
		else {
			out = HtmlUtils.htmlEscape(content);
		}
	}
	return out;
}
 
Example 26
@Override
public void serializeResponse(ApiBootOAuth2Exception e, JsonGenerator generator) {
    try {
        String message = e.getMessage();
        if (message != null) {
            message = HtmlUtils.htmlEscape(message);
        }
        generator.writeObjectField("errorMessage", message);
        generator.writeObjectField("errorCode", HttpStatus.UNAUTHORIZED.getReasonPhrase());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 27
Source Project: teaching   Source File: HTMLUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取HTML内的文本,不包含标签
 *
 * @param html HTML 代码
 */
public static String getInnerText(String html) {
    if (StringUtils.isNotBlank(html)) {
        //去掉 html 的标签
        String content = html.replaceAll("</?[^>]+>", "");
        // 将多个空格合并成一个空格
        content = content.replaceAll("(&nbsp;)+", "&nbsp;");
        // 反向转义字符
        content = HtmlUtils.htmlUnescape(content);
        return content.trim();
    }
    return "";
}
 
Example 28
Source Project: herd   Source File: HerdController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Displays an informational message.
 *
 * @param message the message to display.
 *
 * @return the model and view.
 */
@RequestMapping(UiConstants.DISPLAY_INFO_MESSAGE_URL)
public ModelAndView displayInfoMessage(@RequestParam(UiConstants.MODEL_KEY_MESSAGE) String message)
{
    String viewName = UiConstants.DISPLAY_INFO_MESSAGE_PAGE;
    if (message == null)
    {
        return new ModelAndView(viewName);
    }
    else
    {
        return new ModelAndView(viewName, UiConstants.MODEL_KEY_MESSAGE, HtmlUtils.htmlEscape(message));
    }
}
 
Example 29
private void setText(VkConnection connection, WebhookEmbedBuilder builder, String text, String url) {
    if (StringUtils.isNotEmpty(text)) {
        if (connection.isShowPostLink()) {
            builder.setTitle(new WebhookEmbed.EmbedTitle(getMessage(connection, "vk.message.open"), url));
        }
        builder.setDescription(trimTo(CommonUtils.parseVkLinks(HtmlUtils.htmlUnescape(text)), MessageEmbed.TEXT_MAX_LENGTH));
    }
}
 
Example 30
Source Project: onetwo   Source File: HtmlElement.java    License: Apache License 2.0 5 votes vote down vote up
protected StringBuilder buildAttributeTag(StringBuilder attributesBuf, String attr, Object val){
	String valStr = val==null?"":val.toString();
	if(StringUtils.isBlank(valStr))
		return attributesBuf;
	valStr = HtmlUtils.htmlEscape(valStr);
	attributesBuf.append(attr).append("=\"").append(valStr).append("\"");
	return attributesBuf;
}