Java 类org.springframework.web.util.WebUtils 实例源码

项目:OpenViSu    文件:CsrfHeaderFilter.java   
@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);
}
项目:spring-boot-excel-plugin    文件:ExcelRequestResponseBodyHandler.java   
@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;

}
项目:sns-todo    文件:GlobalController.java   
@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;
}
项目:nixmash-blog    文件:PostsRestController.java   
@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;
}
项目:nixmash-blog    文件:PostsRestController.java   
@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;
}
项目:nixmash-blog    文件:AdminPostsController.java   
@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;
    }
}
项目:nixmash-blog    文件:AdminPostsController.java   
@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;
}
项目:role-api    文件:BaseLoggingFilter.java   
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;
}
项目:bdf2    文件:WsdlController.java   
@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);           
    }
}
项目:spring4-understanding    文件:CharacterEncodingFilterTests.java   
@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);
}
项目:trivolous    文件:MasterCreate2Controller.java   
@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; 
}
项目:complete-transaction-management    文件:MainApplication.java   
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);
        }
    };
}
项目:Qihua    文件:SecurityInterceptor.java   
private void saveTimeoutSession(final HttpServletRequest request) {
  StringBuilder params = new StringBuilder("?");
  Map<String, String[]> parameterMap = request.getParameterMap();
  for (Map.Entry<String, String[]> item : parameterMap.entrySet()) {
    params.append(item.getKey() + "=" + item.getValue()[0] + "&");
  }

  // request.getRequestURI(); // /dxbase/daily/display
  // request.getRequestURL(); //
  // http://10.7.210.7:8080/dxbase/daily/display

  WebUtils.setSessionAttribute(request, Constants.SESSION_TIMEOUT_URI,
      request.getRequestURI().substring(request.getContextPath().length()));
  WebUtils.setSessionAttribute(request, Constants.SESSION_TIMEOUT_REQUEST_PARAMETERS, params);
  WebUtils.setSessionAttribute(request, Constants.SESSION_TIMEOUT_REQUEST_METHOD, request.getMethod());
}
项目:trivolous    文件:GameQueueController.java   
@RequestMapping(value="/submit")
protected String onSubmit(HttpServletRequest request,
          SessionStatus status
        ) throws ServletRequestBindingException {
    UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");
    PlayerData player = playerService.findPlayer(userSession.getGameId(), userSession.getMemberId());
    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());
    request.getSession().removeAttribute("qsess");
    playerService.submitQuestion(player.getId(), q);
    return "redirect:/game/game";
}
项目:trivolous    文件:GameSettingsController.java   
@RequestMapping(value="/game/settings/removePlayer", method=RequestMethod.POST)
public String settingsAction(@RequestParam("id") Long id, HttpServletRequest request) {
    UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");
    PlayerData player = userSession.getPlayerData();
    GameDescriptionData gdd = userSession.getGameDesc();
    if (player.getIsMaster()) {
        logger.info("================ REMOVE PLAYER! " + id);
        if (gdd.getNumPlayers() <=3) {
            logger.error("Cannot remove player when 3 or less " + id);
        }
        else {
            playerService.removePlayer(id);
        }
    }
    return "redirect:/game/settings";
}
项目:spring4-understanding    文件:CharacterEncodingFilterTests.java   
@Test
public void encodingIfEmptyAndNotForced() 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(ENCODING);
    filter.init(new MockFilterConfig(FILTER_NAME));
    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);
}
项目:Qihua    文件:MemberController.java   
@RequestMapping(value = "/password-matches")
public @ResponseBody boolean passwordMatches(final HttpServletRequest request, final String oldPassword) {
  try {
    Member session = (Member) WebUtils.getSessionAttribute(request, Constants.SESSION_MEMBER);

    Member aMember = new Member();
    aMember.setMobile(session.getMobile());
    aMember.setPassword(DigestUtils.md5Hex(oldPassword));

    return memberService.passwordMatches(aMember);
  } catch (Exception e) {
    log.error(ExceptionUtils.getStackTraceAsString(e));
  }

  return false;
}
项目:trivolous    文件:GameQueueController.java   
@RequestMapping(value="/preview", method=RequestMethod.GET)
protected String referenceData(HttpServletRequest request, 
        ModelMap model) {
    QuestionData q = (QuestionData) WebUtils.getSessionAttribute(request, "qsess");
    if (q == null) {
        logger.error("No session in preview get!");
        return "redirect:make";
    } 
    else {      
        TurnForm tf = new TurnForm();
        tf.setSecondsLeft(q.getTimeout());
        tf.setAnswer(Turn.GAVEUP);  // default to gave up
        model.addAttribute("command",tf);
        model.addAttribute("question",q);
        logger.debug("================> qid="+q.getId());       
        return "/game/answer";
    }
}
项目:spring4-understanding    文件:PortletUtils.java   
/**
 * Return the target page specified in the request.
 * @param request current portlet request
 * @param paramPrefix the parameter prefix to check for
 * (e.g. "_target" for parameters like "_target1" or "_target2")
 * @param currentPage the current page, to be returned as fallback
 * if no target page specified
 * @return the page specified in the request, or current page if not found
 */
