Пример #1
0
 /* 发送trace日志到总线上 */
 private void sendTrace(HttpServletRequest req, TraceContext c, BufferedResponseWrapper res) {
   AccessBean b = new AccessBean();
   b.setStamp(FilterHelpers.getRequestTime(req));
   b.setCost((int) FilterHelpers.getCostTime(req));
   b.setTraceId(c.getTraceId());
   b.setRpcId(c.getParentRpcId());
   b.setClientIp(getRemoteIp(req));
   b.setServerIp(ConfigHelper.getServerInnerIP());
   b.setProfile(ConfigHelper.getProcessInfo().getProfile());
   b.setCode(res.getStatus());
   b.setSize(res.getLength());
   b.setReferer(req.getHeader("Referer"));
   b.setUserAgent(req.getHeader("User-Agent"));
   b.setCookie(req.getHeader("Cookie"));
   b.setUid(FilterHelpers.getUserId(req));
   String url = req.getServerName();
   if (req.getServerPort() != 80) {
     url += ':' + req.getServerPort();
   }
   if (req.getQueryString() != null) {
     url += '?' + req.getQueryString();
   }
   b.setUrl(url);
   Message m = new Message("JinJingAccess", c.getTraceId(), JSON.toJSONBytes(b));
   RocketMqSender.getInstance().asyncSend(m);
 }
  protected void redirectToAuthorisationPage(
      HttpServletRequest req,
      HttpServletResponse resp,
      ParameterList requestParameters,
      OpenIDServerBean serverBean)
      throws IOException {
    String URL =
        req.getScheme()
            + "://"
            + req.getServerName()
            + (req.getServerPort() != 80 ? ":" + req.getServerPort() : "")
            + req.getRequestURI();
    String queryString = req.getQueryString();
    if (queryString != null) {
      URL += "?" + queryString;
    }
    serverBean.setServerUrl(URL);
    serverBean.setParameterList(requestParameters);

    String authenticateURL =
        IWMainApplication.getDefaultIWApplicationContext()
            .getApplicationSettings()
            .getProperty(
                OpenIDConstants.PROPERTY_AUTHENTICATION_URL,
                "http://www.elykill.is/pages/profile/mypage/authenticate/");

    resp.sendRedirect(authenticateURL);
  }
Пример #3
0
 // 获得测试主机信息
 @GetMapping(value = "/getHostInfo", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
 @ResponseBody
 public String getHostInfo(HttpServletRequest request, HttpServletResponse response) {
   JSONObject jo = new JSONObject();
   String path = request.getContextPath();
   String basePath = null;
   try {
     InetAddress addr = InetAddress.getLocalHost();
     basePath =
         request.getScheme()
             + "://"
             + addr.getHostAddress()
             + ":"
             + request.getServerPort()
             + path
             + "/";
   } catch (UnknownHostException e) {
     basePath =
         request.getScheme()
             + "://"
             + request.getServerName()
             + ":"
             + request.getServerPort()
             + path
             + "/";
   }
   jo.put("host", basePath);
   return jo.toString();
 }
Пример #4
0
  public String toString() {
    HttpServletRequest request = Context.get().getRequest();

    StringBuilder stringBuilder = new StringBuilder();
    if (!(page != null && page.toLowerCase().startsWith("http"))) {
      if (!secure) stringBuilder.append("http://");
      else stringBuilder.append("https://");

      if (Utils.isNotNull(WEB_SERVER_HOST)) stringBuilder.append(WEB_SERVER_HOST);
      else stringBuilder.append(request.getServerName());

      if (!secure && WEB_SERVER_HTTP_PORT != 0 && WEB_SERVER_HTTP_PORT != 80) {
        stringBuilder.append(":");
        stringBuilder.append(WEB_SERVER_HTTP_PORT);
      } else if (secure && WEB_SERVER_HTTPS_PORT != 0 && WEB_SERVER_HTTPS_PORT != 443) {
        stringBuilder.append(":");
        stringBuilder.append(WEB_SERVER_HTTPS_PORT);
      } else if (request.getServerPort() != 80) {
        stringBuilder.append(":");
        stringBuilder.append(request.getServerPort());
      }
    }
    stringBuilder.append(page);

    encodeParameters(stringBuilder);

    return stringBuilder.toString();
  }
Пример #5
0
  private String getVtiUrl(HttpServletRequest request) {
    String url = request.getScheme() + "://" + request.getServerName();
    if (request.getServerPort() != 80 && request.getServerPort() != 443) {
      url += ":" + request.getServerPort();
    }
    url += "/" + sysAdminParams.getAlfrescoContext() + "/";

    return url;
  }
Пример #6
0
 private String getContextPath(HttpServletRequest request) {
   if (contextPath != null) return contextPath;
   String port =
       request.getServerPort() == 80 || request.getServerPort() == 0
           ? ""
           : ":" + request.getServerPort();
   contextPath =
       request.getScheme() + "://" + request.getServerName() + port + request.getContextPath();
   return contextPath;
 }
Пример #7
0
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.getWriter().print(request.getScheme() + "<br/>"); // 获取请求协议
   response.getWriter().print(request.getServerName() + "<br/>"); // 获取服务器名称
   response.getWriter().print(request.getServerPort() + "<br/>"); // 获取服务器端口号
   response.getWriter().print(request.getContextPath() + "<br/>"); // 获取项目名称
   response.getWriter().print(request.getServerPort() + "<br/>"); // 获取servlet路径
   response.getWriter().print(request.getQueryString() + "<br/>"); // 获取参数部分
   response.getWriter().print(request.getRequestURI() + "<br/>"); // 获取请求URI
   response.getWriter().print(request.getRequestURL() + "<br/>"); // 获取请求URL
 }
