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

The following are Jave code examples for showing how to use getServletPath() 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: ssm-web   File: CheckSessionOutFilter.java   View Source Code Vote up 9 votes
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest hsrq = (HttpServletRequest) request;
    HttpServletResponse hsrp = (HttpServletResponse) response;
    String clientType = hsrq.getParameter("clientType");
    if ("WORD".equals(clientType)) {
        chain.doFilter(request, response);
    } else {
        SessionUser person = null;
        String reqPage = hsrq.getServletPath();
        if (!reqPage.trim().equals("/login.do") && !reqPage.trim().equals("/logout.do")
                ) {
            person = (SessionUser) hsrq.getSession().getAttribute(SysConstants.SESSION_USER_KEY);
            if (person == null) {
                hsrp.sendRedirect("login.do");
                return;
            }
        }
        chain.doFilter(request, response);
    }

}
 
Example 2
Project: jboot   File: JbootResourceServlet.java   View Source Code Vote up 6 votes
private String getPath(final HttpServletRequest request) {
    String servletPath;
    String pathInfo;

    if (request.getDispatcherType() == DispatcherType.INCLUDE && request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null) {
        pathInfo = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
        servletPath = (String) request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
    } else {
        pathInfo = request.getPathInfo();
        servletPath = request.getServletPath();
    }
    String result = pathInfo;
    if (result == null) {
        result = CanonicalPathUtils.canonicalize(servletPath);
    } else if (resolveAgainstContextRoot) {
        result = servletPath + CanonicalPathUtils.canonicalize(pathInfo);
    } else {
        result = CanonicalPathUtils.canonicalize(result);
    }
    if ((result == null) || (result.isEmpty())) {
        result = "/";
    }
    return result;

}
 
Example 3
Project: pub-service   File: RequestUtil.java   View Source Code Vote up 6 votes
/**
 * 获取完整的url,包括域名端口等
 * @return
 */
public static String getWholeUrl(HttpServletRequest request){
	String servername =request.getServerName();
	String path  = request.getServletPath();
	int port = request.getServerPort();
	
	String portstr="";
	if(port!=80){
		portstr=":"+port;
	}
	String contextPath = request.getContextPath();
	if(contextPath.equals("/")){
		contextPath="";
	}
	
	
	String url  = "http://"+servername+portstr+contextPath+"/"+path;
	 
	return url;
	
}
 
Example 4
Project: oscm   File: WSDLFilter.java   View Source Code Vote up 6 votes
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    Pattern pattern = Pattern.compile(urlPattern, Pattern.CASE_INSENSITIVE);
    String url = httpRequest.getServletPath();
    Matcher matcher = pattern.matcher(url);
    if (matcher.matches()) {
        String version = matcher.group(1);
        String serviceName = matcher.group(2);
        String portType = matcher.group(3);
        httpRequest.setAttribute(WSDLDeliverServlet.VERSION, version);
        httpRequest.setAttribute(WSDLDeliverServlet.SERVICE_NAME,
                serviceName);
        httpRequest.setAttribute(WSDLDeliverServlet.PORT_TYPE, portType);
        String fileType = request.getParameterNames().nextElement();
        httpRequest.setAttribute(WSDLDeliverServlet.FILE_TYPE, fileType);
        
        String tenantId = httpRequest.getParameter(tenantIdParam);
        httpRequest.setAttribute(WSDLDeliverServlet.TENANT_ID, tenantId);
        
        httpRequest.getRequestDispatcher(servletUrl).forward(httpRequest,
                response);
    }
    return;
}
 
