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

The following are Jave code examples for showing how to use getServerPort() 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: JavaStudy   File: AuthInterceptorAdapter.java   View Source Code Vote up 11 votes
private boolean forwardToLogin(HttpServletRequest request,
                               HttpServletResponse response) throws ServletException, IOException {
    String url = "http://" + request.getServerName() + ":"
            + request.getServerPort() + request.getContextPath()
            + "/login.jsp";
    response.sendRedirect(url);
    return false;
}
 
Example 2
Project: iotplatform   File: BaseController.java   View Source Code Vote up 7 votes
protected String constructBaseUrl(HttpServletRequest request) {
  String scheme = request.getScheme();
  if (request.getHeader("x-forwarded-proto") != null) {
    scheme = request.getHeader("x-forwarded-proto");
  }
  int serverPort = request.getServerPort();
  if (request.getHeader("x-forwarded-port") != null) {
    try {
      serverPort = request.getIntHeader("x-forwarded-port");
    } catch (NumberFormatException e) {
    }
  }

  String baseUrl = String.format("%s://%s:%d", scheme, request.getServerName(), serverPort);
  return baseUrl;
}
 
Example 3
Project: -Spring-SpringMVC-Mybatis-   File: RequestUtil.java   View Source Code Vote up 7 votes
/**
 * 获取请求basePath
 * @param request
 * @return
 */
public static String getBasePath(HttpServletRequest request) {
	StringBuffer basePath = new StringBuffer();
	String scheme = request.getScheme();
	String domain = request.getServerName();
	int port = request.getServerPort();
	basePath.append(scheme);
	basePath.append("://");
	basePath.append(domain);
	if("http".equalsIgnoreCase(scheme) && 80 != port) {
		basePath.append(":").append(String.valueOf(port));
	} else if("https".equalsIgnoreCase(scheme) && port != 443) {
		basePath.append(":").append(String.valueOf(port));
	}
	return basePath.toString();
}
 
Example 4
Project: social-signin   File: GoogleSignInService.java   View Source Code Vote up 6 votes
public static String generateServletUrl(HttpServletRequest request, String relativePath) {
	String scheme = request.getScheme().toLowerCase();
	String serverName = request.getServerName();
	int serverPort = request.getServerPort();
	String contextPath = request.getContextPath();
	StringBuilder url =  new StringBuilder();
	url.append(scheme).append("://").append(serverName);
	if (("http".equals(scheme) && serverPort != 80) || ("https".equals(scheme) && serverPort != 443)) {
		url.append(":").append(serverPort);
	}
	url.append(contextPath);
	if (!Preconditions.isEmptyString(relativePath)) {
		url.append(relativePath);
	}
	return url.toString();
}
 
Example 5
Project: lambo   File: RequestUtil.java   View Source Code Vote up 6 votes
/**
 * 获取请求basePath
 * @param request
 * @return
 */
public static String getBasePath(HttpServletRequest request) {
	StringBuffer basePath = new StringBuffer();
	String scheme = request.getScheme();
	String domain = request.getServerName();
	int port = request.getServerPort();
	basePath.append(scheme);
	basePath.append("://");
	basePath.append(domain);
	if("http".equalsIgnoreCase(scheme) && 80 != port) {
		basePath.append(":").append(String.valueOf(port));
	} else if("https".equalsIgnoreCase(scheme) && port != 443) {
		basePath.append(":").append(String.valueOf(port));
	}
	return basePath.toString();
}
 
Example 6
Project: validator-web   File: CachingHandler.java   View Source Code Vote up 6 votes
/**
 * Returns the caching key which is based on the servlet path
 * as well as the  cachedPath.
 *
 * @param request
 */
protected String getCachingKey(HttpServletRequest request) {
    StringBuilder absolutePath = new StringBuilder();
    String scheme = request.getScheme();
    int port = request.getServerPort();
    
    absolutePath.append(scheme);
    absolutePath.append("://");
    absolutePath.append(request.getServerName());
    
    if (port > 0 && (("http".equalsIgnoreCase(scheme) && port != 80) || ("https".equalsIgnoreCase(scheme) && port != 443))) {
        absolutePath.append(':');
        absolutePath.append(port);
    }
    
    absolutePath.append(request.getContextPath());
    absolutePath.append(request.getServletPath());
    
    if (request.getPathInfo() != null) {
        absolutePath.append(request.getPathInfo());
    }
    return absolutePath.toString();
}
 
