下面列出了javax.servlet.http.HttpServletRequest#getServerName() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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";
}
@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";
}
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();
}
/**
* 获取当前的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);
}
/**
* 跳转到欢迎页
* @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();
}
}
@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);
}
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);
}
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;
}
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;
}
/**
* 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();
}
}
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;
}
}
/**
* 获取请求路径
* @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;
}
/**
* 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()));
}
/**
* 学员试卷
* @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";
}
private String serverLocation (final HttpServletRequest request) {
return request.getScheme () + "://" + request.getServerName () + ":" + RequestMonitor.port ();
}
/**
* 强化练习
* @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";
}
private String resolveBaseUrl(HttpServletRequest request) {
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + this.urlPrefix;
}
/**
* 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;
}
}
@GetMapping("/server")
@ResponseBody
public String server(HttpServletRequest request) {
return request.getServerName() + ":" + request.getServerPort();
}
/**
* 获取当前工程url
*
* @param request
* @return
*/
public static String getCurrentUrl(HttpServletRequest request) {
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
}