Java Code Examples for javax.servlet.http.HttpServletRequest.getRequestURI()

The following are Jave code examples for showing how to use getRequestURI() of the javax.servlet.http.HttpServletRequest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: filter   File: PreRequestFilter.java   View Source Code Vote up 6 votes
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();

    String fullUrl = request.getRequestURL().toString();
    String url = request.getRequestURI();

    logger.debug(String.format("send %s request to %s", request.getMethod(),fullUrl));
    try {
        requestVerificationService.execute(request,url);
        ctx.setSendZuulResponse(true);
        ctx.setResponseStatusCode(200);
        return request;
    } catch (VerificationException e) {
        logger.error(e.getMessage());
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(200);
        ctx.setResponseBody(String.format(ERROR_MSG_FORMAT,e.getVerificationState()));
        return request;
    }
}
 
Example 2
Project: scoold   File: QuestionController.java   View Source Code Vote up 6 votes
@PostMapping("/{id}/delete")
public String delete(@PathVariable String id, HttpServletRequest req) {
	Post showPost = pc.read(id);
	Profile authUser = utils.getAuthUser(req);
	if (!utils.canEdit(showPost, authUser) || showPost == null) {
		return "redirect:" + req.getRequestURI();
	}
	if (!showPost.isReply()) {
		if ((utils.isMine(showPost, authUser) || utils.isMod(authUser))) {
			showPost.delete();
			return "redirect:" + QUESTIONSLINK + "?success=true&code=16";
		}
	} else if (showPost.isReply()) {
		if (utils.isMine(showPost, authUser) || utils.isMod(authUser)) {
			Post parent = pc.read(showPost.getParentid());
			parent.setAnswercount(parent.getAnswercount() - 1);
			parent.update();
			showPost.delete();
		}
	}
	return "redirect:" + showPost.getPostLink(false, false);
}
 
Example 3
Project: Alpine   File: WhitelistUrlFilter.java   View Source Code Vote up 6 votes
/**
 * Check for allowed URLs being requested.
 *
 * @param request The request object.
 * @param response The response object.
 * @param chain Refers to the {@code FilterChain} object to pass control to the next {@code Filter}.
 * @throws IOException
 * @throws ServletException
 */
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest req = (HttpServletRequest) request;
    final HttpServletResponse res = (HttpServletResponse) response;

    final String requestUri = req.getRequestURI();
    if (requestUri != null) {
        boolean allowed = false;
        for (String url: allowUrls) {
            if (requestUri.equals("/")) {
                if (url.trim().equals("/")) {
                    allowed = true;
                }
            } else if (requestUri.startsWith(url.trim())) {
                allowed = true;
            }
        }
        if (!allowed) {
            res.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }
    chain.doFilter(request, response);
}
 
Example 4
Project: yadaframework   File: CheckSessionFilter.java   View Source Code Vote up 6 votes
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
	// FIXME per qualche strana ragione la sessione non scade se questa url viene ripetutamente chiamata!
	// Per ovviare al problema, faccio il controllo via js con un timeout pari a quello di sessione, in modo che quando arriva è già scaduta,
	// e male che vada la sessione dura il doppio del session timeout impostato (metti che un ajax rinfresca subito dopo il page load per cui il js che entra qui si trova la sessione ancora attiva e la rinfresca)
	if ((servletRequest instanceof HttpServletRequest) && (servletResponse instanceof HttpServletResponse)) {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String requestUri = request.getRequestURI();
		if (requestUri.endsWith(COMMAND)) {
			HttpSession session = request.getSession(false);
			String result = "expired";
			if (session!=null) {
				result = "active";
			}
			if (log.isDebugEnabled()) {
				log.debug(COMMAND + " returned " + result + (session!=null?" "+session.getId():""));
			}
			Writer out = response.getWriter();
			out.write(result);
			out.close();
			return;
		} 
	}
	filterChain.doFilter(servletRequest, servletResponse);
}
 