Example 7
Project: shuzheng   File: RequestUtil.java   View Source Code Vote up 6 votes
/**
 * 获取请求basePath
 * @param request
 * @return
 */
public static String getBasePath(HttpServletRequest request) {
	StringBuffer basePath = new StringBuffer();
	String scheme = request.getScheme();
	String domain = request.getServerName();
	int port = request.getServerPort();
	basePath.append(scheme);
	basePath.append("://");
	basePath.append(domain);
	if("http".equalsIgnoreCase(scheme) && 80 != port) {
		basePath.append(":").append(String.valueOf(port));
	} else if("https".equalsIgnoreCase(scheme) && port != 443) {
		basePath.append(":").append(String.valueOf(port));
	}
	return basePath.toString();
}
 
Example 8
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 9
Project: kettle_support_kettle8.0   File: Saved2Request.java   View Source Code Vote up 5 votes
public Saved2Request(HttpServletRequest request, String backUrl) {
	super(request);
	this.scheme = request.getScheme();
	this.domain = request.getServerName();
	this.port = request.getServerPort();
	this.backUrl = backUrl;
	this.contextPath = request.getContextPath();
}
 
Example 10
Project: logistimo-web-service   File: HttpUtil.java   View Source Code Vote up 5 votes
public static String getUrlBase(HttpServletRequest request) {
  if ((request.getServerPort() == 80) || (request.getServerPort() == 443)) {
    return request.getScheme() + "://" + request.getServerName();
  } else {
    return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
  }
}
 
Example 11
Project: apache-tomcat-7.0.73-with-comment   File: TestRemoteIpFilter.java   View Source Code Vote up 5 votes
@Test
public void testIncomingRequestIsSecuredButProtocolHeaderSaysItIsNotWithCustomValues() throws Exception {
    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("protocolHeader", "x-forwarded-proto");
    filterDef.addInitParameter("remoteIpHeader", "x-my-forwarded-for");
    filterDef.addInitParameter("httpServerPort", "8080");

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("192.168.0.10");
    request.setSecure(true);
    request.setScheme("https");
    request.setHeader("x-my-forwarded-for", "140.211.11.130");
    request.setHeader("x-forwarded-proto", "http");

    // TEST
    HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest();

    // VERIFY
    boolean actualSecure = actualRequest.isSecure();
    assertFalse("request must be unsecured as header x-forwarded-proto said it is http", actualSecure);

    String actualScheme = actualRequest.getScheme();
    assertEquals("scheme must be http as header x-forwarded-proto said it is http", "http", actualScheme);

    int actualServerPort = actualRequest.getServerPort();
    assertEquals("wrong http server port", 8080, actualServerPort);

    String actualRemoteAddr = actualRequest.getRemoteAddr();
    assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr);

    String actualRemoteHost = actualRequest.getRemoteHost();
    assertEquals("remoteHost", "140.211.11.130", actualRemoteHost);
}
 
Example 12
Project: Mastering-Java-EE-Development-with-WildFly   File: ReadClient.java   View Source Code Vote up 5 votes
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	response.setContentType("text/html;charset=UTF-8");
	try (PrintWriter out = response.getWriter()) {
		out.println("<html>");
		out.println("<head>");
		out.println("<title>Invoke the servlet clients</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<h1>Invoke the servlet clients</h1>");

		String path = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()
				+ "/WritingServlet";
		out.println("Invoking the endpoint: " + path + "<br>");
		out.flush();
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		try (BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
			out.println("Sending data ..." + "<br>");
			out.flush();
			out.println(input.readLine());
			out.println("Sleeping ..." + "<br>");
			out.flush();
			sleep(5000);
			out.println("Sending more data ..." + "<br>");
			out.flush();
			out.println(input.readLine());
			input.close();
		}
		out.println("<br><br>Check server.log for output");
		out.println("</body>");
		out.println("</html>");
	} catch (InterruptedException | IOException ex) {
		logger.log(SEVERE, null, ex);
	}
}
 
Example 13
Project: sso-client   File: Urls.java   View Source Code Vote up 5 votes
public static String getServerBaseUrl(final HttpServletRequest request){
    String schema=request.getHeader("x-forwarded-proto");
    if(schema==null || "".equals(schema)){
        schema=request.getScheme();
    }
    schema+="://";
    String host =request.getHeader("x-forwarded-host");
    if(host==null || "".equals(host)){
        host=request.getServerName() + ":" + request.getServerPort();
    }
    String url=schema+host;
    url=regularUrl(url);

    return url;
}
 
