Java Code Examples for javax.servlet.http.HttpServletResponse#encodeURL()

The following examples show how to use javax.servlet.http.HttpServletResponse#encodeURL() . 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: TesterServletEncodeUrl.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Almost minimal processing for a servlet.
 * <p>
 * The request parameter <code>nextUrl</code> specifies the url to which the
 * caller would like to go next. If supplied, put an encoded url into the
 * returned html page as a hyperlink.
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain");
    PrintWriter out = resp.getWriter();
    out.print("OK");

    String param = req.getParameter("nextUrl");
    if (param!=null) {
        // append an encoded url to carry the sessionids
        String targetUrl = resp.encodeURL(param);
        out.print(". You want to go <a href=\"");
        out.print(targetUrl);
        out.print("\">here next</a>.");
    }
}
 
Example 2
Source File: TagUtils.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
/**
 * リンクとして出力するURLを生成します。
 * @param url パス
 * @param params パスに付与するパラメータ
 * @param pageContext ページコンテキスト
 * @param isHtmlEscape HTMLの特殊文字をエスケープするかどうか
 * @param isJavaScriptEscape JavaScriptの特殊文字をエスケープするかどうか
 * @return パス
 * @throws JspException 予期しない例外
 */
public static String createUrl(String url, Map<String, String[]> params, PageContext pageContext, boolean isHtmlEscape, boolean isJavaScriptEscape) throws JspException {
    HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
    HttpServletResponse response = (HttpServletResponse)pageContext.getResponse();

    StringBuilder buffer = new StringBuilder();
    UrlType urlType = getUrlType(url);
    if (urlType == UrlType.CONTEXT_RELATIVE) {
        buffer.append(request.getContextPath());
        if (!url.startsWith("/")) {
            buffer.append("/");
        }
    }
    buffer.append(replaceUriTemplateParams(url, params, pageContext));
    buffer.append(createQueryString(params, (url.indexOf("?") == -1), pageContext));

    String urlStr = buffer.toString();
    if (urlType != UrlType.ABSOLUTE) {
        urlStr = response.encodeURL(urlStr);
    }

    urlStr = isHtmlEscape ? HtmlUtils.htmlEscape(urlStr) : urlStr;
    urlStr = isJavaScriptEscape ? JavaScriptUtils.javaScriptEscape(urlStr) : urlStr;

    return urlStr;
}
 
Example 3
Source File: TesterServletEncodeUrl.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Almost minimal processing for a servlet.
 *
 * @param nextUrl The url the caller would like to go to next. If
 *                supplied, put an encoded url into the returned
 *                html page as a hyperlink.
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain");
    PrintWriter out = resp.getWriter();
    out.print("OK");

    String param = req.getParameter("nextUrl");
    if (param!=null) {
        // append an encoded url to carry the sessionids
        String targetUrl = resp.encodeURL(param);
        out.print(". You want to go <a href=\"");
        out.print(targetUrl);
        out.print("\">here next</a>.");
    }
}
 
Example 4
Source File: TesterServletEncodeUrl.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Almost minimal processing for a servlet.
 *
 * @param nextUrl The url the caller would like to go to next. If
 *                supplied, put an encoded url into the returned
 *                html page as a hyperlink.
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain");
    PrintWriter out = resp.getWriter();
    out.print("OK");

    String param = req.getParameter("nextUrl");
    if (param!=null) {
        // append an encoded url to carry the sessionids
        String targetUrl = resp.encodeURL(param);
        out.print(". You want to go <a href=\"");
        out.print(targetUrl);
        out.print("\">here next</a>.");
    }
}
 
