本文整理汇总了Java中javax.servlet.http.HttpServletRequest.getRequestURI方法的典型用法代码示例。如果您正苦于以下问题:Java HttpServletRequest.getRequestURI方法的具体用法?Java HttpServletRequest.getRequestURI怎么用?Java HttpServletRequest.getRequestURI使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.servlet.http.HttpServletRequest
的用法示例。
在下文中一共展示了HttpServletRequest.getRequestURI方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: run
import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
@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;
}
}
示例2: delete
import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
@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);
}
示例3: doFilter
import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
/**
* 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);
}
示例4: doFilter
import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
@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);
}
示例5: filterBeforeHandling
import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
@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());
}
示例6: preHandle
import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
@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);
}
示例7: beforeRequest
import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
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
}
}
}
示例8: logRequest
import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
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());
}
示例9: logViewer
import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
@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";
}
示例10: getCategory
import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
/**
* 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);
}
示例11: logMessage
import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
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);
}
}
示例12: resolveException
import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
@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;
}
示例13: doFilter
import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
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);
}
示例14: tagsWithSearch
import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
@RequestMapping("/tags:{tagNames}/search:{search}")
public String tagsWithSearch(HttpServletRequest request){
return "redirect:"+ request.getRequestURI() +"/sort:age-desc/page:1";
}
示例15: doFilter
import javax.servlet.http.HttpServletRequest; //导入方法依赖的package包/类
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);
}