public static int getTargetPage(PortletRequest request, String paramPrefix, int currentPage) {
    Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        String paramName = paramNames.nextElement();
        if (paramName.startsWith(paramPrefix)) {
            for (int i = 0; i < WebUtils.SUBMIT_IMAGE_SUFFIXES.length; i++) {
                String suffix = WebUtils.SUBMIT_IMAGE_SUFFIXES[i];
                if (paramName.endsWith(suffix)) {
                    paramName = paramName.substring(0, paramName.length() - suffix.length());
                }
            }
            return Integer.parseInt(paramName.substring(paramPrefix.length()));
        }
    }
    return currentPage;
}
项目:trivolous    文件:GameController.java   
@RequestMapping(value="/game/previousQuestions", method=RequestMethod.GET)
public String previousQuestions(Model model,  HttpServletRequest request) {
    UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");
    long gameId = userSession.getGameId();
    ArrayList<RoundData> rounds = new ArrayList<RoundData>();
    PlayerData player = userSession.getPlayerData();
    RoundData lastRound = playerService.getLastRound(player.getId());
    Integer lastRoundNumber = lastRound.getRoundNumber();
    if (userSession.getGameDesc().getStatus() != STATUS.COMPLETE) {
        lastRoundNumber -= 1;
    }
    if (lastRound != null) {
        for (int i=lastRoundNumber; i > 0; --i) {
            rounds.add(gameService.getRound(gameId, i));
        }
    }
    model.addAttribute("rounds", rounds);
    model.addAttribute("players", playerService.getActivePlayersInGame(gameId));
    return "game/previousQuestions"; 
}
项目:spring4-understanding    文件:XsltView.java   
/**
 * Configure the supplied {@link HttpServletResponse}.
 * <p>The default implementation of this method sets the
 * {@link HttpServletResponse#setContentType content type} and
 * {@link HttpServletResponse#setCharacterEncoding encoding}
 * from the "media-type" and "encoding" output properties
 * specified in the {@link Transformer}.
 * @param model merged output Map (never {@code null})
 * @param response current HTTP response
 * @param transformer the target transformer
 */
protected void configureResponse(Map<String, Object> model, HttpServletResponse response, Transformer transformer) {
    String contentType = getContentType();
    String mediaType = transformer.getOutputProperty(OutputKeys.MEDIA_TYPE);
    String encoding = transformer.getOutputProperty(OutputKeys.ENCODING);
    if (StringUtils.hasText(mediaType)) {
        contentType = mediaType;
    }
    if (StringUtils.hasText(encoding)) {
        // Only apply encoding if content type is specified but does not contain charset clause already.
        if (contentType != null && !contentType.toLowerCase().contains(WebUtils.CONTENT_TYPE_CHARSET_PREFIX)) {
            contentType = contentType + WebUtils.CONTENT_TYPE_CHARSET_PREFIX + encoding;
        }
    }
    response.setContentType(contentType);
}
项目:spring4-understanding    文件:AbstractJasperReportsSingleFormatView.java   
/**
 * We need to write text to the response Writer.
 * @param exporter the JasperReports exporter to use
 * @param populatedReport the populated {@code JasperPrint} to render
 * @param response the HTTP response the report should be rendered to
 * @throws Exception if rendering failed
 */
