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

The following are Jave code examples for showing how to use getServerName() 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: -Spring-SpringMVC-Mybatis-   File: RequestUtil.java   View Source Code Vote up 8 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 2
Project: netty-socketio-demo   File: WebUtils.java   View Source Code Vote up 6 votes
/**
 * 得到项目根路径(形如: http://bridgeli.cn/)
 * 
 * @param request
 * @return
 */
public static String getWebRoot(HttpServletRequest request) {
    // 得到协议如:http
    String scheme = request.getScheme();
    // 得到服务器名称如:127.0.0.1
    String serverName = request.getServerName();
    // 得到端口号如8080
    int serverPort = request.getServerPort();
    // 得到当前上下文路径,也就是安装后的文件夹位置。
    String contextPath = request.getContextPath();
    // 连起来拼成完整的url
    StringBuffer sb = new StringBuffer();
    sb.append(scheme);
    sb.append("://");
    sb.append(serverName);
    if (80 != serverPort) {
        sb.append(":");
        sb.append(serverPort);
    }
    sb.append(contextPath);
    sb.append("/");
    return sb.toString();
}
 
Example 3
Project: rure   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 4
Project: JavaStudy   File: AuthInterceptorAdapter.java   View Source Code Vote up 5 votes
private boolean redirect(HttpServletRequest request, HttpServletResponse response){
        String url = "http://" + request.getServerName() + ":"
                + request.getServerPort() + request.getContextPath();
        try {
//            request.getSession().setAttribute("redirect",request.getServletPath());
            response.sendRedirect(url);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
 
Example 5
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 6
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 7
Project: framework   File: RequestUtils.java   View Source Code Vote up 5 votes
/**
 * 获取Http请求的完整路径,包括参数
 *
 * @param request
 * @return
 */
public static String getFullURL(HttpServletRequest request) {
	String url = "";
	url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getServletPath();
	if (request.getQueryString() != null) {
		url += "?" + request.getQueryString();
	}
	return url;
}
 
Example 8
Project: apache-tomcat-7.0.73-with-comment   File: CorsFilter.java   View Source Code Vote up 5 votes
private boolean isLocalOrigin(HttpServletRequest request, String origin) {

        // Build scheme://host:port from request
        StringBuilder target = new StringBuilder();
        String scheme = request.getScheme();
        if (scheme == null) {
            return false;
        } else {
            scheme = scheme.toLowerCase(Locale.ENGLISH);
        }
        target.append(scheme);
        target.append("://");

        String host = request.getServerName();
        if (host == null) {
            return false;
        }
        target.append(host);

        int port = request.getServerPort();
        if ("http".equals(scheme) && port != 80 ||
                "https".equals(scheme) && port != 443) {
            target.append(':');
            target.append(port);
        }

        return origin.equalsIgnoreCase(target.toString());
    }
 
Example 9
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 10
Project: ditb   File: HMaster.java   View Source Code Vote up 5 votes
@Override
public void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
  String redirectUrl = request.getScheme() + "://"
    + request.getServerName() + ":" + regionServerInfoPort
    + request.getRequestURI();
  response.sendRedirect(redirectUrl);
}
 
Example 11
Project: ctsms   File: WebUtil.java   View Source Code Vote up 5 votes
public static String getApplicationRootUrl() {
	try {
		HttpServletRequest request = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest());
		URL reconstructedUrl = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), "");
		return reconstructedUrl.toString();
	} catch (Exception e) {
		return getHttpBaseUrl();
	}
}
 