Example 5
Project: lib-edge   File: BeforeControllerAdvice.java   View Source Code Vote up 6 votes
@Before("init()")
public void filterBeforeHandling(JoinPoint joinPoint) throws Exception {
  log.debug("before handing");
  ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  HttpServletRequest request = attributes.getRequest();
  Map<String, String> requestInfoMap = new LinkedHashMap<>();
  String clientIpAddr = RequestHelper.getRealIp(request);
  String requestUri = request.getRequestURI();
  String requestMethod = request.getMethod();
  int size = 0;
  requestInfoMap.put(TemplateEnum.MESSAGE_SOURCE, environment.getProperty(ENV_LOG_KAFKA_MESSAGE_SOURCE));
  requestInfoMap.put(TemplateEnum.REMOTE_HOST, clientIpAddr);
  requestInfoMap.put(TemplateEnum.REQUEST_METHOD, requestMethod);
  requestInfoMap.put(TemplateEnum.RESPONSE_BODY_SIZE, String.valueOf(size));
  requestInfoMap.put(TemplateEnum.REQUEST_URI, requestUri);
  requestInfoMap.put(TemplateEnum.SERVICE_NAME, environment.getProperty(ENV_APPLICATION_NAME));
  requestInfo.set(requestInfoMap);
  startTime.set(System.currentTimeMillis());
}
 
Example 6
Project: cas-5.1.0   File: CasSecurityContextConfiguration.java   View Source Code Vote up 5 votes
@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
                         final Object handler) throws Exception {
    final String requestPath = request.getRequestURI();
    final Pattern pattern = Pattern.compile("/status(/)*$");

    if (pattern.matcher(requestPath).find()) {
        return requiresAuthenticationStatusInterceptor().preHandle(request, response, handler);
    }
    return requiresAuthenticationStatusAdminEndpointsInterceptor().preHandle(request, response, handler);
}
 
Example 7
Project: yadaframework   File: AuditFilter.java   View Source Code Vote up 5 votes
protected void beforeRequest(HttpServletRequest request) {
	if (log.isInfoEnabled()) {
		try {
			String requestUri = request.getRequestURI();
			String queryString = request.getQueryString();
			String ajaxFlag = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"))?" (ajax)":"";
			log.info("requestUri:{}" + ajaxFlag, requestUri);
			if (queryString!=null) {
				log.info("queryString:{}", queryString);
			}
			if (log.isDebugEnabled()) {
				Map<String, String[]> postDataMap = request.getParameterMap();
				for (String paramName : postDataMap.keySet()) {
					String[] paramValue = postDataMap.get(paramName);
					StringBuffer paramString = new StringBuffer();
					for (int i = 0; i < paramValue.length; i++) {
						if (i>0) {
							paramString.append(" & ");
						}
						paramString.append(paramValue[i]);
					}
					if ("password".equals(paramName) || "confirmPassword".equals(paramName)) {
						paramString=new StringBuffer("[value hidden from log]");
					}
					log.debug("** {} = {} **", paramName, paramString);
				}
				if (postDataMap.isEmpty()) {
					if (org.apache.commons.fileupload.servlet.ServletFileUpload.isMultipartContent(request)) {
						log.debug("** multipart request");
					}
				}
			}
		} catch (Throwable e) {
			// Ignoro
		}
	}
}
 
Example 8
Project: Equella   File: LoggingContextFilter.java   View Source Code Vote up 5 votes
public void logRequest(HttpServletRequest request)
{
	final StringBuilder params = new StringBuilder(request.getRequestURI() + "\n");
	final Map<String, String[]> parameterMap = request.getParameterMap();
	for( Entry<String, String[]> entry : parameterMap.entrySet() )
	{
		final String key = entry.getKey();
		final String keyLower = key.toLowerCase();
		final boolean blankOut = keyLower.contains("password") || keyLower.contains("secret");
		params.append(key);
		params.append("=");

		boolean firstVal = true;
		final String[] values = entry.getValue();
		if( values != null )
		{
			for( String value : values )
			{
				if( !firstVal )
				{
					params.append(",");
				}
				if( blankOut )
				{
					params.append(Strings.padStart("", value.length(), '*'));
				}
				else
				{
					params.append(value);
				}
				firstVal = false;
			}
		}
		params.append("\n");
	}
	REQUEST_LOGGER.trace(params.toString());
}
 