Пример #8
0
 /**
  * NOT UNIT TESTED Returns the base url (e.g, <tt>http://myhost:8080/myapp</tt>) suitable for
  * using in a base tag or building reliable urls.
  */
 public static String getBaseUrl(HttpServletRequest request) {
   if ((request.getServerPort() == 80) || (request.getServerPort() == 443))
     return request.getScheme() + "://" + request.getServerName() + request.getContextPath();
   else
     return request.getScheme()
         + "://"
         + request.getServerName()
         + ":"
         + request.getServerPort()
         + request.getContextPath();
 }
Пример #9
0
 /**
  * get server context
  *
  * @return
  */
 private String getServerContext() {
   HttpServletRequest request = getServletRequest();
   final StringBuilder serverPath = new StringBuilder();
   serverPath.append(request.getScheme() + "://");
   serverPath.append(request.getServerName());
   if (request.getServerPort() != 80) {
     serverPath.append(":" + request.getServerPort());
   }
   serverPath.append(request.getContextPath());
   return serverPath.toString();
 }
Пример #10
0
 private String calculateBaseUrl() {
   HttpServletRequest request = RequestContext.getCurrent().getRequest();
   return request.getScheme()
       + "://"
       + request.getServerName()
       + ("http".equals(request.getScheme()) && request.getServerPort() == 80
               || "https".equals(request.getScheme()) && request.getServerPort() == 443
           ? ""
           : ":" + request.getServerPort())
       + request.getContextPath();
 }
Пример #11
0
 /**
  * Returns current deployment root with port (if required) for using as label link, for example.
  *
  * @return current deployment root with port, e.g. "http://myhost.com:8080/myforum" or
  *     "http://myhost.com/myforum"
  */
 protected String getDeploymentRootUrl(HttpServletRequest request) {
   StringBuilder urlBuilder =
       new StringBuilder()
           .append(request.getScheme())
           .append("://")
           .append(request.getServerName());
   if (request.getServerPort() != 80) {
     urlBuilder.append(":").append(request.getServerPort());
   }
   urlBuilder.append(request.getContextPath());
   return urlBuilder.toString();
 }
 // This code is heavily inspired by the stuff in HttpUtils.getRequestURL
 private String getUrlPrefix(HttpServletRequest req) {
   StringBuffer url = new StringBuffer();
   String scheme = req.getScheme();
   int port = req.getServerPort();
   url.append(scheme); // http, https
   url.append("://");
   url.append(req.getServerName());
   if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443)) {
     url.append(':');
     url.append(req.getServerPort());
   }
   return url.toString();
 }
