本文整理匯總了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);
}