Example 9
Project: forweaver2.0   File: RepositoryController.java   View Source Code Vote up 5 votes
@RequestMapping("/{creatorName}/{repositoryName}/log-viewer/log:{log}")
public String logViewer(@PathVariable("repositoryName") String repositoryName,
		@PathVariable("creatorName") String creatorName,
		@PathVariable("log") String log,
		HttpServletRequest request,Model model) {
	Repository repository = repositoryService.get(creatorName+"/"+repositoryName);
	String uri = request.getRequestURI();
	log = uri.substring(uri.indexOf("/log:")+5);
	VCLog gitLog = gitService.getGitLog(creatorName, repositoryName, log);
	if(gitLog == null)
		return "redirect:/repository/"+ creatorName+"/"+repositoryName+"/log";
	model.addAttribute("repository", repository);
	model.addAttribute("gitLog",gitLog);
	return "/repository/logViewer";
}
 
Example 10
Project: solo-spring   File: CategoryConsole.java   View Source Code Vote up 5 votes
/**
 * Gets a category by the specified request.
 * <p>
 * Renders the response with a json object, for example,
 * 
 * <pre>
 * {
 *     "sc": boolean,
 *     "category": {
 *         "oId": "",
 *         "categoryTitle": "",
 *         "categoryURI": "",
 *         ....
 *     }
 * }
 * </pre>
 * </p>
 *
 * @param request
 *            the specified http servlet request
 * @param response
 *            the specified http servlet response
 * @param context
 *            the specified http request context
 * @throws Exception
 *             exception
 */
@RequestMapping(value = "/console/category/*", method = RequestMethod.GET)
public void getCategory(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
	if (!userQueryService.isAdminLoggedIn(request)) {
		response.sendError(HttpServletResponse.SC_FORBIDDEN);
		return;
	}

	final JSONRenderer renderer = new JSONRenderer();

	try {
		final String requestURI = request.getRequestURI();
		final String categoryId = requestURI.substring((Latkes.getContextPath() + "/console/category/").length());

		final JSONObject result = categoryQueryService.getCategory(categoryId);
		if (null == result) {
			renderer.setJSONObject(QueryResults.defaultResult());
			renderer.render(request, response);
			return;
		}

		final StringBuilder tagBuilder = new StringBuilder();
		final List<JSONObject> tags = (List<JSONObject>) result.opt(Category.CATEGORY_T_TAGS);
		for (final JSONObject tag : tags) {
			tagBuilder.append(tag.optString(Tag.TAG_TITLE)).append(",");
		}
		tagBuilder.deleteCharAt(tagBuilder.length() - 1);
		result.put(Category.CATEGORY_T_TAGS, tagBuilder.toString());

		renderer.setJSONObject(result);
		result.put(Keys.STATUS_CODE, true);
	} catch (final ServiceException e) {
		logger.error(e.getMessage(), e);

		final JSONObject jsonObject = QueryResults.defaultResult();
		renderer.setJSONObject(jsonObject);
		jsonObject.put(Keys.MSG, langPropsService.get("getFailLabel"));
	}
	renderer.render(request, response);
}
 
Example 11
Project: java-logging   File: RequestStatusLoggingFilter.java   View Source Code Vote up 5 votes
private void logMessage(ServletRequest request,
                        ServletResponse response,
                        long startTime,
                        boolean isSuccess,
                        Throwable cause) {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    String requestMethod = httpServletRequest.getMethod();
    String requestUri = httpServletRequest.getRequestURI();
    long responseTime = clock.millis() - startTime;

    // collect markers
    Map<String, Object> fields = new ConcurrentHashMap<>();

    fields.put("requestMethod", requestMethod);
    fields.put("requestUri", requestUri);
    fields.put("responseTime", responseTime);

    if (response != null) {
        fields.put("responseCode", ((HttpServletResponse) response).getStatus());
    }

    LogstashMarker marker = appendEntries(fields);

    // format the message
    String status = isSuccess ? "processed" : "failed";
    String message = String.format("Request %s %s %s in %dms", requestMethod, requestUri, status, responseTime);

    // log the event
    if (isSuccess) {
        LOG.info(marker, message);
    } else {
        LOG.error(marker, message, cause);
    }
}
 