Пример #13
0
  public String login() {
    LoginLogic loginLogic = super.getInstance(LoginLogic.class);
    String ip = servletRequest.getRemoteAddr();

    log.debug("User ({}) tries to login from {}...", username, ip);

    boolean validePass;
    try {
      validePass = loginLogic.checkLogin(username, password, ip);
    } catch (Throwable e) {
      addFieldError("loginError", "登录失败!");
      log.debug("login failed");
      return INPUT;
    }

    if (validePass) {
      Map<String, Object> session = ActionContext.getContext().getSession();
      UserForm userForm = new UserForm();
      userForm.setUserName(username);
      SimpleUserSession userSession = new SimpleUserSession(userForm, true);
      session.put(SessionConstant.USER_SESSION, userSession);

      log.debug("login success");
      if (!Tools.isEmptyString(backUrl)) {
        HttpServletRequest request = ServletActionContext.getRequest();
        StringBuffer callBack = new StringBuffer();
        callBack
            .append(request.getScheme())
            .append("://")
            .append(request.getServerName())
            .append((request.getServerPort() == 80 ? "" : ":" + request.getServerPort()))
            .append(request.getContextPath());
        callBack.append(backUrl);
        try {
          ServletActionContext.getResponse().sendRedirect(callBack.toString());
        } catch (IOException e) {
          log.error(e.getMessage(), e);
          return SUCCESS;
        }
        return null;
      }

      return SUCCESS;
    } else {
      addFieldError("loginError", "用户名或密码错误");
      log.debug("login failed");
      return INPUT;
    }
  }
Пример #14
0
 private String getCodebase(HttpServletRequest request) {
   StringBuffer codebaseBuffer = new StringBuffer();
   String forwardProto = request.getHeader("X-Forwarded-Proto");
   boolean secure =
       (forwardProto != null && forwardProto.toLowerCase().equals("https")) || request.isSecure();
   codebaseBuffer.append(secure ? "https://" : "http://");
   codebaseBuffer.append(request.getServerName());
   if (request.getServerPort() != (!secure ? 80 : 443)) {
     codebaseBuffer.append(':');
     codebaseBuffer.append(request.getServerPort());
   }
   codebaseBuffer.append(request.getContextPath());
   codebaseBuffer.append('/');
   return codebaseBuffer.toString();
 }