Example 5
Project: convertigo-engine   File: WebServiceServlet.java   View Source Code Vote up 6 votes
protected String generateWsdl(HttpServletRequest request) throws EngineException {
      Engine.logEngine.debug("(WebServiceServlet) WSDL required");
      
String servletPath = request.getServletPath();
Engine.logEngine.debug("(WebServiceServlet) Servlet path: " + servletPath);

      String servletURI = HttpUtils.originalRequestURL(request);
      Engine.logEngine.debug("(WebServiceServlet) Servlet uri: " + servletURI);
      
try {
	int projectNameStartIndex = servletPath.indexOf("/projects/") + 10; 
	int slashIndex = servletPath.indexOf("/", projectNameStartIndex);

	String projectName = servletPath.substring(projectNameStartIndex, slashIndex);
	Engine.logEngine.debug("(WebServiceServlet) Project name: " + projectName);

	if (servletPath.endsWith(".wsl") || servletPath.endsWith(".ws") || servletPath.endsWith(".wsr")) {
		return generateWsdlForDocLiteral(servletURI, projectName);
	}
	throw new EngineException("Unhandled SOAP method (RPC or literal accepted)");
}
catch(StringIndexOutOfBoundsException e) {
	throw new EngineException("Unable to find the project name into the provided URL (\"" + servletPath + "\").");
}
  }
 
Example 6
Project: GameProject-V1.0Beta   File: AdminFilter.java   View Source Code Vote up 5 votes
/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
		throws IOException, ServletException {
	// TODO Auto-generated method stub
	// place your code here

	// pass the request along the filter chain
	HttpServletRequest hsRequest = (HttpServletRequest) request;
	HttpServletResponse hsResponse=(HttpServletResponse)response;
	
	//用于获取当前页面的路径
	String servletPath = hsRequest.getServletPath();
	//获取session储存的admin信息
	Admin admin = (Admin)hsRequest.getSession().getAttribute("loginedAdmin");
	List<GameCompleteServer> list = new GameServerListDao().findGameServers();
	
	if("/adminjsp/server.jsp".equals(servletPath)) {
		if(null != admin) {
			if(null != list && list.size() > 0 
					&& null == hsRequest.getSession().getAttribute("gameServerList"))
				hsRequest.getSession().setAttribute("gameServerList", list);
			System.out.println(list.size());
		}
	} else if("/userjsp/login.jsp".equals(servletPath)) {
		if(null != list && list.size() > 0 
				&& null == hsRequest.getSession().getAttribute("gameServerList")) {
			hsRequest.getSession().setAttribute("gameServerList", list);
			System.out.println(list.size());
		}
	}
	
	chain.doFilter(request, response);
}
 
Example 7
Project: acmeair-modular   File: RESTCookieSessionFilter.java   View Source Code Vote up 5 votes
@Override
public void doFilter(ServletRequest req, ServletResponse resp,	FilterChain chain) throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest)req;
	HttpServletResponse response = (HttpServletResponse)resp;	
	
	String path = request.getContextPath() + request.getServletPath() + request.getPathInfo();

	
	if (path.endsWith(LOGIN_PATH) || path.endsWith(LOGOUT_PATH) || path.endsWith(LOADDB_PATH)) {
		// if logging in, logging out, or loading the database, let the request flow
		chain.doFilter(req, resp);
		return;
	}
	
	Cookie cookies[] = request.getCookies();
	Cookie sessionCookie = null;

	if (cookies != null) {
		for (Cookie c : cookies) {
			if (c.getName().equals(LoginREST.SESSIONID_COOKIE_NAME)) {
				sessionCookie = c;
			}
			if (sessionCookie!=null)
				break; 
		}
		String sessionId = "";
		if (sessionCookie!=null) // We need both cookie to work
			sessionId= sessionCookie.getValue().trim();
		// did this check as the logout currently sets the cookie value to "" instead of aging it out
		// see comment in LogingREST.java
		if (sessionId.equals("")) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return;
		}
		
		JSONObject jsonObject = authService.validateSession(sessionId);
		if (jsonObject != null) {
			String loginUser=(String) jsonObject.get("customerid");				
			request.setAttribute(LOGIN_USER, loginUser);
			chain.doFilter(req, resp);
			return;
		} else {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return;
		}
	}
	
	// if we got here, we didn't detect the session cookie, so we need to return 404
	response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
 