Example 12
Project: belling-admin   File: ExceptionResolver.java   View Source Code Vote up 4 votes
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
		Exception exception) {
	Object result = null;
	String url = request.getRequestURI();//请求URL
	ModelAndView mv = new ModelAndView();
	boolean isJson = ServletUtil.isJSONResponse(request);//是否需要返回json格式数据
	if(exception instanceof org.apache.shiro.authz.UnauthorizedException){
		//没有访问权限
		System.out.println("***没有访问权限:" + url + "  ***" + exception.getMessage());
		mv.addObject("message", "抱歉,您没有当前的操作权限!");//没有操作权限
		LoggerUtils.fmtError(ExceptionResolver.class, exception, exception.getMessage());
	} else if (exception instanceof BaseException) {
		BaseException ae = (BaseException) exception;
		result = ResponseResult.create(ae.getCode()).setMessage(ae.getMessage());
	} else if (exception instanceof ExpiredSessionException) {
		// 捕获因Session会话失效被shiro过滤器拦截异常处理响应数据格式不对,导致tabels js报错问题
		result = TablePageResult.createSuccessResult(new ArrayList<UserOnlineDTO>(), 0, 1);
	} else {
		mv.addObject("message", exception.getMessage());//没有操作权限
		result = ResponseResult.create(ResponseCode.ERROR).setMessage("未知错误");
		LoggerUtils.fmtError(ExceptionResolver.class, exception, exception.getMessage());
	}
	//最后返回错误提示信息
	if(isJson){
		response.setContentType("application/json;charset=UTF-8");
		response.setStatus(HttpStatus.OK.value());
		try {
			PrintWriter writer = response.getWriter();
			writer.write(JSON.toJSONString(result));
			writer.flush();
			writer.close();
		} catch (IOException e) {
			LoggerUtils.fmtError(ExceptionResolver.class, e, "Failed to serialize the object to json for exception resolver!");
		}
	} else{
		//不需要返回json格式,直接返回错误提示页面
		mv.setViewName("exception");
	}
	return mv;
}
 
Example 13
Project: iBase4J-Common   File: XssFilter.java   View Source Code Vote up 4 votes
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
    throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest)arg0;
    HttpServletResponse response = (HttpServletResponse)arg1;
    String pathInfo = req.getPathInfo() == null ? "" : req.getPathInfo();
    String url = req.getServletPath() + pathInfo;
    String uri = req.getRequestURI();
    boolean isNoticeUrl = false;
    // 排除部分URL不做过滤。
    for (String str : excludeUrls) {
        if (uri.indexOf(str) >= 0) {
            logger.info("该URL不作校验:" + url);
            arg2.doFilter(req, response);
            return;
        }
    }
    for (String st : noticeUrls) {
        if (uri.indexOf(st) >= 0) {
            isNoticeUrl = true;
            break;
        }
    }
    // 获取请求所有参数,校验防止SQL注入,防止XSS漏洞

    Enumeration<?> params = req.getParameterNames();
    String paramN = null;
    while (params.hasMoreElements()) {
        paramN = (String)params.nextElement();
        String paramVale = req.getParameter(paramN);
        if (!paramN.toLowerCase().contains("password")) {
            logger.info(paramN + "==" + paramVale);
        }
        if (isNoticeUrl) {
            paramVale = xssEncode(paramVale);
        }
        // 校验是否存在SQL注入信息
        if (checkSQLInject(paramVale, url)) {
            errorResponse(response, paramN);
            return;
        }
    }
    arg2.doFilter(req, response);
}
 
Example 14
Project: forweaver2.0   File: CodeController.java   View Source Code Vote up 4 votes
@RequestMapping("/tags:{tagNames}/search:{search}")
public String tagsWithSearch(HttpServletRequest request){
	return "redirect:"+ request.getRequestURI() +"/sort:age-desc/page:1";
}
 