Example 12
Project: DWSurvey   File: MyCollectAction.java   View Source Code Vote up 5 votes
@Override
public String execute() throws Exception {
	HttpServletRequest request=Struts2Utils.getRequest();
	String tabId=request.getParameter("tabId");

	String baseUrl = "";
	baseUrl = request.getScheme() +"://" + request.getServerName()  
					+ (request.getServerPort() == 80 ? "" : ":" +request.getServerPort())
                       + request.getContextPath();

	request.setAttribute("baseUrl", baseUrl);

	User user=accountManager.getCurUser();
   	if(user!=null){
   		SurveyDirectory surveyDirectory=surveyDirectoryManager.getSurveyByUser(surveyId, user.getId());
   		if(surveyDirectory!=null){
   			request.setAttribute("survey", surveyDirectory);
   			if(IFRAME.equals(tabId)){
   				return IFRAME;
   			}else if(SITECOMP.equals(tabId)){
   				return SITECOMP;
   			}else if(WEIXIN.equals(tabId)){
   				return WEIXIN;
   			}else if(SHARE.equals(tabId)){
   				return SHARE;
   			}
   			return COLLECT1;
   		}
   	}
	return null;
}
 
Example 13
Project: supervisor   File: LoginFilter.java   View Source Code Vote up 5 votes
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
	String requestURI = request.getRequestURI();
	LOG.debug("filt uri : " + requestURI);
	
	requestURI = requestURI.replaceAll("/+", "/");
	if (requestURI.equals("/")||requestURI.startsWith("/resources")|| requestURI.equals("/home/auth")) {
		filterChain.doFilter(request, response);
		return;
	}
	String path = request.getContextPath();
	this.basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
	
	HttpSession session = request.getSession();
	
	User user=(User) session.getAttribute("curUser");
	if(null==user){
		java.io.PrintWriter out = response.getWriter();
	    out.println("<html>");
	    out.println("<script>");
	    out.println("window.open ('"+basePath+"','_top')");
	    out.println("</script>");
	    out.println("</html>");
	}else{
		filterChain.doFilter(request, response);
		return;
	}
}
 
Example 14
Project: jsr375-extensions   File: OAuth2ServiceFactory.java   View Source Code Vote up 5 votes
protected String assembleCallbackUrl(HttpServletRequest request) {
    return request.getScheme() + "://" +
            request.getServerName() +
            getServerPort(request) +
            request.getContextPath();

}
 
Example 15
Project: jerrydog   File: BasicAuthenticator.java   View Source Code Vote up 4 votes
/**
 * Authenticate the user making this request, based on the specified
 * login configuration.  Return <code>true</code> if any specified
 * constraint has been satisfied, or <code>false</code> if we have
 * created a response challenge already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param login Login configuration describing how authentication
 *              should be performed
 *
 * @exception IOException if an input/output error occurs
 */
public boolean authenticate(HttpRequest request,
                            HttpResponse response,
                            LoginConfig config)
    throws IOException {

    // Have we already authenticated someone?
    Principal principal =
        ((HttpServletRequest) request.getRequest()).getUserPrincipal();
    if (principal != null) {
        if (debug >= 1)
            log("Already authenticated '" + principal.getName() + "'");
        return (true);
    }

    // Validate any credentials already included with this request
    HttpServletRequest hreq =
        (HttpServletRequest) request.getRequest();
    HttpServletResponse hres =
        (HttpServletResponse) response.getResponse();
    String authorization = request.getAuthorization();
    String username = parseUsername(authorization);
    String password = parsePassword(authorization);
    principal = context.getRealm().authenticate(username, password);
    if (principal != null) {
        register(request, response, principal, Constants.BASIC_METHOD,
                 username, password);
        return (true);
    }

    // Send an "unauthorized" response and an appropriate challenge
    String realmName = config.getRealmName();
    if (realmName == null)
        realmName = hreq.getServerName() + ":" + hreq.getServerPort();
//        if (debug >= 1)
//            log("Challenging for realm '" + realmName + "'");
    hres.setHeader("WWW-Authenticate",
                   "Basic realm=\"" + realmName + "\"");
    hres.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    //      hres.flushBuffer();
    return (false);

}
 
