当前位置: 首页>>代码示例>>Java>>正文


Java WebUtils类代码示例

本文整理汇总了Java中org.springframework.web.util.WebUtils的典型用法代码示例。如果您正苦于以下问题:Java WebUtils类的具体用法?Java WebUtils怎么用?Java WebUtils使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


WebUtils类属于org.springframework.web.util包,在下文中一共展示了WebUtils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: doFilterInternal

import org.springframework.web.util.WebUtils; //导入依赖的package包/类
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    throws ServletException, IOException
{
  CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
  if (csrf != null) {
    Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
    String token = csrf.getToken();
    if (cookie == null || token != null && !token.equals(cookie.getValue())) {
      cookie = new Cookie("XSRF-TOKEN", token);
      cookie.setPath("/");
      response.addCookie(cookie);
    }
  }
  filterChain.doFilter(request, response);
}
 
开发者ID:kreinhard,项目名称:OpenViSu,代码行数:17,代码来源:CsrfHeaderFilter.java

示例2: resolveArgument

import org.springframework.web.util.WebUtils; //导入依赖的package包/类
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

    HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
    MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(servletRequest, MultipartHttpServletRequest.class);

    ExcelRequestBody annotation = parameter.getParameterAnnotation(ExcelRequestBody.class);
    if (multipartRequest != null) {
        List<Object> result = new ArrayList<>();
        List<MultipartFile> files = multipartRequest.getFiles(annotation.name());
        for (MultipartFile file : files) {
            if (converters.supportsExcelType(annotation.type())) {
                List<?> part = converters.fromExcel(annotation, file.getInputStream());
                result.addAll(part);
            }
        }
        return result;
    }
    return null;

}
 
开发者ID:natsuforyou,项目名称:spring-boot-excel-plugin,代码行数:22,代码来源:ExcelRequestResponseBodyHandler.java

示例3: parseLocaleCookieIfNecessary

import org.springframework.web.util.WebUtils; //导入依赖的package包/类
private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
    if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
        // Retrieve and parse cookie value.
        Cookie cookie = WebUtils.getCookie(request, getCookieName());
        Locale locale = null;
        TimeZone timeZone = null;
        if (cookie != null) {
            String value = cookie.getValue();

            // Remove the double quote
            value = StringUtils.replace(value, "%22", "");

            String localePart = value;
            String timeZonePart = null;
            int spaceIndex = localePart.indexOf(' ');
            if (spaceIndex != -1) {
                localePart = value.substring(0, spaceIndex);
                timeZonePart = value.substring(spaceIndex + 1);
            }
            locale = (!"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null);
            if (timeZonePart != null) {
                timeZone = StringUtils.parseTimeZoneString(timeZonePart);
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale +
                    "'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
            }
        }
        request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
            (locale != null ? locale: determineDefaultLocale(request)));

        request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
            (timeZone != null ? timeZone : determineDefaultTimeZone(request)));
    }
}
 
开发者ID:GastonMauroDiaz,项目名称:buenojo,代码行数:36,代码来源:AngularCookieLocaleResolver.java

示例4: parseLocaleCookieIfNecessary

import org.springframework.web.util.WebUtils; //导入依赖的package包/类
private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
    if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
        // Retrieve and parse cookie value.
        Cookie cookie = WebUtils.getCookie(request, getCookieName());
        Locale locale = null;
        TimeZone timeZone = null;
        if (cookie != null) {
            String value = cookie.getValue();

            // Remove the double quote
            value = StringUtils.replace(value, "%22", "");

            String localePart = value;
            String timeZonePart = null;
            int spaceIndex = localePart.indexOf(' ');
            if (spaceIndex != -1) {
                localePart = value.substring(0, spaceIndex);
                timeZonePart = value.substring(spaceIndex + 1);
            }
            locale = !"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null;
            if (timeZonePart != null) {
                timeZone = StringUtils.parseTimeZoneString(timeZonePart);
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale +
                    "'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
            }
        }
        request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
            locale != null ? locale: determineDefaultLocale(request));

        request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
            timeZone != null ? timeZone : determineDefaultTimeZone(request));
    }
}
 
开发者ID:quanticc,项目名称:sentry,代码行数:36,代码来源:AngularCookieLocaleResolver.java

示例5: globalError

import org.springframework.web.util.WebUtils; //导入依赖的package包/类
@ApiOperation("display error page")
@GetMapping("error")
public ModelAndView globalError(HttpServletRequest request) {
    String remoteIp = NetworkUtil.getRemoteIp();
    String lastAccessUri = RequestHolder.getLastAccessUri();

    ModelAndView modelAndView = new ModelAndView("error");
    modelAndView.addObject("uri", request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE));
    modelAndView.addObject("status", request.getAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE));
    Object error = request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE);
    modelAndView.addObject("error", error);
    Object msg = request.getAttribute(WebUtils.ERROR_MESSAGE_ATTRIBUTE);
    modelAndView.addObject("message", msg);
    log.warn("{} {} visit {},error:{},msg:{}", WARN_CHECK, remoteIp, lastAccessUri, error, msg);
    return modelAndView;
}
 