Example 5
Source File: RequestHandler.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
private static String getFullIncomingURL(HttpServletRequest request, HttpServletResponse response, Boolean encode) { // SCIPIO
    String newUrl;
    if (SecureUrlRedirFmt.VALUE.isIncoming()) {
        // SCIPIO: 2018-07-18: new http-to-https redirect url format option
        newUrl = RequestLinkUtil.rebuildOriginalRequestURL(request, response, UtilHttp.getLocaleExistingSession(request),
                true, SecureUrlRedirFmt.VALUE.isStaticHost(), true, true, true);
        if (!Boolean.FALSE.equals(encode)) {
            newUrl = response.encodeURL(newUrl); // for URL rewriting, etc.
        }
    } else {
        StringBuilder urlBuf = new StringBuilder();
        urlBuf.append(request.getPathInfo());
        if (request.getQueryString() != null) {
            urlBuf.append("?").append(request.getQueryString());
        }
        // SCIPIO: Always make full URL for redirect so uses host from entities
        //String newUrl = RequestHandler.makeUrl(request, response, urlBuf.toString());
        newUrl = RequestHandler.makeUrl(request, response, urlBuf.toString(), true, null, encode);
    }
    return newUrl;
}
 
Example 6
Source File: UrlTag.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Build the URL for the tag from the tag attributes and parameters.
 * @return the URL value as a String
 */
String createUrl() throws JspException {
	Assert.state(this.value != null, "No value set");
	HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
	HttpServletResponse response = (HttpServletResponse) this.pageContext.getResponse();

	StringBuilder url = new StringBuilder();
	if (this.type == UrlType.CONTEXT_RELATIVE) {
		// add application context to url
		if (this.context == null) {
			url.append(request.getContextPath());
		}
		else {
			if (this.context.endsWith("/")) {
				url.append(this.context.substring(0, this.context.length() - 1));
			}
			else {
				url.append(this.context);
			}
		}
	}
	if (this.type != UrlType.RELATIVE && this.type != UrlType.ABSOLUTE && !this.value.startsWith("/")) {
		url.append("/");
	}
	url.append(replaceUriTemplateParams(this.value, this.params, this.templateParams));
	url.append(createQueryString(this.params, this.templateParams, (url.indexOf("?") == -1)));

	String urlStr = url.toString();
	if (this.type != UrlType.ABSOLUTE) {
		// Add the session identifier if needed
		// (Do not embed the session identifier in a remote link!)
		urlStr = response.encodeURL(urlStr);
	}

	// HTML and/or JavaScript escape, if demanded.
	urlStr = htmlEscape(urlStr);
	urlStr = (this.javaScriptEscape ? JavaScriptUtils.javaScriptEscape(urlStr) : urlStr);

	return urlStr;
}
 
Example 7
Source File: URLManager.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Crea un URL completo ad una pagina del portale a partire dalle
 * informazioni essenziali contenute nell'oggetto pageUrl passato come
 * parametro.<br>
 * In questa implementazione, l'URL è costruito come concatenazione dei
 * seguenti elementi:
 * <ul>
 * <li>parametro di configurazione PAR_APPL_BASE_URL, che rappresenta l'URL
 * base della web application così come viene visto dall'esterno; deve
 * comprendere la stringa "http://" e deve terminare con "/";</li>
 * <li>codice della lingua impostata nell'oggetto pageUrl, oppure la lingua
 * corrente, oppure la lingua di default;</li>
 * <li>se il parametro "urlStyle" è settato a "classic", codice della pagina
 * corrente impostata nell'oggetto pageUrl seguito dal suffisso ".page",
 * altrimenti, se il parametro "urlStyle" è settato a "breadcrumbs",
 * "/pages/" seguito dal'insieme del codici pagina dalla root alla pagina
 * corrente separati da "/";</li>
 * <li>eventuale query string se sull'oggetto pageUrl sono stati impostati
 * parametri.</li>
 * </ul>
 *
 * @param pageUrl L'oggetto contenente le informazioni da tradurre in URL.
 * @param reqCtx Il contesto della richiesta.
 * @return La Stringa contenente l'URL.
 * @see com.agiletec.aps.system.services.url.AbstractURLManager#getURLString(com.agiletec.aps.system.services.url.PageURL,
 * com.agiletec.aps.system.RequestContext)
 */