Example 16
Project: jerrydog   File: DigestAuthenticator.java   View Source Code Vote up 4 votes
/**
 * Generates the WWW-Authenticate header.
 * <p>
 * The header MUST follow this template :
 * <pre>
 *      WWW-Authenticate    = "WWW-Authenticate" ":" "Digest"
 *                            digest-challenge
 *
 *      digest-challenge    = 1#( realm | [ domain ] | nOnce |
 *                  [ digest-opaque ] |[ stale ] | [ algorithm ] )
 *
 *      realm               = "realm" "=" realm-value
 *      realm-value         = quoted-string
 *      domain              = "domain" "=" <"> 1#URI <">
 *      nonce               = "nonce" "=" nonce-value
 *      nonce-value         = quoted-string
 *      opaque              = "opaque" "=" quoted-string
 *      stale               = "stale" "=" ( "true" | "false" )
 *      algorithm           = "algorithm" "=" ( "MD5" | token )
 * </pre>
 *
 * @param request HTTP Servlet request
 * @param resonse HTTP Servlet response
 * @param login Login configuration describing how authentication
 *              should be performed
 * @param nOnce nonce token
 */
protected void setAuthenticateHeader(HttpServletRequest request,
                                     HttpServletResponse response,
                                     LoginConfig config,
                                     String nOnce) {

    // Get the realm name
    String realmName = config.getRealmName();
    if (realmName == null)
        realmName = request.getServerName() + ":"
            + request.getServerPort();

    byte[] buffer = md5Helper.digest(nOnce.getBytes());

    String authenticateHeader = "Digest realm=\"" + realmName + "\", "
        +  "qop=\"auth\", nonce=\"" + nOnce + "\", " + "opaque=\""
        + md5Encoder.encode(buffer) + "\"";
    // System.out.println("Authenticate header value : "
    //                   + authenticateHeader);
    response.setHeader("WWW-Authenticate", authenticateHeader);

}
 
Example 17
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 18
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 19
Project: Your-Microservice   File: YourServletUriComponentsBuilder.java   View Source Code Vote up 4 votes
/**
 * Prepare a builder by copying the scheme, host, port, path, and
 * query string of an HttpServletRequest.
 * @param request to build path from
 * @return a URI component builder
 */
public static YourServletUriComponentsBuilder fromRequest(HttpServletRequest request) {
    String scheme = request.getScheme();
    String host = request.getServerName();
    int port = request.getServerPort();

    String hostHeader = request.getHeader("X-Forwarded-Host");
    if (StringUtils.hasText(hostHeader)) {
        String[] hosts = StringUtils.commaDelimitedListToStringArray(hostHeader);
        String hostToUse = hosts[0];
        if (hostToUse.contains(":")) {
            String[] hostAndPort = StringUtils.split(hostToUse, ":");
            host  = hostAndPort[0];
            port = Integer.parseInt(hostAndPort[1]);
        }
        else {
            host = hostToUse;
            port = -1;
        }
    }

    String portHeader = request.getHeader("X-Forwarded-Port");
    if (StringUtils.hasText(portHeader)) {
        port = Integer.parseInt(portHeader);
    }

    String protocolHeader = request.getHeader("X-Forwarded-Proto");
    if (StringUtils.hasText(protocolHeader)) {
        scheme = protocolHeader;
    }

    YourServletUriComponentsBuilder builder = new YourServletUriComponentsBuilder();
    builder.scheme(scheme);
    builder.host(host);
    if (scheme.equals("http") && port != 80 || scheme.equals("https") && port != 443) {
        builder.port(port);
    }
    builder.pathFromRequest(request);
    builder.query(request.getQueryString());
    return builder;
}
 
Example 20
Project: appinventor-extensions   File: Server.java   View Source Code Vote up 2 votes
/**
 * Returns URL built by appending path to the current server and the server
 * port and base URL.
 *
 * @param req HTTP request
 * @param path requested path
 * @return build URL
 */
public static String urlFromPath(HttpServletRequest req, String path) {
  // TODO(user): omit the port if it is the default port for a schema
  return req.getScheme() + "://" + req.getServerName() + ':' + req.getServerPort()
      + ServerLayout.ODE_BASEURL + path;
}