org.springframework.web.util.HtmlUtils Java Examples

The following examples show how to use org.springframework.web.util.HtmlUtils. 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 File: HtmlEscape.java    From bbs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 转义
 * @param data
 * @return
 */
public static String escape(String data){
	//  &:& 
	//  " :" 
	//  < :&lt; 
	//  > :&gt; 
	data = HtmlUtils.htmlEscape(data);
	//  ' :\' 
	//  " :\" 
	//  \ :\\ 
	//  走纸换页: \f 
	//  换行:\n 
	//  换栏符:\t 
	//  回车:\r 
	//  回退符:\b 
//	data = JavaScriptUtils.javaScriptEscape(data);
	return data;
}
 
Example #2
Source File: GradebookService.java    From lams with 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 #3
Source File: GradebookService.java    From lams with 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 #4
Source File: JwtLoginFilter.java    From SpringSecurity-JWT-Vue-Deom with 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 #5
Source File: CommentServiceImpl.java    From MyCommunity with 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 #6
Source File: PeerreviewServiceImpl.java    From lams with 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 #7
Source File: WebInstructionalOfferingTableBuilder.java    From unitime with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: BootOAuthExceptionJacksonSerializer.java    From oauth-boot with 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 #9
Source File: StringEscapeEditor.java    From feiqu-opensource with 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 #10
Source File: ApiDocInterfaceController.java    From feiqu-opensource with Apache License 2.0 6 votes vote down vote up
/**
 * 更新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 #11
Source File: ArticleController.java    From feiqu-opensource with 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 #12
Source File: JobController.java    From feiqu-opensource with 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 #13
Source File: WebInstructionalOfferingTableBuilder.java    From unitime with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: HtmlEscapingAwareTag.java    From lams with 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 #15
Source File: HerdUiControllerAdvice.java    From herd with 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 #16
Source File: EmailNotificationSender.java    From zhcet-web with Apache License 2.0 5 votes vote down vote up
private void sanitize(Notification notification) {
    String title = notification.getTitle();
    if (title != null)
        notification.setTitle(HtmlUtils.htmlEscape(title));
    String message = notification.getMessage();
    if (message != null)
        notification.setMessage(HtmlUtils.htmlEscape(message));
}
 
Example #17
Source File: WebClassListTableBuilder.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
protected TableCell buildNote(PreferenceGroup prefGroup, boolean isEditable, UserContext user){
	TableCell cell = null;
	if (prefGroup instanceof Class_) {
		Class_ c = (Class_) prefGroup;
		String offeringNote = c.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering().getNotes();
		String classNote = c.getNotes();
		String note = (offeringNote == null || offeringNote.isEmpty() ? classNote : offeringNote + (classNote == null || classNote.isEmpty() ? "" : "\n" + classNote));
		if (note != null && !note.isEmpty()) {
			if (CommonValues.NoteAsShortText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
				if (classNote != null && !classNote.isEmpty()) note = classNote;
				if (note.length() > 20) note = note.substring(0, 20) + "...";
				cell = initNormalCell(note.replaceAll("\n","<br>"), isEditable);
    			cell.setAlign("left");
			} else if (CommonValues.NoteAsFullText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
				cell = initNormalCell(note.replaceAll("\n","<br>"), isEditable);
    			cell.setAlign("left");
			} else {
	    		cell = initNormalCell("<IMG border='0' alt='" + MSG.altHasNoteToMgr() + "' title='" + HtmlUtils.htmlEscape(note) + "' 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 #18
Source File: GBUserGridRowDTO.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public GBUserGridRowDTO(User user) {
this.id = user.getUserId().toString();
this.rowName = HtmlUtils.htmlEscape(user.getLastName() + ", " + user.getFirstName());
this.firstName = user.getFirstName();
this.lastName = user.getLastName();
this.login = user.getLogin();
this.setPortraitId(user.getPortraitUuid());
   }
 
Example #19
Source File: WebXssFilter.java    From roncoo-jui-springboot with 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 #20
Source File: DiscussPostServiceImpl.java    From MyCommunity with 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 #21
Source File: ArticleController.java    From feiqu-opensource with 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 #22
Source File: ArticleController.java    From feiqu-opensource with 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 #23
Source File: DefaultGmlImportService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #24
Source File: HTMLUtils.java    From jeecg-cloud with 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 #25
Source File: UserService.java    From White-Jotter with 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 #26
Source File: HTMLUtils.java    From teaching with 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 #27
Source File: DefaultAuthorizationDeniedResponse.java    From api-boot with Apache License 2.0 5 votes vote down vote up
@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 #28
Source File: HtmlEscapingAwareTag.java    From java-technology-stack with 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 #29
Source File: SearchBindStatus.java    From es with 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 #30
Source File: HerdController.java    From herd with 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));
    }
}