@Override
public String getURLString(PageURL pageUrl, RequestContext reqCtx) {
    try {
        String langCode = pageUrl.getLangCode();
        Lang lang = this.getLangManager().getLang(langCode);
        if (lang == null && null != reqCtx) {
            lang = (Lang) reqCtx.getExtraParam(SystemConstants.EXTRAPAR_CURRENT_LANG);
        }
        if (lang == null) {
            lang = this.getLangManager().getDefaultLang();
        }
        String pageCode = pageUrl.getPageCode();
        IPage page = this.getPageManager().getOnlinePage(pageCode);
        if (page == null && null != reqCtx) {
            page = (IPage) reqCtx.getExtraParam(SystemConstants.EXTRAPAR_CURRENT_PAGE);
        }
        if (page == null) {
            page = this.getPageManager().getOnlineRoot();
        }
        HttpServletRequest request = (null != reqCtx) ? reqCtx.getRequest() : null;
        String url = this.createURL(page, lang, pageUrl.getParams(), pageUrl.isEscapeAmp(), request);
        if (null != reqCtx && this.useJsessionId()) {
            HttpServletResponse resp = reqCtx.getResponse();
            String encUrl = resp.encodeURL(url.toString());
            return encUrl;
        } else {
            return url;
        }
    } catch (Throwable t) {
        _logger.error("Error creating url", t);
        throw new RuntimeException("Error creating url", t);
    }
}
 
Example 8
Source File: UrlTag.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Build the URL for the tag from the tag attributes and parameters.
 * @return the URL value as a String
 * @throws JspException
 */
private String createUrl() throws JspException {
	HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
	HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
	StringBuilder url = new StringBuilder();
	if (this.type == UrlType.CONTEXT_RELATIVE) {
		// add application context to url
		if (this.context == null) {
			url.append(request.getContextPath());
		}
		else {
			if (this.context.endsWith("/")) {
				url.append(this.context.substring(0, this.context.length() - 1));
			}
			else {
				url.append(this.context);
			}
		}
	}
	if (this.type != UrlType.RELATIVE && this.type != UrlType.ABSOLUTE && !this.value.startsWith("/")) {
		url.append("/");
	}
	url.append(replaceUriTemplateParams(this.value, this.params, this.templateParams));
	url.append(createQueryString(this.params, this.templateParams, (url.indexOf("?") == -1)));

	String urlStr = url.toString();
	if (this.type != UrlType.ABSOLUTE) {
		// Add the session identifier if needed
		// (Do not embed the session identifier in a remote link!)
		urlStr = response.encodeURL(urlStr);
	}

	// HTML and/or JavaScript escape, if demanded.
	urlStr = htmlEscape(urlStr);
	urlStr = this.javaScriptEscape ? JavaScriptUtils.javaScriptEscape(urlStr) : urlStr;

	return urlStr;
}
 
Example 9
Source File: UrlTag.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build the URL for the tag from the tag attributes and parameters.
 * @return the URL value as a String
 */
String createUrl() throws JspException {
	HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
	HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();

	StringBuilder url = new StringBuilder();
	if (this.type == UrlType.CONTEXT_RELATIVE) {
		// add application context to url
		if (this.context == null) {
			url.append(request.getContextPath());
		}
		else {
			if (this.context.endsWith("/")) {
				url.append(this.context.substring(0, this.context.length() - 1));
			}
			else {
				url.append(this.context);
			}
		}
	}
	if (this.type != UrlType.RELATIVE && this.type != UrlType.ABSOLUTE && !this.value.startsWith("/")) {
		url.append("/");
	}
	url.append(replaceUriTemplateParams(this.value, this.params, this.templateParams));
	url.append(createQueryString(this.params, this.templateParams, (url.indexOf("?") == -1)));

	String urlStr = url.toString();
	if (this.type != UrlType.ABSOLUTE) {
		// Add the session identifier if needed
		// (Do not embed the session identifier in a remote link!)
		urlStr = response.encodeURL(urlStr);
	}

	// HTML and/or JavaScript escape, if demanded.
	urlStr = htmlEscape(urlStr);
	urlStr = (this.javaScriptEscape ? JavaScriptUtils.javaScriptEscape(urlStr) : urlStr);

	return urlStr;
}
 
Example 10
Source File: UrlTag.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Build the URL for the tag from the tag attributes and parameters.
 * @return the URL value as a String
 */
