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

The following examples show how to use javax.servlet.http.HttpServletRequest#getServerName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WeixinIndexController.java    From jeewx-boot with Apache License 2.0 7 votes vote down vote up
/**
 * 跳转到欢迎页
 * @return
 * @throws Exception 
 */
@RequestMapping(method = {RequestMethod.GET,RequestMethod.POST})
public void index(HttpServletRequest request,HttpServletResponse response,ModelMap model) throws Exception{
	 try {
		 VelocityContext velocityContext = new VelocityContext();
		 String viewName = "commonweixin/back/main/index.vm";
		 String jwid = request.getParameter("jwid");
		 if(oConvertUtils.isEmpty(jwid)){
			 //throw new BusinessException("商城信息异常");
		 }else{
			 MyJwWebJwid myJwWebJwid= myJwWebJwidService.queryByJwid(jwid);
			 if(myJwWebJwid==null){
				 //throw new BusinessException("商城信息异常");
			 }
			 String userid = (String) request.getSession().getAttribute("system_userid");
			 if(oConvertUtils.isEmpty(userid)){
				 String path = request.getContextPath();
				 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
				 System.out.println("----basePath------"+basePath);
				 response.sendRedirect(basePath+"/system/login.do");
			 }
			 if(userid!=null && myJwWebJwid!=null && !userid.equals(myJwWebJwid.getCreateBy())){
				 //throw new BusinessException("商城信息异常");
			 }
			 velocityContext.put("jwid", jwid);
			 velocityContext.put("userid", userid);
			 velocityContext.put("myJwWebJwid", myJwWebJwid);
			 ViewVelocity.view(request,response,viewName,velocityContext);
			 return;
		 }
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 2
Source File: QuestionPageTeacher.java    From ExamStack with GNU General Public License v2.0 6 votes vote down vote up
@RequestMapping(value = "/teacher/question/question-preview/{questionId}", method = RequestMethod.GET)
public String questionPreviewPage(Model model,
		@PathVariable("questionId") int questionId, HttpServletRequest request){
	String strUrl = "http://" + request.getServerName() //服务器地址  
               + ":"   
               + request.getServerPort() + "/";
	Question question = questionService.getQuestionByQuestionId(questionId);
	List<Integer> idList = new ArrayList<Integer>();
	idList.add(questionId);
	List<QuestionQueryResult> questionQueryList = questionService.getQuestionDescribeListByIdList(idList);
	HashMap<Integer, QuestionQueryResult> questionMap = new HashMap<Integer, QuestionQueryResult>();
	for (QuestionQueryResult qqr : questionQueryList) {
		if (questionMap.containsKey(qqr.getQuestionId())) {
			QuestionQueryResult a = questionMap.get(qqr.getQuestionId());
			questionMap.put(qqr.getQuestionId(), a);
		} else {
			questionMap.put(qqr.getQuestionId(), qqr);
		}
	}
	QuestionAdapter adapter = new QuestionAdapter(question,null,questionMap.get(questionId),strUrl);
	String strHtml = adapter.getStringFromXML(true, false, true);
	model.addAttribute("strHtml", strHtml);
	model.addAttribute("question", question);
	return "question-preview";
}
 
Example 3
Source File: AwsProxyHttpServletRequestTest.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
@Test
public void serverName_hostHeader_returnsHostHeaderOnly() {
    AwsProxyRequestBuilder proxyReq = new AwsProxyRequestBuilder("/test", "GET")
            .header(HttpHeaders.HOST, "testapi.com");
    LambdaContainerHandler.getContainerConfig().addCustomDomain("testapi.com");
    HttpServletRequest servletReq = getRequest(proxyReq, null, null);
    String serverName = servletReq.getServerName();
    assertEquals("testapi.com", serverName);
}
 
Example 4
Source File: QuestionPageTeacher.java    From ExamStack with GNU General Public License v2.0 6 votes vote down vote up
@RequestMapping(value = "/teacher/question/question-preview/{questionId}", method = RequestMethod.GET)
public String questionPreviewPage(Model model,
		@PathVariable("questionId") int questionId, HttpServletRequest request){
	String strUrl = "http://" + request.getServerName() //服务器地址  
               + ":"   
               + request.getServerPort() + "/";
	Question question = questionService.getQuestionByQuestionId(questionId);
	List<Integer> idList = new ArrayList<Integer>();
	idList.add(questionId);
	List<QuestionQueryResult> questionQueryList = questionService.getQuestionDescribeListByIdList(idList);
	HashMap<Integer, QuestionQueryResult> questionMap = new HashMap<Integer, QuestionQueryResult>();
	for (QuestionQueryResult qqr : questionQueryList) {
		if (questionMap.containsKey(qqr.getQuestionId())) {
			QuestionQueryResult a = questionMap.get(qqr.getQuestionId());
			questionMap.put(qqr.getQuestionId(), a);
		} else {
			questionMap.put(qqr.getQuestionId(), qqr);
		}
	}
	QuestionAdapter adapter = new QuestionAdapter(question,null,questionMap.get(questionId),strUrl);
	String strHtml = adapter.getStringFromXML(true, false, true);
	model.addAttribute("strHtml", strHtml);
	model.addAttribute("question", question);
	return "question-preview";
}
 
Example 5
Source File: WechatInterceptor.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 获取当前的url
 *
 * @param controller
 * @return
 */
public static String getGotoUrl(Controller controller) {

    HttpServletRequest req = controller.getRequest();

    // 获取用户将要去的路径
    String queryString = req.getQueryString();

    // 被拦截前的请求URL
    String url = req.getScheme() + "://" + req.getServerName() + req.getRequestURI();
    if (StrUtil.isNotBlank(queryString)) {
        url = url.concat("?").concat(queryString);
    }

    return StrUtil.urlEncode(url);
}
 
Example 6
Source File: LocationSimulatorRestApi.java    From Real-Time-Taxi-Dispatch-Simulator with MIT License 6 votes vote down vote up
private String getKmlUrl(HttpServletRequest request) {

        final String scheme = request.getScheme();
        final String serverName = request.getServerName();
        final int serverPort = request.getServerPort();
        final String contextPath = request.getContextPath();

        StringBuilder url = new StringBuilder();
        url.append(scheme).append("://").append(serverName);

        if ((serverPort != 80) && (serverPort != 443)) {
            url.append(":").append(serverPort);
        }

        url.append(contextPath).append("/api/kml/");
        return url.toString();
    }
 
Example 7
Source File: RequestData.java    From sample.ferret with Apache License 2.0 5 votes vote down vote up
public RequestData(final HttpServletRequest request) {
    method = request.getMethod();
    uri = request.getRequestURI();
    protocol = request.getProtocol();
    servletPath = request.getServletPath();
    pathInfo = request.getPathInfo();
    pathTranslated = request.getPathTranslated();
    characterEncoding = request.getCharacterEncoding();
    queryString = request.getQueryString();
    contentLength = request.getContentLength();
    contentType = request.getContentType();
    serverName = request.getServerName();
    serverPort = request.getServerPort();
    remoteUser = request.getRemoteUser();
    remoteAddress = request.getRemoteAddr();
    remoteHost = request.getRemoteHost();
    remotePort = request.getRemotePort();
    localAddress = request.getLocalAddr();
    localHost = request.getLocalName();
    localPort = request.getLocalPort();
    authorizationScheme = request.getAuthType();
    preferredClientLocale = request.getLocale();
    allClientLocales = Collections.list(request.getLocales());
    contextPath = request.getContextPath();
    userPrincipal = request.getUserPrincipal();
    requestHeaders = getRequestHeaders(request);
    cookies = getCookies(request.getCookies());
    requestAttributes = getRequestAttributes(request);
}
 
Example 8
Source File: ExamPage.java    From ExamStack with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 学员试卷
 * @param model
 * @param request
 * @param examhistoryId
 * @return
 */
@RequestMapping(value = "/student/student-answer-sheet/{examId}", method = RequestMethod.GET)
private String studentAnswerSheetPage(Model model, HttpServletRequest request, @PathVariable int examId) {
	
	UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	ExamHistory history = examService.getUserExamHistByUserIdAndExamId(userInfo.getUserid(), examId, 2, 3);
	int examPaperId = history.getExamPaperId();
	
	String strUrl = "http://" + request.getServerName() // 服务器地址
			+ ":" + request.getServerPort() + "/";
	
	ExamPaper examPaper = examPaperService.getExamPaperById(examPaperId);
	StringBuilder sb = new StringBuilder();
	if(examPaper.getContent() != null && !examPaper.getContent().equals("")){
		Gson gson = new Gson();
		String content = examPaper.getContent();
		List<QuestionQueryResult> questionList = gson.fromJson(content, new TypeToken<List<QuestionQueryResult>>(){}.getType());
		
		for(QuestionQueryResult question : questionList){
			QuestionAdapter adapter = new QuestionAdapter(question,strUrl);
			sb.append(adapter.getStringFromXML());
		}
	}
	
	model.addAttribute("htmlStr", sb);
	model.addAttribute("exampaperid", examPaperId);
	model.addAttribute("examHistoryId", history.getHistId());
	model.addAttribute("exampapername", examPaper.getName());
	model.addAttribute("examId", history.getExamId());
	return "student-answer-sheet";
}
 
Example 9
Source File: RestListenerUtils.java    From iaf with Apache License 2.0 5 votes vote down vote up
public static String retrieveSOAPRequestURL(IPipeLineSession session) throws IOException {
	HttpServletRequest request = (HttpServletRequest) session.get(IPipeLineSession.HTTP_REQUEST_KEY);
	if (request != null) {
		String url = request.getScheme() + "://" + request.getServerName();
		if(!(request.getScheme().equalsIgnoreCase("http") && request.getServerPort() == 80) && !(request.getScheme().equalsIgnoreCase("https") && request.getServerPort() == 443))
			url += ":" + request.getServerPort();
		url += request.getContextPath() + "/services/";
		return url;
	}
	return null;
}
 
Example 10
Source File: WhitelistUtils.java    From knox with Apache License 2.0 5 votes vote down vote up
private static String deriveDefaultDispatchWhitelist(HttpServletRequest request,
                                                     String whitelistTemplate) {
  String defaultWhitelist = null;

  // Check first for the X-Forwarded-Host header, and use it to determine the domain
  String domain = getDomain(request.getHeader("X-Forwarded-Host"));

  // If a domain has still not yet been determined, try the requested host name
  String requestedHost = null;

  if (domain == null) {
    requestedHost = request.getServerName();
    domain = getDomain(requestedHost);
  }

  if (domain != null) {
    defaultWhitelist = defineWhitelistForDomain(domain, whitelistTemplate);
  } else {
    if (!requestedHost.matches(LOCALHOST_REGEXP)) { // localhost will be handled subsequently
      // Use the requested host address/name for the whitelist
      LOG.unableToDetermineKnoxDomainForDefaultWhitelist(requestedHost);
      defaultWhitelist = String.format(Locale.ROOT, whitelistTemplate, requestedHost);
    }
  }

  // If the whitelist has not been determined at this point, default to just the local/relative whitelist
  if (defaultWhitelist == null) {
    LOG.unableToDetermineKnoxDomainForDefaultWhitelist("localhost");
    defaultWhitelist = String.format(Locale.ROOT, whitelistTemplate, LOCALHOST_REGEXP_SEGMENT);
  }

  return defaultWhitelist;
}
 
Example 11
Source File: WebUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Check if the request is a same-origin one, based on {@code Origin}, {@code Host},
 * {@code Forwarded}, {@code X-Forwarded-Proto}, {@code X-Forwarded-Host} and
 * {@code X-Forwarded-Port} headers.
 *
 * <p><strong>Note:</strong> as of 5.1 this method ignores
 * {@code "Forwarded"} and {@code "X-Forwarded-*"} headers that specify the
 * client-originated address. Consider using the {@code ForwardedHeaderFilter}
 * to extract and use, or to discard such headers.

 * @return {@code true} if the request is a same-origin one, {@code false} in case
 * of cross-origin request
 * @since 4.2
 */
public static boolean isSameOrigin(HttpRequest request) {
	HttpHeaders headers = request.getHeaders();
	String origin = headers.getOrigin();
	if (origin == null) {
		return true;
	}

	String scheme;
	String host;
	int port;
	if (request instanceof ServletServerHttpRequest) {
		// Build more efficiently if we can: we only need scheme, host, port for origin comparison
		HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
		scheme = servletRequest.getScheme();
		host = servletRequest.getServerName();
		port = servletRequest.getServerPort();
	}
	else {
		URI uri = request.getURI();
		scheme = uri.getScheme();
		host = uri.getHost();
		port = uri.getPort();
	}

	UriComponents originUrl = UriComponentsBuilder.fromOriginHeader(origin).build();
	return (ObjectUtils.nullSafeEquals(scheme, originUrl.getScheme()) &&
			ObjectUtils.nullSafeEquals(host, originUrl.getHost()) &&
			getPort(scheme, port) == getPort(originUrl.getScheme(), originUrl.getPort()));
}
 
Example 12
Source File: Servlets.java    From jease with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the plain name (without port) of the host serving the given
 * request. If a X-Forwarded-Host-Header is present (e.g. running behind
 * proxy server), it will be returned, otherwise request.getServerName() is
 * returned.
 */
public static String getServerName(HttpServletRequest request) {
	if (request.getHeader("X-Forwarded-Host") != null) {
		return request.getHeader("X-Forwarded-Host");
	} else {
		return request.getServerName();
	}
}
 
Example 13
Source File: ClientIpUtil.java    From oauth2-server with MIT License 5 votes vote down vote up
public static String getServerHost(HttpServletRequest request) {
    String scheme = request.getScheme();
    String serverName = request.getServerName();
    int serverPort = request.getServerPort();
    if (serverPort == 80 || serverPort == 443) {
        return scheme + "://" + serverName;
    } else {
        return scheme + "://" + serverName + ":" + serverPort;
    }
}
 
Example 14
Source File: HttpRequestUtil.java    From charging_pile_cloud with MIT License 5 votes vote down vote up
/**
 * 获取请求路径
 * @return
 */

public static String getReqHttpAndHttpsPath() {
    HttpServletRequest request =getHttpServletRequest();
    String reqUrl = "";
    //获取服务器名,localhost;
    String serverName = request.getServerName();
    //获取服务器端口号,8080;
    Integer serverPort = request.getServerPort();
    reqUrl = "http://" + serverName + ":" + serverPort;
    return reqUrl;
}
 
Example 15
Source File: IndexController.java    From spring-boot-greendogdelivery-casadocodigo with GNU General Public License v3.0 4 votes vote down vote up
@GetMapping("/server")
@ResponseBody
public String server(HttpServletRequest request) {
	return request.getServerName() + ":" + request.getServerPort();
}
 
Example 16
Source File: HstsSuperCookieNewIDServlet.java    From browserprint with MIT License 4 votes vote down vote up
/**
 * Serves requests for hsts[1 to ID_LENGTH].browserprint.info/hstsSuperCookie/newID/*
 * This script applies an given ID to a new client one bit at a time.
 * 
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	int subdomainNumber;
	{
		String subdomain = request.getServerName();
		Matcher domainRegexMatcher = domainRegexPattern.matcher(subdomain);
		if(domainRegexMatcher.matches() == false){
			System.err.println("HstsSuperCookieNewIDServlet: Invalid subdomain <" + subdomain + ">.");
			response.sendError(404);
			return;
		}
		subdomainNumber = Integer.parseInt(domainRegexMatcher.group(1));
	}
	int subdomainGroup = (subdomainNumber - 1) / HstsSuperCookieStartServlet.ID_LENGTH + 1;//1,2,3,4 = 1; 5,6,7,8 = 2; ...
	int subdomainGroupIndex = (subdomainNumber - 1) % HstsSuperCookieStartServlet.ID_LENGTH + 1;//1 = 1; 2 = 2; 3 = 3; 4 = 4; 5 = 1
	
	Matcher pathRegexMatcher = pathRegexPattern.matcher(request.getRequestURI());
	if(pathRegexMatcher.matches() == false){
		System.err.println("HstsSuperCookieNewIDServlet: Invalid path. Must contain valid ID. Path = <" + request.getRequestURI() + ">.");
		response.sendError(404);
		return;
	}
	
	String id = pathRegexMatcher.group(1);
	if(id.charAt(subdomainGroupIndex - 1) == '1'){
		//Enable HSTS so next time the client visits contacts this subdomain it will be using HTTPS.
		response.setHeader("Strict-Transport-Security", "max-age=31622400");
	}
	/*else{//Bit is 0, so don't do anything
	}*/
	
	if(subdomainGroupIndex < HstsSuperCookieStartServlet.ID_LENGTH){
		//Redirect the client to the next subdomain in the chain.
		response.sendRedirect("https://hsts" + (subdomainNumber + 1) + "." + getServletContext().getInitParameter("websiteBaseURL") + response.encodeRedirectURL("/hstsSuperCookie/newID/" + id));
		return;
	}
	else{//subdomainGroupIndex == HstsSuperCookieStartServlet.ID_LENGTH
		//This is the last subdomain in the ID assignment chain, redirect the client for ID extraction.
		response.sendRedirect("https://hsts0." + getServletContext().getInitParameter("websiteBaseURL") + response.encodeRedirectURL("/hstsSuperCookie/midpoint/" + subdomainGroup));
		return;
	}
}
 
Example 17
Source File: SwaggerMappingSupport.java    From swagger with Apache License 2.0 4 votes vote down vote up
private String resolveBaseUrl(HttpServletRequest request) {
    return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + this.urlPrefix;
}
 
Example 18
Source File: PracticePage.java    From ExamStack with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 强化练习
 * @param model
 * @param request
 * @param knowledgePointId
 * @param questionTypeId
 * @return
 */
@RequestMapping(value = "/student/practice-improve/{fieldId}/{knowledgePointId}/{questionTypeId}", method = RequestMethod.GET)
public String practiceImprove(Model model, HttpServletRequest request,
		@PathVariable("fieldId") int fieldId,
		@PathVariable("knowledgePointId") int knowledgePointId,
		@PathVariable("questionTypeId") int questionTypeId) {

	String strUrl = "http://" + request.getServerName() // 服务器地址
			+ ":" + request.getServerPort() + "/";
	List<QuestionQueryResult> qqrList = questionService
			.getQuestionAnalysisListByPointIdAndTypeId(questionTypeId,
					knowledgePointId);
	String questionTypeName = "";
	String fieldName = "";
	try{
		fieldName = qqrList.get(0).getPointName().split(">")[1];
	}catch(Exception e){
		//log.info(e.getMessage());
	}
	
	Map<Integer,QuestionType> questionTypeMap = questionService.getQuestionTypeMap();
	for(Map.Entry<Integer,QuestionType> entry : questionTypeMap.entrySet()){
		
		if(entry.getKey() == questionTypeId){
			questionTypeName = entry.getValue().getName();
			break;
		}	
	}
	int amount = qqrList.size();
	StringBuilder sb = new StringBuilder();
	for(QuestionQueryResult qqr : qqrList){
		QuestionAdapter adapter = new QuestionAdapter(qqr,strUrl);
		sb.append(adapter.getStringFromXML());
	}
	
	model.addAttribute("questionStr", sb.toString());
	model.addAttribute("amount", amount);
	model.addAttribute("fieldName", fieldName);
	model.addAttribute("questionTypeName", questionTypeName);
	model.addAttribute("practiceName", "强化练习");
	model.addAttribute("knowledgePointId", knowledgePointId);
	model.addAttribute("questionTypeId", questionTypeId);
	model.addAttribute("fieldId", fieldId);
	return "practice-improve-qh";
}
 
Example 19
Source File: RequestMonitor.java    From curl with The Unlicense 4 votes vote down vote up
private String serverLocation (final HttpServletRequest request) {
    return request.getScheme () + "://" + request.getServerName () + ":" + RequestMonitor.port ();
}
 
Example 20
Source File: PayUtil.java    From MicroCommunity with Apache License 2.0 2 votes vote down vote up
/**
 * 获取当前工程url
 *
 * @param request
 * @return
 */
public static String getCurrentUrl(HttpServletRequest request) {
    return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
}