开发者ID:helloworldtang,项目名称:sns-todo,代码行数:17,代码来源:GlobalController.java

示例6: getQuickSearchPosts

import org.springframework.web.util.WebUtils; //导入依赖的package包/类
@RequestMapping(value = "/quicksearch/page/{pageNumber}",
        produces = "text/html;charset=UTF-8")
public String getQuickSearchPosts(@PathVariable int pageNumber,
                                  HttpServletRequest request,
                                  CurrentUser currentUser) {
    String search = (String) WebUtils.getSessionAttribute(request, SESSION_QUICKSEARCH_QUERY);
    String result;
    List<PostDoc> postDocs = postDocService.doQuickSearch(search);
    if (postDocs.size() == 0) {
        result = fmService.getNoResultsMessage(search);
    } else {
        Slice<PostDoc> posts = postDocService.doPagedQuickSearch(search, pageNumber, POST_PAGING_SIZE);
        result = populatePostDocStream(posts.getContent(), currentUser);
        WebUtils.setSessionAttribute(request, SESSION_ATTRIBUTE_QUICKSEARCH_POSTS, posts.getContent());
    }
    return result;
}
 
开发者ID:mintster,项目名称:nixmash-blog,代码行数:18,代码来源:PostsRestController.java

示例7: getPostsByLikes

import org.springframework.web.util.WebUtils; //导入依赖的package包/类
@RequestMapping(value = "/likes/{userId}/page/{pageNumber}",
        produces = "text/html;charset=UTF-8")
public String getPostsByLikes(@PathVariable long userId,
                              @PathVariable int pageNumber,
                              HttpServletRequest request,
                              CurrentUser currentUser) {
    List<Post> posts = postService.getPostsByUserLikes(userId);
    String result;
    if (posts == null) {
        result = fmService.getNoLikesMessage();
    } else {
        posts = postService.getPagedLikedPosts(userId, pageNumber, POST_PAGING_SIZE);
        result = populatePostStream(posts, currentUser);
        WebUtils.setSessionAttribute(request, SESSION_ATTRIBUTE_LIKEDPOSTS, posts);
    }
    return result;
}
 
开发者ID:mintster,项目名称:nixmash-blog,代码行数:18,代码来源:PostsRestController.java

示例8: addPostLink

import org.springframework.web.util.WebUtils; //导入依赖的package包/类
@RequestMapping(value = "/add/{type}", method = GET)
public String addPostLink(@PathVariable("type") String type, Model model, HttpServletRequest request) {
    PostType postType = PostType.valueOf(type.toUpperCase());
    model.addAttribute("postDTO", new PostDTO());
    model.addAttribute("canPreview", false);
    model.addAttribute("categories", postService.getAdminSelectionCategories());
    if (postType == PostType.POST) {
        WebUtils.setSessionAttribute(request, SESSION_ATTRIBUTE_NEWPOST, null);
        model.addAttribute("hasPost", true);
        model.addAttribute("postheader", webUI.getMessage(ADD_POST_HEADER));
        return ADMIN_POST_ADD_VIEW;
    } else {
        model.addAttribute("postLink", new PostLink());
        model.addAttribute("postheader", webUI.getMessage(ADD_LINK_HEADER));
        return ADMIN_LINK_ADD_VIEW;
    }
}
 
开发者ID:mintster,项目名称:nixmash-blog,代码行数:18,代码来源:AdminPostsController.java

示例9: addLink

import org.springframework.web.util.WebUtils; //导入依赖的package包/类
@RequestMapping(value = "/add/link", params = {"isLink"}, method = GET)
public String addLink(@RequestParam(value = "isLink") Boolean isLink,
                      @Valid PostLink postLink, BindingResult result, Model model, HttpServletRequest request) {
    model.addAttribute("postheader", webUI.getMessage(ADD_LINK_HEADER));
    if (StringUtils.isEmpty(postLink.getLink())) {
        result.rejectValue("link", "post.link.is.empty");
    } else {
        PagePreviewDTO pagePreview = jsoupService.getPagePreview(postLink.getLink());
        if (pagePreview == null) {
            result.rejectValue("link", "post.link.page.not.found");
            return ADMIN_LINK_ADD_VIEW;
        } else {
            model.addAttribute("categories", postService.getAdminSelectionCategories());
            model.addAttribute("hasLink", true);
            model.addAttribute("hasCarousel", true);
            WebUtils.setSessionAttribute(request, "pagePreview", pagePreview);
            model.addAttribute("pagePreview", pagePreview);
            model.addAttribute("postDTO",
                    postDtoFromPagePreview(pagePreview, postLink.getLink()));
        }
    }
    return ADMIN_LINK_ADD_VIEW;
}
 