protected void renderReportUsingWriter(net.sf.jasperreports.engine.JRExporter exporter,
        JasperPrint populatedReport, HttpServletResponse response) throws Exception {

    // Copy the encoding configured for the report into the response.
    String contentType = getContentType();
    String encoding = (String) exporter.getParameter(net.sf.jasperreports.engine.JRExporterParameter.CHARACTER_ENCODING);
    if (encoding != null) {
        // Only apply encoding if content type is specified but does not contain charset clause already.
        if (contentType != null && !contentType.toLowerCase().contains(WebUtils.CONTENT_TYPE_CHARSET_PREFIX)) {
            contentType = contentType + WebUtils.CONTENT_TYPE_CHARSET_PREFIX + encoding;
        }
    }
    response.setContentType(contentType);

    // Render report into HttpServletResponse's Writer.
    JasperReportsUtils.render(exporter, populatedReport, response.getWriter());
}
项目:trivolous    文件:MasterCreate2Controller.java   
@RequestMapping(value="/make", method=RequestMethod.POST)
protected String makePost(
        HttpServletRequest request, HttpServletResponse response, 
        QuestionData q, 
        ModelMap model)
        throws Exception {
    UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");
    PlayerData player = playerService.findPlayer(userSession.getGameId(), userSession.getMemberId());

    logger.debug("makequestion post playerid="+player.getId()+" qid="+q.getId()+" imageId="+q.getImageId());

    logger.debug("================> qid="+q.getId());       
    request.getSession().setAttribute("qsess", q);

    return "redirect:preview";
}
项目:spring4-understanding    文件:AnnotationMethodHandlerAdapter.java   
@Override
protected Object resolveCookieValue(String cookieName, Class<?> paramType, NativeWebRequest webRequest)
        throws Exception {

    HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
    Cookie cookieValue = WebUtils.getCookie(servletRequest, cookieName);
    if (Cookie.class.isAssignableFrom(paramType)) {
        return cookieValue;
    }
    else if (cookieValue != null) {
        return urlPathHelper.decodeRequestString(servletRequest, cookieValue.getValue());
    }
    else {
        return null;
    }
}
项目:spring4-understanding    文件:RequestMappingHandlerAdapter.java   
@Override
protected ModelAndView handleInternal(HttpServletRequest request,
        HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {

    checkRequest(request);

    if (getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) {
        applyCacheSeconds(response, this.cacheSecondsForSessionAttributeHandlers);
    }
    else {
        prepareResponse(response);
    }

    // Execute invokeHandlerMethod in synchronized block if required.
    if (this.synchronizeOnSession) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            Object mutex = WebUtils.getSessionMutex(session);
            synchronized (mutex) {
                return invokeHandlerMethod(request, response, handlerMethod);
            }
        }
    }

    return invokeHandlerMethod(request, response, handlerMethod);
}
项目:spring4-understanding    文件:AbstractController.java   
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    // Delegate to WebContentGenerator for checking and preparing.
    checkRequest(request);
    prepareResponse(response);

    // Execute handleRequestInternal in synchronized block if required.
    if (this.synchronizeOnSession) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            Object mutex = WebUtils.getSessionMutex(session);
            synchronized (mutex) {
                return handleRequestInternal(request, response);
            }
        }
    }

    return handleRequestInternal(request, response);
}
项目:trivolous    文件:MasterCreate2Controller.java   
@RequestMapping(value="/preview", method=RequestMethod.GET)
protected String previewGet( HttpServletRequest request, 
        ModelMap model) {
    QuestionData q = (QuestionData) WebUtils.getSessionAttribute(request, "qsess");
    if (q == null) {
        logger.error("No session in preview get!");
        return "redirect:make";
    } 
    else {
        TurnForm tf = new TurnForm();
        tf.setSecondsLeft(q.getTimeout());
        tf.setAnswer(Turn.GAVEUP);  // default to gave up
        model.addAttribute("command",tf);
        model.addAttribute("question",q);
        logger.error("================> qid="+q.getId());       
        return "/game/answer";
    }
}
项目:trivolous    文件:GameQueueController.java   
@RequestMapping(value="/make", method=RequestMethod.POST)
protected String onSubmit(
        HttpServletRequest request, HttpServletResponse response, 
        QuestionData q, 
        ModelMap model,
        SessionStatus status)
        throws Exception {
    UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");
    PlayerData player = playerService.findPlayer(userSession.getGameId(), userSession.getMemberId());
    if (request.getParameterMap().containsKey("delete")) {
        // delete all queued questions by sending empty list to reorder to.
        ArrayList<Integer> emptyList = new ArrayList<Integer>();
        playerService.reorderQueuedQuestions(player.getId(),emptyList);
        // clear question in session now.
        status.setComplete();
        return "redirect:make";
    }
    else {
        logger.debug("makequestion post playerid="+player.getId()+" qid="+q.getId()+" imageId="+q.getImageId());
        logger.debug("================> qid="+q.getId());       
        request.getSession().setAttribute("qsess", q); // put question is session so it can be grabbed for verify and submit.
        return "redirect:preview";
    }
}
项目:spring4-understanding    文件:SessionLocaleResolver.java   
@Override
public LocaleContext resolveLocaleContext(final HttpServletRequest request) {
    return new TimeZoneAwareLocaleContext() {
        @Override
        public Locale getLocale() {
            Locale locale = (Locale) WebUtils.getSessionAttribute(request, LOCALE_SESSION_ATTRIBUTE_NAME);
            if (locale == null) {
                locale = determineDefaultLocale(request);
            }
            return locale;
        }
        @Override
        public TimeZone getTimeZone() {
            TimeZone timeZone = (TimeZone) WebUtils.getSessionAttribute(request, TIME_ZONE_SESSION_ATTRIBUTE_NAME);
            if (timeZone == null) {
                timeZone = determineDefaultTimeZone(request);
            }
            return timeZone;
        }
    };
}
项目:spring4-understanding    文件:DispatcherServletTests.java   
@Test
public void cleanupAfterIncludeWithRemove() throws ServletException, IOException {
    MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/main.do");
    MockHttpServletResponse response = new MockHttpServletResponse();

    request.setAttribute("test1", "value1");
    request.setAttribute("test2", "value2");
    WebApplicationContext wac = new StaticWebApplicationContext();
    request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);

    request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "/form.do");
    simpleDispatcherServlet.service(request, response);

    assertEquals("value1", request.getAttribute("test1"));
    assertEquals("value2", request.getAttribute("test2"));
    assertEquals(wac, request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE));
    assertNull(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
    assertNull(request.getAttribute("command"));
}
项目:spring4-understanding    文件:CharacterEncodingFilterTests.java   
@Test
public void forceEncodingAlwaysSetsEncoding() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    request.setCharacterEncoding(ENCODING);
    given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
    given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null);

    HttpServletResponse response = mock(HttpServletResponse.class);
    FilterChain filterChain = mock(FilterChain.class);

    CharacterEncodingFilter filter = new CharacterEncodingFilter(ENCODING, true);
    filter.init(new MockFilterConfig(FILTER_NAME));
    filter.doFilter(request, response, filterChain);

    verify(request).setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
    verify(request).removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
    verify(response).setCharacterEncoding(ENCODING);
    verify(filterChain).doFilter(request, response);
}
项目:spring4-understanding    文件:AbstractSockJsService.java   
protected boolean checkOrigin(ServerHttpRequest request, ServerHttpResponse response, HttpMethod... httpMethods)
        throws IOException {

    if (WebUtils.isSameOrigin(request)) {
        return true;
    }

    if (!WebUtils.isValidOrigin(request, this.allowedOrigins)) {
        if (logger.isWarnEnabled()) {
            logger.warn("Origin header value '" + request.getHeaders().getOrigin() + "' not allowed.");
        }
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return false;
    }

    return true;
}
项目:buenojo    文件:AngularCookieLocaleResolver.java   
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)));
    }
}
项目:configx    文件:ExceptionHandlerAdvice.java   
/**
 * 返回请求参数
 *
 * @param request
 * @return
 */