String createUrl() throws JspException {
	Assert.state(this.value != null, "No value set");
	HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
	HttpServletResponse response = (HttpServletResponse) this.pageContext.getResponse();

	StringBuilder url = new StringBuilder();
	if (this.type == UrlType.CONTEXT_RELATIVE) {
		// add application context to url
		if (this.context == null) {
			url.append(request.getContextPath());
		}
		else {
			if (this.context.endsWith("/")) {
				url.append(this.context.substring(0, this.context.length() - 1));
			}
			else {
				url.append(this.context);
			}
		}
	}
	if (this.type != UrlType.RELATIVE && this.type != UrlType.ABSOLUTE && !this.value.startsWith("/")) {
		url.append("/");
	}
	url.append(replaceUriTemplateParams(this.value, this.params, this.templateParams));
	url.append(createQueryString(this.params, this.templateParams, (url.indexOf("?") == -1)));

	String urlStr = url.toString();
	if (this.type != UrlType.ABSOLUTE) {
		// Add the session identifier if needed
		// (Do not embed the session identifier in a remote link!)
		urlStr = response.encodeURL(urlStr);
	}

	// HTML and/or JavaScript escape, if demanded.
	urlStr = htmlEscape(urlStr);
	urlStr = (this.javaScriptEscape ? JavaScriptUtils.javaScriptEscape(urlStr) : urlStr);

	return urlStr;
}
 
Example 11
Source File: SpringFormTag.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected String resolveAction() throws JspException {
    String action = super.resolveAction();

    if (UrlUtil.isAbsoluteUrl(action)) {
        return action;
    } else {
        HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
        return response.encodeURL(action);
    }
}
 
Example 12
Source File: UrlRewriting.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 4 votes vote down vote up
private String encodeURLRewrite(HttpServletResponse resp, String url) {
    return resp.encodeURL(url);
}
 
Example 13
Source File: CK3ImageBrowser.java    From docx-html-editor with GNU Affero General Public License v3.0 4 votes vote down vote up
protected String getUrl(HttpServletResponse response, String name) {
	return response.encodeURL(Editor.getContextPath() + "/services/image/" + name);		
}
 
Example 14
Source File: ServiceUtils.java    From nano-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs a service url from the HttpServletRequest or from the given
 * serviceUrl. Prefers the serviceUrl provided if both a serviceUrl and a
 * serviceName.
 *
 * @param request the HttpServletRequest
 * @param response the HttpServletResponse
 * @param service the configured service url (this will be used if not null)
 * @param serverNames the server name to  use to construct the service url if the service param is empty.  Note, prior to CAS Client 3.3, this was a single value.
 *           As of 3.3, it can be a space-separated value.  We keep it as a single value, but will convert it to an array internally to get the matching value. This keeps backward compatability with anything using this public
 *           method.
 * @param serviceParameterName the service parameter name to remove (i.e. service)
 * @param artifactParameterName the artifact parameter name to remove (i.e. ticket)
 * @param encode whether to encode the url or not (i.e. Jsession).
 * @return the service url to use.
 */
public static String constructServiceUrl(final HttpServletRequest request, final HttpServletResponse response, final String service,
        final String serverNames, final String serviceParameterName, final String artifactParameterName, final boolean encode) {
    if (StringUtils.isNotBlank(service)) {
        return encode ? response.encodeURL(service) : service;
    }

    final String serverName = findMatchingServerName(request, serverNames);
    final URIBuilder originalRequestUrl = new URIBuilder(request.getRequestURL().toString(), encode);
    originalRequestUrl.setParameters(request.getQueryString());

    URIBuilder builder = null;

    boolean containsScheme = true;
    if (!serverName.startsWith("https://") && !serverName.startsWith("http://")) {
        builder = new URIBuilder(encode);
        builder.setScheme(request.isSecure() ? "https" : "http");
        builder.setHost(serverName);
        containsScheme = false;
    } else {
        builder = new URIBuilder(serverName, encode);
    }

    if (!serverNameContainsPort(containsScheme, serverName) && !requestIsOnStandardPort(request)) {
        builder.setPort(request.getServerPort());
    }

    builder.setEncodedPath(request.getRequestURI());

    final List<String> serviceParameterNames = Arrays.asList(serviceParameterName.split(","));
    if (!serviceParameterNames.isEmpty() && !originalRequestUrl.getQueryParams().isEmpty()) {
        for (final URIBuilder.BasicNameValuePair pair : originalRequestUrl.getQueryParams()) {
            if (!pair.getName().equals(artifactParameterName) && !serviceParameterNames.contains(pair.getName())) {
                builder.addParameter(pair.getName(), pair.getValue());
            }
        }
    }

    final String result = builder.toString();
    final String returnValue = encode ? response.encodeURL(result) : result;
    LOGGER.debug("serviceUrl generated: {}", returnValue);
    return returnValue;
}
 