开发者ID:mintster,项目名称:nixmash-blog,代码行数:24,代码来源:AdminPostsController.java

示例10: extractRequestPayload

import org.springframework.web.util.WebUtils; //导入依赖的package包/类
private String extractRequestPayload(HttpServletRequest request) {
	ContentCachingRequestWrapper wrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);

	if (wrapper == null) {
		return UNKNOWN_PAYLOAD;
	}

	if (wrapper.getContentLength() > 0) {
		try {
			return request.getReader().lines().collect(Collectors.joining(StringUtils.LF));
		} catch (IOException e) {
			return UNKNOWN_PAYLOAD;
		}
	}
	return EMPTY_PAYLOAD;
}
 
开发者ID:cmateosl,项目名称:role-api,代码行数:17,代码来源:BaseLoggingFilter.java

示例11: findSession

import org.springframework.web.util.WebUtils; //导入依赖的package包/类
/**
 * 查询创建的cookie
 * @param request
 * @return
 */
@RequestMapping(value = "/find", method = RequestMethod.GET)
@ResponseBody
public PrevalentMessage findSession(HttpServletRequest request) {

    Cookie cookie = WebUtils.getCookie(request, "token");

    return new PrevalentMessage(cookie.getValue());
}
 
开发者ID:lordking,项目名称:spring-rest-sample,代码行数:14,代码来源:CrossDomainSessionController.java

示例12: handleRequestInternal

import org.springframework.web.util.WebUtils; //导入依赖的package包/类
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
	String fileName = WebUtils.extractFilenameFromUrlPath(request.getRequestURI());
	WsdlDefinition target=null;
	if(wsdlDefinitions.containsKey(fileName)){
		target = wsdlDefinitions.get(fileName);
	}
	if(target==null){
		PrintWriter out=response.getWriter();
		try{
			out.write("WSDL file ["+fileName+"] is not exist!");
			return null;
		}finally{
			out.flush();
			out.close();
		}			
	}else{
		return wsdlDefinitionHandlerAdapter.handle(request, response,target);			
	}
}
 
开发者ID:bsteker,项目名称:bdf2,代码行数:22,代码来源:WsdlController.java

示例13: withBeanInitialization

import org.springframework.web.util.WebUtils; //导入依赖的package包/类
@Test
public void withBeanInitialization() throws Exception {
	HttpServletRequest request = mock(HttpServletRequest.class);
	given(request.getCharacterEncoding()).willReturn(null);
	given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
	given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null);

	MockHttpServletResponse response = new MockHttpServletResponse();

	FilterChain filterChain = mock(FilterChain.class);

	CharacterEncodingFilter filter = new CharacterEncodingFilter();
	filter.setEncoding(ENCODING);
	filter.setBeanName(FILTER_NAME);
	filter.setServletContext(new MockServletContext());
	filter.doFilter(request, response, filterChain);

	verify(request).setCharacterEncoding(ENCODING);
	verify(request).setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
	verify(request).removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
	verify(filterChain).doFilter(request, response);
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:23,代码来源:CharacterEncodingFilterTests.java

示例14: previewPost

import org.springframework.web.util.WebUtils; //导入依赖的package包/类
@RequestMapping(value="/preview", method=RequestMethod.POST)
protected String previewPost(HttpServletRequest request, 
		@ModelAttribute TurnForm tf, 
		ModelMap model)
		throws Exception {
	QuestionData q = (QuestionData) WebUtils.getSessionAttribute(request, "qsess");
	if (q == null) {
		logger.error("No session in preview post!");
		return "redirect:make";
	} 		
	logger.debug("================> qid="+q.getId());

	boolean isTimeout = (tf.getSecondsLeft() <= 0);
	if (isTimeout) tf.setAnswer(Turn.TIMEOUT);

	boolean isRight = false;
	if (q.getAnswer().equals(tf.getAnswer())) isRight=true;
	
	logger.debug("Question preview id="+q.getId()+" isRight="+isRight);
	return "redirect:make?verified="+isRight; 
}
 
开发者ID:kenfrank,项目名称:trivolous,代码行数:22,代码来源:MasterCreate2Controller.java

示例15: csrfHeaderFilter

import org.springframework.web.util.WebUtils; //导入依赖的package包/类
private Filter csrfHeaderFilter() {
	return new OncePerRequestFilter() {
		@Override
		protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
			CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
			if (csrf != null) {
				Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
				String token = csrf.getToken();
				if (cookie == null || token != null && !token.equals(cookie.getValue())) {
					cookie = new Cookie("XSRF-TOKEN", token);
					cookie.setPath("/");
					response.addCookie(cookie);
				}
			}
			filterChain.doFilter(request, response);
		}
	};
}
 
开发者ID:gjk0090,项目名称:complete-transaction-management,代码行数:19,代码来源:MainApplication.java


注:本文中的org.springframework.web.util.WebUtils类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。