Пример #15
0
  public static String getAppURL() {
    HttpServletRequest request =
        (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    StringBuilder url = new StringBuilder();
    url.append(request.getScheme());
    url.append("://");
    url.append(request.getServerName());
    if (request.getServerPort() > 0) {
      url.append(':');
      url.append(request.getServerPort());
    }

    url.append(request.getContextPath());
    return url.toString();
  }
Пример #16
0
  public CopyOfExportTask(
      String connectUrls,
      String queryProcedure,
      Map<String, String> params,
      String resultProcedure,
      HttpServletRequest request) {
    this.connectUrls = connectUrls;

    this.params = new HashMap<String, String>();
    Object[] keys = params.keySet().toArray();
    this.keys = new String[keys.length];
    for (int i = 0; i < keys.length; i++) { // 把map里所有key转成小写,与执行的存储过程保持一致
      String key = keys[i].toString();
      this.keys[i] = key.toLowerCase();
      this.params.put(key.toLowerCase(), MapUtils.getString(params, key, ""));
    }
    this.queryProcedure = handleSql(queryProcedure.toLowerCase(), this.params);
    this.resultProcedure = resultProcedure.toLowerCase();
    this.fileName =
        MapUtils.getString(params, "modulename", "导出文件")
            + "_"
            + new SimpleDateFormat(Constant.TIMESTAMP_FORMAT_yyyyMMddHHmmssSSS).format(new Date())
            + Constant.EXCEL;
    this.ip = request.getServerName();
    this.port = request.getServerPort();
    this.filePath =
        request.getRealPath(Constant.EXPORT_PATH_FOLDER) + File.separatorChar + this.fileName;
    this.jt = DBUtil.getReadJdbcTemplate(this.connectUrls);
  }
Пример #17
0
 private String getAppUrl(HttpServletRequest request) {
   return "http://"
       + request.getServerName()
       + ":"
       + request.getServerPort()
       + request.getContextPath();
 }
Пример #18
0
  // callRestfulApi - Calls restful API and returns results as a string
  public String callRestfulApi(
      String addr, HttpServletRequest request, HttpServletResponse response) {
    if (localCookie) CookieHandler.setDefault(cm);

    try {
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      URL url = new URL(API_ROOT + addr);
      URLConnection urlConnection = url.openConnection();
      String cookieVal = getBrowserInfiniteCookie(request);
      if (cookieVal != null) {
        urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
      }
      IOUtils.copy(urlConnection.getInputStream(), output);
      String newCookie = getConnectionInfiniteCookie(urlConnection);
      if (newCookie != null && response != null) {
        setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
      }
      return output.toString();
    } catch (IOException e) {
      System.out.println(e.getMessage());
      return null;
    }
  } // TESTED
Пример #19
0
  private void handleRequest(final HttpServletRequest req, final HttpServletResponse resp)
      throws IOException {
    try {
      final URI referer = new URI(req.getHeader("referer")); // $NON-NLS-1$
      if (!referer.getHost().equals(req.getServerName())
          || referer.getPort() != req.getServerPort()
          || !referer.getPath().startsWith(req.getContextPath())) {
        throw new Exception();
      }
    } catch (final Exception e) {
      resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      return;
    }

    final String command = req.getPathInfo();
    if (command != null && command.equals("/openFile")) { // $NON-NLS-1$
      execOpenFile(req, resp);
      resp.setHeader(
          "Cache-Control", "no-store, no-cache, must-revalidate"); // $NON-NLS-1$ //$NON-NLS-2$
      return;
    }

    resp.sendError(
        HttpServletResponse.SC_BAD_REQUEST, "Unsupported command: " + command); // $NON-NLS-1$
    return;
  }
Пример #20
0
  private void sendSourceMap(
      String moduleName, HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    long startTime = System.currentTimeMillis();

    ModuleState moduleState = modules.get(moduleName);
    File sourceMap = moduleState.findSourceMap();

    // Stream the file, substituting the sourceroot variable with the filename.
    // (This is more efficient than parsing the file as JSON.)

    // We need to do this at runtime because we don't know what the hostname will be
    // until we get a request. (For example, some people run the Code Server behind
    // a reverse proxy to support https.)

    String sourceRoot =
        String.format(
            "http://%s:%d/sourcemaps/%s/",
            request.getServerName(), request.getServerPort(), moduleName);

    PageUtil.sendTemplateFile(
        "application/json",
        sourceMap,
        "\"" + SOURCEROOT_TEMPLATE_VARIABLE + "\"",
        "\"" + sourceRoot + "\"",
        response);

    long elapsedTime = System.currentTimeMillis() - startTime;

    logger.log(
        TreeLogger.WARN,
        "sent source map for module '" + moduleName + "' in " + elapsedTime + " ms");
  }
Пример #21
0
 /**
  * 获取请求的路径
  *
  * @param request request对象
  * @param hasParam 是否包含参数列表
  * @return
  */
 public static String getUri(HttpServletRequest request, boolean hasParam) {
   StringBuffer buffer = new StringBuffer();
   StringBuffer loginPath = request.getRequestURL();
   String path = request.getContextPath();
   String basePath =
       request.getScheme()
           + "://"
           + request.getServerName()
           + ":"
           + request.getServerPort()
           + path
           + "/";
   String userPath = loginPath.substring(basePath.length(), loginPath.length());
   buffer.append(userPath);
   if (hasParam) {
     Map<String, String[]> map = request.getParameterMap();
     int index = 0;
     for (String key : map.keySet()) {
       if (index == 0) buffer.append("?");
       else buffer.append("&");
       index++;
       String[] paravalue = map.get(key);
       buffer.append(key + "=" + paravalue[0]);
     }
   }
   return buffer.toString();
 }
Пример #22
0
  /** 获取请求路径 */
  public String getRequestPath() {
    HttpServletRequest httpServletRequest = getRequest();
    StringBuilder builder = new StringBuilder();
    String scheme = httpServletRequest.getScheme();
    String serverName = httpServletRequest.getServerName();
    int serverPort = httpServletRequest.getServerPort();
    String requestURI = httpServletRequest.getRequestURI();
    builder.append(scheme);
    builder.append("://");
    builder.append(serverName);
    builder.append(":");
    builder.append(serverPort);
    builder.append(requestURI);

    @SuppressWarnings("unchecked")
    Enumeration<String> parameterNames = httpServletRequest.getParameterNames();
    boolean hasMoreElements = parameterNames.hasMoreElements();
    if (hasMoreElements) {
      builder.append("?");
    }
    while (parameterNames.hasMoreElements()) {
      String element = parameterNames.nextElement();
      builder.append(element);
      builder.append("=");
      builder.append(httpServletRequest.getParameter(element));
      builder.append("&");
    }
    String str = builder.toString();
    if (hasMoreElements) {
      str = str.substring(0, str.length() - 1);
    }
    return str;
  }
Пример #23
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // url query : xcap-root/xcap-caps/global/index
    String ser = request.getServerName();
    int port = request.getServerPort();
    String contextPath = request.getSession().getServletContext().getContextPath();
    String url = ser.concat(":").concat(String.valueOf(port));

    String str =
        "<?xml version='1.0' encoding='UTF-8'?>"
            .concat("<xcap-caps xmlns=\"urn:ietf:params:xml:ns:xcap-caps\">")
            .concat("<auids>")
            .concat("  <auid>UABContacts</auid>")
            .concat("  <auid>SingSpacesContacts</auid>")
            .concat("</auids>")
            .concat("<extensions/>")
            .concat(" <namespaces>")
            .concat("  <namespace>http://")
            .concat(url)
            .concat(contextPath)
            .concat("/xcap-schema/UABContacts</namespace>")
            .concat("  <namespace>http://")
            .concat(url)
            .concat(contextPath)
            .concat("/xcap-schema/SingSpacesContacts</namespace>")
            .concat(" </namespaces>")
            .concat("</xcap-caps>");

    response.getWriter().print(str);
  }