Example 15
Source File: PankuzuTag.java    From sinavi-jfw with Apache License 2.0 4 votes vote down vote up
String encodeURL(String url) {
    PageContext pageContext = (PageContext) getJspContext();
    HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
    return response.encodeURL(url);
}
 
Example 16
Source File: BaseURLTag.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
@Override
public int doEndTag() throws JspException{
	
	BaseURL url = getUrl();
	
	if(url == null){
		throw new IllegalStateException("internal error: url not set");
	}
	
	setUrlParameters(url);		
	setUrlProperties(url);
	
	HttpServletResponse response = 
		(HttpServletResponse) pageContext.getResponse();
	
	//	properly encoding urls to allow non-cookie enabled sessions - PLUTO-252 
	String urlString = response.encodeURL(url.toString());

		if(Boolean.parseBoolean(escapeXml))
		{
		 urlString = doEscapeXml(urlString);
	}
	
    if (var == null) {
           try {            	
               JspWriter writer = pageContext.getOut();
               writer.print(urlString);
           } catch (IOException ioe) {
               throw new JspException(
                   "Portlet/ResourceURL-Tag Exception: cannot write to the output writer.");
           }
       } 
    else {
           pageContext.setAttribute(var, urlString,
                                    PageContext.PAGE_SCOPE);
       }
    
    /*cleanup*/
    propertiesMap.clear();
    parametersMap.clear();
    removedParametersList.clear();
    
    setUrl(null);
    
       return EVAL_PAGE;
}
 
Example 17
Source File: Download.java    From iaf with Apache License 2.0 4 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	HttpSession session=request.getSession();
	if (session!=null) {
		String url = (String)session.getAttribute(URL_KEY);
		if (url!=null) {
			String parameters=null;
			Map params=(Map)session.getAttribute(PARAMETERS_KEY);
			for (Iterator it=params.keySet().iterator(); it.hasNext();) {
				String name=(String)it.next();
				String values[]=(String[])params.get(name);
				for (int i=0; i<values.length; i++) {
					if (parameters==null) {
						parameters="?";
					} else {
						parameters+="&";
					}
					parameters+=name+"="+URLEncoder.encode(values[i],response.getCharacterEncoding());
				}
			}
			if (parameters!=null) {
				url+=parameters;
			}
			String context=request.getContextPath();
			if (url.startsWith(context)) {
				url=url.substring(context.length());
			}
			url=response.encodeURL(url);
			if (log.isDebugEnabled()) log.debug("dispatching to ["+url+"]");
			String contenttype=(String)session.getAttribute(CONTENTTYPE_KEY);
			String filename=(String)session.getAttribute(FILENAME_KEY);
			
			session.removeAttribute(URL_KEY);
			session.removeAttribute(PARAMETERS_KEY);
			session.removeAttribute(CONTENTTYPE_KEY);
			session.removeAttribute(FILENAME_KEY);
			
			response.setContentType(contenttype);
			response.setHeader("Content-Disposition","attachment; filename=\""+filename+"\"");
			RequestDispatcher rd=request.getRequestDispatcher(url);
			rd.include(request,response);
		}
	}
}
 
Example 18
Source File: Editor.java    From docx-html-editor with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * XSLT extension function which encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. 
 * The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. 
 * For example, if the browser supports cookies, or session tracking is turned off, URL encoding is unnecessary.
 * 
 * For robust session tracking, all URLs emitted by a servlet should be run through this method. 
 * Otherwise, URL rewriting cannot be used with browsers which do not support cookies.
 * 
 * @param url
 * @return
 */
public static String encodeURL(HttpServletResponse response, String url) {
	
	return response.encodeURL(url);
}