Example 15
Project: JAVA-   File: XssFilter.java   View Source Code Vote up 4 votes
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
		throws IOException, ServletException {
	HttpServletRequest req = (HttpServletRequest) arg0;
	HttpServletResponse response = (HttpServletResponse) arg1;
	String pathInfo = req.getPathInfo() == null ? "" : req.getPathInfo();
	String url = req.getServletPath() + pathInfo;
	String uri = req.getRequestURI();
	boolean isNoticeUrl = false;
	// 排除部分URL不做过滤。
	for (String str : excludeUrls) {
		if (uri.indexOf(str) >= 0) {
			logger.info("该URL不作校验:" + url);
			arg2.doFilter(req, response);
			return;
		}
	}
	for (String st : noticeUrls) {
		if (uri.indexOf(st) >= 0) {
			isNoticeUrl = true;
			break;
		}
	}
	// 获取请求所有参数,校验防止SQL注入,防止XSS漏洞

	Enumeration<?> params = req.getParameterNames();
	String paramN = null;
	while (params.hasMoreElements()) {
		paramN = (String) params.nextElement();
		String paramVale = req.getParameter(paramN);
		if (!paramN.toLowerCase().contains("password")) {
			logger.info(paramN + "==" + paramVale);
		}
		if (isNoticeUrl) {
			paramVale = xssEncode(paramVale);
		}
		// 校验是否存在SQL注入信息
		if (checkSQLInject(paramVale, url)) {
			errorResponse(response, paramN);
			return;
		}
	}
	arg2.doFilter(req, response);

}
 
Example 16
Project: forweaver2.0   File: PostController.java   View Source Code Vote up 4 votes
@RequestMapping("/tags:{tagNames}/search:{search}")
public String tagsWithSearch(HttpServletRequest request){
	return "redirect:"+ request.getRequestURI() +"/sort:age-desc/page:1";
}
 
Example 17
Project: forweaver2.0   File: RepositoryController.java   View Source Code Vote up 4 votes
@RequestMapping("/{creatorName}/{repositoryName}/browser/log:{log}")
public String fileBrowser(HttpServletRequest request){
	return "redirect:"+request.getRequestURI()+"/filepath:/"; 
}
 
Example 18
Project: cas-security-spring-boot-starter   File: RequestAwareCasAuthenticationEntryPoint.java   View Source Code Vote up 4 votes
static String getBaseUrl(HttpServletRequest request, boolean withContextPath) {
    String uri = request.getRequestURI();
    StringBuilder url = new StringBuilder(request.getRequestURL());
    String contextPath = request.getContextPath();
    return  url.substring(0, url.length() - uri.length() + (withContextPath ? contextPath.length() : 0));
}
 
Example 19
Project: apache-tomcat-7.0.73-with-comment   File: WebdavServlet.java   View Source Code Vote up 4 votes
/**
 * Send a multistatus element containing a complete error report to the
 * client.
 *
 * @param req Servlet request
 * @param resp Servlet response
 * @param errorList List of error to be displayed
 */
private void sendReport(HttpServletRequest req, HttpServletResponse resp,
                        Hashtable<String,Integer> errorList)
        throws IOException {

    resp.setStatus(WebdavStatus.SC_MULTI_STATUS);

    String absoluteUri = req.getRequestURI();
    String relativePath = getRelativePath(req);

    XMLWriter generatedXML = new XMLWriter();
    generatedXML.writeXMLHeader();

    generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus",
            XMLWriter.OPENING);

    Enumeration<String> pathList = errorList.keys();
    while (pathList.hasMoreElements()) {

        String errorPath = pathList.nextElement();
        int errorCode = errorList.get(errorPath).intValue();

        generatedXML.writeElement("D", "response", XMLWriter.OPENING);

        generatedXML.writeElement("D", "href", XMLWriter.OPENING);
        String toAppend = errorPath.substring(relativePath.length());
        if (!toAppend.startsWith("/"))
            toAppend = "/" + toAppend;
        generatedXML.writeText(absoluteUri + toAppend);
        generatedXML.writeElement("D", "href", XMLWriter.CLOSING);
        generatedXML.writeElement("D", "status", XMLWriter.OPENING);
        generatedXML.writeText("HTTP/1.1 " + errorCode + " "
                + WebdavStatus.getStatusText(errorCode));
        generatedXML.writeElement("D", "status", XMLWriter.CLOSING);

        generatedXML.writeElement("D", "response", XMLWriter.CLOSING);

    }

    generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING);

    Writer writer = resp.getWriter();
    writer.write(generatedXML.toString());
    writer.close();

}
 
Example 20
Project: springboot-shiro-cas-mybatis   File: CasDefaultFlowUrlHandler.java   View Source Code Vote up 4 votes
@Override
public String createFlowDefinitionUrl(final String flowId, final AttributeMap input, final HttpServletRequest request) {
    return request.getRequestURI()
        + (request.getQueryString() != null ? '?'
        + request.getQueryString() : "");
}