Example 8
Project: tomcat7   File: TestRestCsrfPreventionFilter2.java   View Source Code Vote up 5 votes
private String getRequestedPath(HttpServletRequest request) {
    String path = request.getServletPath();
    if (request.getPathInfo() != null) {
        path = path + request.getPathInfo();
    }
    return path;
}
 
Example 9
Project: alfresco-remote-api   File: AbstractBaseUrlGenerator.java   View Source Code Vote up 5 votes
public String getServletPath(HttpServletRequest req)
{
	if(overrideServletPath)
	{
		return servletPathOverride;
	}
	else
	{
		return req.getServletPath();
	}
}
 
Example 10
Project: xm-ms-balance   File: TenantInterceptor.java   View Source Code Vote up 5 votes
private boolean isIgnoredRequest(HttpServletRequest request) {
    String path = request.getServletPath();
    List<String> ignoredPatterns = applicationProperties.getTenantIgnoredPathList();
    if (ignoredPatterns != null && path != null) {
        for (String pattern : ignoredPatterns) {
            if (matcher.match(pattern, path)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 11
Project: lams   File: InvokerHttpRequest.java   View Source Code Vote up 5 votes
/**
 * Construct a new wrapped request around the specified servlet request.
 *
 * @param request The servlet request being wrapped
 */
public InvokerHttpRequest(HttpServletRequest request) {

    super(request);
    this.pathInfo = request.getPathInfo();
    this.pathTranslated = request.getPathTranslated();
    this.requestURI = request.getRequestURI();
    this.servletPath = request.getServletPath();

}
 
Example 12
Project: oasp-tutorial-sources   File: CsrfRequestMatcher.java   View Source Code Vote up 5 votes
private String getRequestPath(HttpServletRequest request) {

    String url = request.getServletPath();
    String pathInfo = request.getPathInfo();

    if (pathInfo != null) {
      url += pathInfo;
    }

    return url;
  }
 
Example 13
Project: lazycat   File: HostManagerServlet.java   View Source Code Vote up 5 votes
/**
 * Process a GET request for the specified resource.
 *
 * @param request
 *            The servlet request we are processing
 * @param response
 *            The servlet response we are creating
 *
 * @exception IOException
 *                if an input/output error occurs
 * @exception ServletException
 *                if a servlet-specified error occurs
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

	StringManager smClient = StringManager.getManager(Constants.Package, request.getLocales());

	// Identify the request parameters that we need
	String command = request.getPathInfo();
	if (command == null)
		command = request.getServletPath();
	String name = request.getParameter("name");

	// Prepare our output writer to generate the response message
	response.setContentType("text/plain; charset=" + Constants.CHARSET);
	PrintWriter writer = response.getWriter();

	// Process the requested command
	if (command == null) {
		writer.println(sm.getString("hostManagerServlet.noCommand"));
	} else if (command.equals("/add")) {
		add(request, writer, name, false, smClient);
	} else if (command.equals("/remove")) {
		remove(writer, name, smClient);
	} else if (command.equals("/list")) {
		list(writer, smClient);
	} else if (command.equals("/start")) {
		start(writer, name, smClient);
	} else if (command.equals("/stop")) {
		stop(writer, name, smClient);
	} else {
		writer.println(sm.getString("hostManagerServlet.unknownCommand", command));
	}

	// Finish up the response
	writer.flush();
	writer.close();

}
 
Example 14
Project: lams   File: UrlPathHelper.java   View Source Code Vote up 5 votes
/**
 * Return the servlet path for the given request, detecting an include request
 * URL if called within a RequestDispatcher include.
 * @param request current HTTP request
 * @return the servlet path
 */
public String getOriginatingServletPath(HttpServletRequest request) {
	String servletPath = (String) request.getAttribute(WebUtils.FORWARD_SERVLET_PATH_ATTRIBUTE);
	if (servletPath == null) {
		servletPath = request.getServletPath();
	}
	return servletPath;
}
 
Example 15
Project: acmeair   File: RESTCookieSessionFilter.java   View Source Code Vote up 4 votes
private void doFilter(RequestContext context) throws IOException, ServletException {
	HttpServletRequest request = context.getRequest();

	String path = request.getContextPath() + request.getServletPath();
	if (request.getPathInfo() != null) {
		path = path + request.getPathInfo();
	}
	logger.debug("Get the request path {}", path);
	
	
	if (path.endsWith(LOGIN_PATH) || path.endsWith(LOGOUT_PATH) || path.endsWith(LOADDB_PATH) ||
			path.contains(CONFIG_PATH) || path.contains(LOADER_PATH)) {
		// if logging in, logging out, lookup configuration, or loading the database , let the request flow
		return;
	}
	
	Cookie cookies[] = request.getCookies();
	Cookie sessionCookie = null;
	if (cookies != null) {
		for (Cookie c : cookies) {
			if (c.getName().equals(CustomerSession.SESSIONID_COOKIE_NAME)) {
				sessionCookie = c;
			}
			if (sessionCookie!=null)
				break;
		}
		String sessionId = "";
		if (sessionCookie!=null) // We need both cookie to work
			sessionId= sessionCookie.getValue().trim();
		// did this check as the logout currently sets the cookie value to "" instead of aging it out
		// see comment in LogingREST.java
		if (sessionId.equals("")) {
			logger.warn("Session id is empty");
			setFailedRequest(HttpServletResponse.SC_FORBIDDEN);
			return;
		}
		// Need the URLDecoder so that I can get @ not %40
		CustomerSession cs = getCustomerSession(sessionId);
		if (cs != null) {
			context.addZuulRequestHeader(LOGIN_USER, cs.getCustomerid());
			logger.info("Customer {} validated with session id {}", cs.getCustomerid(), sessionId);
			return;
		}
		else {
			logger.warn("No customer session found with session id {}", sessionId);
			setFailedRequest(HttpServletResponse.SC_FORBIDDEN);
			return;
		}
	}

	logger.warn("No session cookie provided");
	// if we got here, we didn't detect the session cookie, so we need to return 404
	setFailedRequest(HttpServletResponse.SC_FORBIDDEN);

}
 
Example 16
Project: tauren   File: WebUtil.java   View Source Code Vote up 4 votes
/**
 * 获取请求路径
 */
public static String getRequestPath(HttpServletRequest request) {
    String servletPath = request.getServletPath();
    String pathInfo = StringUtils.defaultIfEmpty(request.getPathInfo(), "");
    return servletPath + pathInfo;
}
 
Example 17
Project: logistimo-web-service   File: SecurityFilter.java   View Source Code Vote up 4 votes
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
    throws IOException, ServletException {
  xLogger.fine("Entered doFilter");
  HttpServletRequest req = (HttpServletRequest) request;
  HttpServletResponse resp = (HttpServletResponse) response;
  String servletPath = req.getServletPath();
  if (req.getCharacterEncoding() == null) {
    request.setCharacterEncoding(Constants.UTF8);
  }
  // BACKWARD COMPATIBILITY - in case people have already bookmarked these links
  if ("/index.jsp".equals(servletPath) || "/login.jsp".equals(servletPath)) {
    resp.sendRedirect(isForceNewUI ? HOME_URL_NEW : HOME_URL);
    return;
  }
  SecureUserDetails
      userDetails = null;
  // END BACKWARD COMPATIBILITY
  if (!LOGIN_URL.equals(servletPath) && !AUTHENTICATE_URL.equals(servletPath) && (
      servletPath.isEmpty() || servletPath.equals("/") || servletPath.startsWith("/s/") || (
          servletPath.startsWith(TASK_URL) && StringUtils
              .isBlank(req.getHeader(Constants.X_APP_ENGINE_TASK_NAME))))) {
    userDetails = SecurityMgr
        .getSessionDetails(req.getSession());
    if (userDetails == null) { // session not authenticated yet; direct to login screen
      if (!(servletPath.startsWith(TASK_ADMIN_URL) && ACTION_UPDATESYSCONFIG
          .equals(request.getParameter(ACTION)))) {
        if (isForceNewUI) {
          resp.sendRedirect(HOME_URL_NEW);  // login please
        } else {
          String redirectPath = LOGIN_URL;
          if (servletPath.startsWith("/s/") || servletPath.startsWith(TASK_URL)) {
            String rUrl = servletPath;
            String queryString = req.getQueryString();
            if (queryString != null && !queryString.isEmpty()) {
              rUrl += "?" + queryString;
            }
            redirectPath += "?rurl=" + URLEncoder.encode(rUrl, "UTF-8");
          }
          resp.sendRedirect(redirectPath);  // login please
        }
        return;
      }
    } else {
      String role = userDetails.getRole();
      if (SecurityConstants.ROLE_KIOSKOWNER
          .equals(role)) { // Kiosk owner cannot access this interface
        SessionMgr.cleanupSession(req.getSession());
        resp.sendRedirect(LOGIN_URL + "?status=4");
        return;
      }
      if ((servletPath.contains("/admin/") || servletPath.startsWith(TASK_URL))
          && !SecurityConstants.ROLE_SUPERUSER.equals(role)) { // only superuser can access
        SessionMgr.cleanupSession(req.getSession());
        resp.sendRedirect(LOGIN_URL + "?status=4"); // access denied
        return;
      }

    }
  }
  if (userDetails != null) {
    SecurityUtils.setUserDetails(userDetails);
  }
  try {
    if (filterChain != null) {
      filterChain.doFilter(request, response);
    }
  } finally {
    if (userDetails != null) {
      SecurityUtils.setUserDetails(null);
    }
  }
}
 
Example 18
Project: lemon   File: CmsFilter.java   View Source Code Vote up 4 votes
public void doFilter(ServletRequest req, ServletResponse res,
        FilterChain filterChain) throws ServletException, IOException {
    TenantDTO tenantDto = null;

    try {
        tenantDto = tenantHolder.getTenantDto();
    } catch (Exception ex) {
        filterChain.doFilter(req, res);

        return;
    }

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    logger.debug("requestURI : {}", request.getRequestURI());
    logger.debug("requestURL : {}", request.getRequestURL());
    logger.debug("servletPath : {}", request.getServletPath());
    logger.debug("pathInfo : {}", request.getPathInfo());

    String servletPath = request.getServletPath();

    if (tenantDto.getType() != TenantDTO.TYPE_CMS) {
        if (servletPath.startsWith("/cms/r/")) {
            String path = storeBaseDir + "/" + tenantDto.getId()
                    + cmsBaseDir + servletPath.substring("/cms".length());
            logger.debug("path : {}", path);
            IoUtils.copyFileToOutputStream(path, response.getOutputStream());
        } else {
            filterChain.doFilter(req, res);
        }

        return;
    }

    if ("/portal/index.do".equals(servletPath)) {
        response.sendRedirect(request.getContextPath() + "/index.html");

        return;
    }

    IoUtils.copyFileToOutputStream(storeBaseDir + "/" + tenantDto.getId()
            + cmsBaseDir + servletPath, response.getOutputStream());
}
 
Example 19
Project: oscm   File: UserBean.java   View Source Code Vote up 4 votes
/**
 * Checks if a redirect is required after the successful operation.
 */
String getLoginRedirect(HttpServletRequest httpRequest, HttpSession session,
        boolean successOnEmptyRedirect) {
    VOUserDetails user = getLoggedInUser();

    checkAddSubacription(user);

    if (StringUtils.isNotBlank(requestedRedirect)) {
        confirmedRedirect = requestedRedirect;
    } else if (!successOnEmptyRedirect
            || user.getStatus() == UserAccountStatus.ACTIVE) {
        String relativePath = "";
        if (httpRequest.getServletPath() != null) {
            relativePath += httpRequest.getServletPath();
        }
        if (httpRequest.getPathInfo() != null) {
            relativePath += httpRequest.getPathInfo();
        }
        String queryPart = getServiceDetailsQueryPart(httpRequest,
                getSessionBean());
        relativePath += queryPart;

        confirmedRedirect = relativePath;
    } else {
        confirmedRedirect = null;
    }
    boolean isMPLServiceLogin = !(Constants.REQ_ATTR_LOGIN_TYPE_NO_MPL
            .equals(getServiceLoginType()));
    if (confirmedRedirect != null) {
        if (isMPLServiceLogin) {
            if (!confirmedRedirect
                    .contains(Constants.REQ_ATTR_SERVICE_LOGIN_TYPE)) {
                confirmedRedirect += (confirmedRedirect.contains("?")) ? "&"
                        : "?";
                confirmedRedirect += Constants.REQ_ATTR_SERVICE_LOGIN_TYPE
                        + "=" + getServiceLoginType();
            }
        }
    }

    session.setAttribute(Constants.SESS_ATTR_FORWARD_URL,
            confirmedRedirect);
    if (isPasswordChangeRequired()) {
        // return to screen in AJAX style to show changePWD fields
        return null;
    }
    if (confirmedRedirect == null) {
        return OUTCOME_SUCCESS;
    }
    return OUTCOME_MARKETPLACE_REDIRECT;
}
 
Example 20
Project: xcx-specialty   File: LoginFilter.java   View Source Code Vote up 4 votes
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
	// TODO Auto-generated method stub
			HttpServletRequest req = (HttpServletRequest) request;
			HttpServletResponse res = (HttpServletResponse) response;
			//从SESSION获取对象
			Object obj = req.getSession().getAttribute("user");
			String servletPath = req.getServletPath();
			//System.out.println(obj+"0");
			if(obj != null){
				//System.out.println(obj+"3");
				chain.doFilter(request, response);//请求:我自己定义请求,例外就是页面JS,JSP,HTML
			}else{
				//获取访问的地址
				/**
				 * res.getScheme() 获取访问的协议 http https
				 * res.getServerName() 获取访问的项目名称
				 * res.getServerPort() 获取访问的端口
				 * res.getContextPath();//获取项目名称
				 * res.getServletPath();//实际访问的路径
				 */
				String path = req.getContextPath();
				String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path+"/";
				
				if(servletPath.contains(".")){
					int index = servletPath.lastIndexOf(".");
					String suffix = servletPath.substring(index);
					//System.out.println("suffix:"+suffix);
					if(".js.html.css.jpg.png".contains(suffix)||"/login.html".equals(servletPath)){
						chain.doFilter(request, response);
					}else{//重定向
						System.out.println("重定向");
						res.sendRedirect(basePath);
					}
				}else{//这里是处理我们自己定义请求
					String loginStatus = (String) req.getSession().getAttribute("loginStatus");
					if(loginStatus!=null&&!loginStatus.equals("")&&loginStatus.equals("loginout")){//如果是登出后 刷新原有的页面则需要进行重定向到登录页面
						req.getSession().invalidate();//清除session
						res.sendRedirect(basePath);
					}else{
					//System.out.println(servletPath+"1");
					if(servletPath.contains("login")||servletPath.contains("regist")){
						//System.out.println(req.getServletPath()+"::::::::"+res.getLocale());
						chain.doFilter(request, response);
					}else if(servletPath.contains("ficationCode")||servletPath.contains("regist")){
						chain.doFilter(request, response);
					}else if(servletPath.contains("repassword")||servletPath.contains("regist")){
						chain.doFilter(request, response);
					}else{//重定向
						System.out.println(basePath+"login.html");
						res.sendRedirect(basePath+"login.html");
					}
				    }
				}
			}
	
}