Example 14
Project: tomcat7   File: RemoteIpFilter.java   View Source Code Vote up 5 votes
public XForwardedRequest(HttpServletRequest request) {
    super(request);
    this.localPort = request.getLocalPort();
    this.remoteAddr = request.getRemoteAddr();
    this.remoteHost = request.getRemoteHost();
    this.scheme = request.getScheme();
    this.secure = request.isSecure();
    this.serverPort = request.getServerPort();
    
    headers = new HashMap<String, List<String>>();
    for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) {
        String header = headerNames.nextElement();
        headers.put(header, Collections.list(request.getHeaders(header)));
    }
}
 
Example 15
Project: web-framework-for-java   File: HttpHelper.java   View Source Code Vote up 4 votes
public static String getRootUrl(HttpServletRequest request) {
	return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
}
 
Example 16
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");
					}
				    }
				}
			}
	
}
 
Example 17
Project: opencron   File: WebUtils.java   View Source Code Vote up 4 votes
public static String getWebUrlPath(HttpServletRequest request) {
    String port = request.getServerPort() == 80 ? "" : (":"+request.getServerPort());
    String path = request.getContextPath().replaceAll("/$","");
    return request.getScheme()+"://"+request.getServerName()+port+path;
}
 
Example 18
Project: spring-boot-greendogdelivery-casadocodigo   File: IndexController.java   View Source Code Vote up 4 votes
@GetMapping("/oferta")
@ResponseBody
public MensagemDTO getMessage(HttpServletRequest request) {
    return new MensagemDTO(this.message,request.getServerName() + ":" + request.getServerPort(),this.debug);
}
 
Example 19
Project: csap-core   File: CorePortals.java   View Source Code Vote up 4 votes
@RequestMapping ( CsapCoreService.MAINSERVICES_URL )
public String applicationPortal (	ModelMap modelMap, HttpServletRequest request, HttpSession session,
									@RequestParam ( value = CSAP.PACKAGE_PARAM , required = false ) String releasePackage,
									@CookieValue ( value = "JSESSIONID" , required = false ) String cookie ) {

	if ( logger.isDebugEnabled() ) {
		logger.debug( " Entered" );
	}

	if ( Application.isJvmInManagerMode() && request.getServerPort() == 443
			&& cookie == null ) {
		// Hook for switching admin into https mode this is only needed when
		// admin is
		// running in secure mode. Jsessionids will NOT be set in http,
		// therefore we
		// redirect to the url.
		// logger.debug("Redirecting to https") ;

		// This might look like a infinite loop, but when secure mode is
		// configured the requestUrl will
		// have the https in front as it is configured in server.xml, it
		// does NOT come from the request
		// response.sendRedirect(request.getRequestURL().toString());
		return "redirect:" + request.getRequestURL()
			.toString();
	}

	setCommonAttributes( modelMap, session );

	if ( !request.getServerName().contains( "." ) ) {
		String fqdn = "LB Url not found in lifecycle settings";
		try {
			String lb = application.lifeCycleSettings().getLbServer();
			String dn = request.getServerName()
					+ lb.substring( lb.indexOf( "." ) );
			fqdn = request.getRequestURL().toString().replace( request.getServerName(), dn );
		} catch (Exception e) {
			logger.warn( "Failed to find LB settings" );
		}

		modelMap.addAttribute( "domainUrl", fqdn );
	}

	addSelectedReleasePackage( modelMap, releasePackage );

	if ( releasePackage == null ) {
		//
		if ( Application.isJvmInManagerMode()
				&& application.getRootModel()
					.getReleaseModelCount() > 1 ) {
			return "/deployment/package-select";
		}

		releasePackage = application.getActiveModelName();
	}

	return "/deployment/service-body";
}
 
Example 20
Project: angit   File: WebHelper.java   View Source Code Vote up 2 votes
/**
 * 获取访问路径
 *
 * @param request HttpServletRequest
 * @return 访问路径 base url
 */
public static String getBaseURL(HttpServletRequest request) {
    String path = request.getContextPath();
    return request.getScheme() + "://"
        + request.getServerName() + ":" + request.getServerPort() + path + "/";
}