private String getRequestParams(HttpServletRequest request) {
    Map<String, Object> parameterMap = new HashMap<>();

    // http request中的参数
    Map<String, Object> requestparameterMap = WebUtils.getParametersStartingWith(request, "");
    parameterMap.putAll(requestparameterMap);

    return JSON.toJSONString(parameterMap);
}
项目:csap-core    文件:ServiceOsManager.java   
public String extractSsoCookie ( HttpServletRequest request ) {
    String ssoCookieStringForHeader = HostRequests.getSSO_COOKIE_NAME() + "=NotUsed";

    if ( request != null ) {
        ssoCookieStringForHeader = HostRequests.getSSO_COOKIE_NAME() + "="
                + WebUtils.getCookie( request, HostRequests.getSSO_COOKIE_NAME() ).getValue();
    }

    return ssoCookieStringForHeader;
}
项目:sentry    文件:AngularCookieLocaleResolver.java   
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));
    }
}
项目:nixmash-blog    文件:PostsController.java   
@RequestMapping(value = "/search", method = GET)
public String searchPage(Model model, HttpServletRequest request) {
    model.addAttribute("postQueryDTO", new PostQueryDTO());
    model.addAttribute("isSearchResult", false);
    WebUtils.setSessionAttribute(request, SESSION_POSTQUERYDTO, null);
    return POSTS_SEARCH_VIEW;
}
项目:nixmash-blog    文件:PostsController.java   
@RequestMapping(value = "/search",  params = {"query"}, method = GET)
public String searchPageResults(@Valid PostQueryDTO postQueryDTO,
                                BindingResult result, Model model, HttpServletRequest request) {
    model.addAttribute("postQuery", postQueryDTO);
    if (result.hasErrors()) {
        return POSTS_SEARCH_VIEW;
    } else {
        WebUtils.setSessionAttribute(request, SESSION_POSTQUERYDTO, postQueryDTO);
        model.addAttribute("isSearchResult", true);
        return POSTS_SEARCH_VIEW;
    }
}
项目:nixmash-blog    文件:PostsController.java   
@RequestMapping(value = "", params = {"search"}, method = GET)
public String quicksearch(Model model, String search, HttpServletRequest request) {
    List<PostDoc> postDocs = postDocService.doQuickSearch(search);

    boolean showMore = postDocs.size() > POST_PAGING_SIZE;
    boolean hasQuickSearchResults = postDocs.size() > 0;

    WebUtils.setSessionAttribute(request, SESSION_QUICKSEARCH_QUERY, search);
    model.addAttribute("showmore", showMore);
    model.addAttribute("query", search);
    model.addAttribute("hasResults", hasQuickSearchResults);
    return POSTS_QUICKSEARCH_VIEW;
}
项目:nixmash-blog    文件:PostsRestController.java   
@RequestMapping(value = "/titles/page/{pageNumber}", produces = "text/html;charset=UTF-8")
    public String getPostTitles(@PathVariable Integer pageNumber, HttpServletRequest request, CurrentUser currentUser) {
//        Slice<Post> posts = postService.getPublishedPosts(pageNumber, TITLE_PAGING_SIZE);
        Slice<Post> posts = postService.getPagedPostsByPostType(PostType.POST, pageNumber, TITLE_PAGING_SIZE);
        String result = populatePostStream(posts.getContent(), currentUser, TITLE_TEMPLATE);
        WebUtils.setSessionAttribute(request, SESSION_ATTRIBUTE_POSTTITLES, posts.getContent());
        return result;
    }