Пример #24
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet TestServlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");
    Client client = ClientBuilder.newClient();
    client.register(MyReader.class).register(MyWriter.class);

    WebTarget target =
        client.target(
            "http://"
                + request.getServerName()
                + ":"
                + request.getServerPort()
                + request.getContextPath()
                + "/webresources/endpoint");
    System.out.println("POST request");
    MyObject mo =
        target
            .request()
            .post(
                Entity.entity(new MyObject("Duke", 18), MediaType.APPLICATION_JSON),
                MyObject.class);
    out.println("Received response: " + mo.getName() + ", " + mo.getAge() + "<br><br>");

    out.println("Check server.log for client/server interceptor output.");
    out.println("</body>");
    out.println("</html>");
  }
Пример #25
0
  private String calculateAppMountUrl(HttpServletRequest request, Boolean absoluteUrls) {
    StringBuffer buf = new StringBuffer();

    if (absoluteUrls) {
      buf.append(request.getScheme()).append("://").append(request.getServerName());
      if (request.getScheme().equalsIgnoreCase("https") && request.getServerPort() != 443
          || request.getScheme().equalsIgnoreCase("http") && request.getServerPort() != 80) {

        buf.append(":").append(request.getServerPort());
      }
    }
    if (!request.getContextPath().equals("/")) {
      buf.append(request.getContextPath());
    }
    return buf.toString();
  }
Пример #26
0
  public ServletRequestCopy(HttpServletRequest request) {
    this.servletPath = request.getServletPath();
    this.contextPath = request.getContextPath();
    this.pathInfo = request.getPathInfo();
    this.requestUri = request.getRequestURI();
    this.requestURL = request.getRequestURL();
    this.method = request.getMethod();
    this.serverName = request.getServerName();
    this.serverPort = request.getServerPort();

    HttpSession session = request.getSession(true);
    httpSession = new HttpSessionCopy(session);

    String s;
    Enumeration<String> e = request.getHeaderNames();
    while (e != null && e.hasMoreElements()) {
      s = e.nextElement();
      Enumeration<String> headerValues = request.getHeaders(s);
      this.headers.put(s, headerValues);
    }

    e = request.getAttributeNames();
    while (e != null && e.hasMoreElements()) {
      s = e.nextElement();
      attributes.put(s, request.getAttribute(s));
    }

    e = request.getParameterNames();
    while (e != null && e.hasMoreElements()) {
      s = e.nextElement();
      parameters.put(s, request.getParameterValues(s));
    }
  }
  // 编辑器上传图片
  @RequestMapping("/upload")
  @ResponseBody
  public JSONObject upload(
      @RequestParam("imgFile") MultipartFile file, HttpServletRequest request, ModelMap m)
      throws IOException {

    // String filetype =
    // StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String ymd = sdf.format(new Date());

    String realRootPath =
        getServletContext().getResource("/").toString() + "upload/choicenesscontent/" + ymd + "/";
    YztUtil.writeFile(file.getInputStream(), realRootPath, file.getOriginalFilename());

    /**/
    String path = request.getContextPath();
    String basePath =
        request.getScheme()
            + "://"
            + request.getServerName()
            + ":"
            + request.getServerPort()
            + path
            + "/";
    // System.out.println("getContextPath==="+
    // basePath+"upload/user/headimg/"+user.getId()+"."+filetype);
    String picurl = basePath + "upload/choicenesscontent/" + ymd + "/" + file.getOriginalFilename();
    // user.setPicurl(picurl);

    JSONObject json = new JSONObject();
    json.put("error", 0);
    json.put("url", picurl);
    return json;
  }
Пример #28
0
  // postToRestfulApi -
  // Note: params in the addr field need to be URLEncoded
  private String postToRestfulApi(
      String addr, String data, HttpServletRequest request, HttpServletResponse response) {
    if (localCookie) CookieHandler.setDefault(cm);
    String result = "";
    try {
      URLConnection connection = new URL(API_ROOT + addr).openConnection();
      String cookieVal = getBrowserInfiniteCookie(request);
      if (cookieVal != null) {
        connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
        connection.setDoInput(true);
      }
      connection.setDoOutput(true);
      connection.setRequestProperty("Accept-Charset", "UTF-8");

      // Post JSON string to URL
      OutputStream os = connection.getOutputStream();
      byte[] b = data.getBytes("UTF-8");
      os.write(b);

      // Receive results back from API
      InputStream is = connection.getInputStream();
      result = IOUtils.toString(is, "UTF-8");

      String newCookie = getConnectionInfiniteCookie(connection);
      if (newCookie != null && response != null) {
        setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
      }
    } catch (Exception e) {
      // System.out.println("Exception: " + e.getMessage());
    }
    return result;
  } // TESTED
  /**
   * 将用户提交的简介写入html文件中, 并将文件的url设置进的htmlurl属性中
   *
   * @param request
   * @param choicenesscontent
   * @throws IOException
   */
  private void saveHtmlUrl(HttpServletRequest request, YztChoicenesscontent choicenesscontent)
      throws IOException {
    // 保存简介的html
    String introduction = choicenesscontent.getIntroduction();

    String htmlStr =
        "<!DOCTYPE html><head><meta charset=\"UTF-8\"><title>内容简介</title></head><body>"
            + introduction
            + "</body></html>";

    /* String htmlStr = choicenesscontent.getIntroduction(); */
    // 返回简介html 要存在服务器上的绝对路径
    String path = "upload/choicenesscontent/" + choicenesscontent.getId() + ".html";
    String realRootPath = request.getServletContext().getRealPath("/") + path;
    File file = new File(realRootPath);
    BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    bw.write(htmlStr);
    // 拼成一个url路径
    String htmlurl =
        request.getScheme()
            + "://"
            + request.getServerName()
            + ":"
            + request.getServerPort()
            + request.getContextPath()
            + "/"
            + path;

    choicenesscontent.setIntroductionHtmlUrl(htmlurl);
    bw.close();
  }
Пример #30
0
  public void setURIs(HttpServletRequest request) {
    String serverURL = ApplicationBean.getInstance().getSiteBean().getServerURL();

    String baseURI = request.getRequestURI();
    int extension = baseURI.lastIndexOf("/");
    // This is automatically overwritten by StartServlet
    // if there is an entry "serverURL" in web.xml
    if (serverURL == null || serverURL.length() < 1) {
      ApplicationBean.getInstance()
          .getSiteBean()
          .setServerURL(
              request.getScheme()
                  + "://"
                  + request.getServerName()
                  + ":"
                  + request.getServerPort());
    }
    if (extension != -1) {
      Constants.BaseURL = serverURL + baseURI.substring(0, extension);
      Constants.setHyperlink(Constants.BaseURL);
    }

    // So that JSP can access it...
    HttpSession session = request.getSession();
    session.setAttribute("BASEURL", Constants.BaseURL);

    // persist the last serverURL
    persistLastServerURL(serverURL, Constants.BaseURL);
  }