Java Code Examples for javax.servlet.jsp.PageContext#getRequest()

The following examples show how to use javax.servlet.jsp.PageContext#getRequest() . 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: ListTagUtil.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Includes arbitrary _local_ url as content
 * @param ctx caller's page context
 * @param url local url
 * @throws JspException if something goes wrong
 *
 * Note: Local means Urls in the same application
 */
public static void includeContent(PageContext ctx, String url) throws JspException {
    HttpServletRequest request = (HttpServletRequest) ctx.getRequest();
    HttpServletResponse response = (HttpServletResponse) ctx.getResponse();
    RequestDispatcher rd =
        request.getSession(true).getServletContext().getRequestDispatcher(url);
    if (rd == null) {
        ListTagUtil.write(ctx, "<!-- " + url + " not found -->");
    }
    else {
        try {
            BufferedResponseWrapper wrapper = new BufferedResponseWrapper(response);
            rd.include(request, wrapper);
            wrapper.flush();
            ListTagUtil.write(ctx, wrapper.getBufferedOutput());
        }
        catch (Exception e) {
            throw new JspException(e);
        }
    }
}
 
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: MessageTagTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void requestContext() throws ServletException {
	PageContext pc = createPageContext();
	RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest(), pc.getServletContext());
	assertEquals("test message", rc.getMessage("test"));
	assertEquals("test message", rc.getMessage("test", (Object[]) null));
	assertEquals("test message", rc.getMessage("test", "default"));
	assertEquals("test message", rc.getMessage("test", (Object[]) null, "default"));
	assertEquals("test arg1 message arg2",
			rc.getMessage("testArgs", new String[] {"arg1", "arg2"}, "default"));
	assertEquals("test arg1 message arg2",
			rc.getMessage("testArgs", Arrays.asList(new String[] {"arg1", "arg2"}), "default"));
	assertEquals("default", rc.getMessage("testa", "default"));
	assertEquals("default", rc.getMessage("testa", (List) null, "default"));
	MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] {"test"});
	assertEquals("test message", rc.getMessage(resolvable));
}
 
Example 4
Source File: ThemeTagTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void requestContext() throws ServletException {
	PageContext pc = createPageContext();
	RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest());
	assertEquals("theme test message", rc.getThemeMessage("themetest"));
	assertEquals("theme test message", rc.getThemeMessage("themetest", (String[]) null));
	assertEquals("theme test message", rc.getThemeMessage("themetest", "default"));
	assertEquals("theme test message", rc.getThemeMessage("themetest", (Object[]) null, "default"));
	assertEquals("theme test message arg1",
			rc.getThemeMessage("themetestArgs", new String[] {"arg1"}));
	assertEquals("theme test message arg1",
			rc.getThemeMessage("themetestArgs", Arrays.asList(new String[] {"arg1"})));
	assertEquals("default", rc.getThemeMessage("themetesta", "default"));
	assertEquals("default", rc.getThemeMessage("themetesta", (List) null, "default"));
	MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] {"themetest"});
	assertEquals("theme test message", rc.getThemeMessage(resolvable));
}
 
Example 5
Source File: ListTagUtil.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Includes arbitrary _local_ url as content
 * @param ctx caller's page context
 * @param url local url
 * @throws JspException if something goes wrong
 *
 * Note: Local means Urls in the same application
 */
public static void includeContent(PageContext ctx, String url) throws JspException {
    HttpServletRequest request = (HttpServletRequest) ctx.getRequest();
    HttpServletResponse response = (HttpServletResponse) ctx.getResponse();
    RequestDispatcher rd =
        request.getSession(true).getServletContext().getRequestDispatcher(url);
    if (rd == null) {
        ListTagUtil.write(ctx, "<!-- " + url + " not found -->");
    }
    else {
        try {
            BufferedResponseWrapper wrapper = new BufferedResponseWrapper(response);
            rd.include(request, wrapper);
            wrapper.flush();
            ListTagUtil.write(ctx, wrapper.getBufferedOutput());
        }
        catch (Exception e) {
            throw new JspException(e);
        }
    }
}
 
Example 6
Source File: MessageTagTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void requestContext() throws ServletException {
	PageContext pc = createPageContext();
	RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest(), pc.getServletContext());
	assertEquals("test message", rc.getMessage("test"));
	assertEquals("test message", rc.getMessage("test", (Object[]) null));
	assertEquals("test message", rc.getMessage("test", "default"));
	assertEquals("test message", rc.getMessage("test", (Object[]) null, "default"));
	assertEquals("test arg1 message arg2",
			rc.getMessage("testArgs", new String[] {"arg1", "arg2"}, "default"));
	assertEquals("test arg1 message arg2",
			rc.getMessage("testArgs", Arrays.asList(new String[] {"arg1", "arg2"}), "default"));
	assertEquals("default", rc.getMessage("testa", "default"));
	assertEquals("default", rc.getMessage("testa", (List) null, "default"));
	MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] {"test"});
	assertEquals("test message", rc.getMessage(resolvable));
}
 
Example 7
Source File: ImplicitObjectELResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 *
 * Creates the Map that maps cookie name to the first matching
 * Cookie in request.getCookies().
 **/
public static Map createCookieMap (PageContext pContext)
{
  // Read all the cookies and construct the entire map
  HttpServletRequest request = (HttpServletRequest) pContext.getRequest ();
  Cookie [] cookies = request.getCookies ();
  Map ret = new HashMap ();
  for (int i = 0; cookies != null && i < cookies.length; i++) {
    Cookie cookie = cookies [i];
    if (cookie != null) {
      String name = cookie.getName ();
      if (!ret.containsKey (name)) {
        ret.put (name, cookie);
      }
    }
  }
  return ret;
}
 
Example 8
Source File: JspAwareRequestContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initialize this context with the given page context,
 * using the given model attributes for Errors retrieval.
 * @param pageContext current JSP page context
 * @param model the model attributes for the current view
 * (can be {@code null}, using the request attributes for Errors retrieval)
 */
protected void initContext(PageContext pageContext, Map<String, Object> model) {
	if (!(pageContext.getRequest() instanceof HttpServletRequest)) {
		throw new IllegalArgumentException("RequestContext only supports HTTP requests");
	}
	this.pageContext = pageContext;
	initContext((HttpServletRequest) pageContext.getRequest(), (HttpServletResponse) pageContext.getResponse(),
			pageContext.getServletContext(), model);
}
 
Example 9
Source File: Util.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/** Utility methods
 * taken from org.apache.taglibs.standard.tag.common.core.UrlSupport
 */
public static String resolveUrl(
        String url, String context, PageContext pageContext)
throws JspException {
    // don't touch absolute URLs
    if (isAbsoluteUrl(url))
        return url;
    
    // normalize relative URLs against a context root
    HttpServletRequest request =
        (HttpServletRequest) pageContext.getRequest();
    if (context == null) {
        if (url.startsWith("/"))
            return (request.getContextPath() + url);
        else
            return url;
    } else {
        if (!context.startsWith("/") || !url.startsWith("/")) {
            throw new JspTagException(
            "In URL tags, when the \"context\" attribute is specified, values of both \"context\" and \"url\" must start with \"/\".");
        }
        if (context.equals("/")) {
            // Don't produce string starting with '//', many
            // browsers interpret this as host name, not as
            // path on same host.
            return url;
        } else {
            return (context + url);
        }
    }
}
 
Example 10
Source File: ThemeTagTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void requestContext() throws ServletException {
	PageContext pc = createPageContext();
	RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest());
	assertEquals("theme test message", rc.getThemeMessage("themetest"));
	assertEquals("theme test message", rc.getThemeMessage("themetest", (String[]) null));
	assertEquals("theme test message", rc.getThemeMessage("themetest", "default"));
	assertEquals("theme test message", rc.getThemeMessage("themetest", (Object[]) null, "default"));
	assertEquals("theme test message arg1",
			rc.getThemeMessage("themetestArgs", new String[] {"arg1"}));
	assertEquals("theme test message arg1",
			rc.getThemeMessage("themetestArgs", Arrays.asList(new String[] {"arg1"})));
	assertEquals("default", rc.getThemeMessage("themetesta", "default"));
	assertEquals("default", rc.getThemeMessage("themetesta", (List) null, "default"));
	MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] {"themetest"});
	assertEquals("theme test message", rc.getThemeMessage(resolvable));
}
 
Example 11
Source File: JspAwareRequestContext.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize this context with the given page context,
 * using the given model attributes for Errors retrieval.
 * @param pageContext current JSP page context
 * @param model the model attributes for the current view
 * (can be {@code null}, using the request attributes for Errors retrieval)
 */
protected void initContext(PageContext pageContext, Map<String, Object> model) {
	if (!(pageContext.getRequest() instanceof HttpServletRequest)) {
		throw new IllegalArgumentException("RequestContext only supports HTTP requests");
	}
	this.pageContext = pageContext;
	initContext((HttpServletRequest) pageContext.getRequest(), (HttpServletResponse) pageContext.getResponse(),
			pageContext.getServletContext(), model);
}
 
Example 12
Source File: ImplicitObjectELResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * Creates the Map that maps header name to an array of header
 * values.
 **/
public static Map createHeadersMap (PageContext pContext)
{
  final HttpServletRequest request =
    (HttpServletRequest) pContext.getRequest ();
  return new EnumeratedMap ()
    {
      public Enumeration enumerateKeys () 
      {
        return request.getHeaderNames ();
      }

      public Object getValue (Object pKey) 
      {
        if (pKey instanceof String) {
          // Drain the header enumeration
          List l = new ArrayList ();
          Enumeration e = request.getHeaders ((String) pKey);
          if (e != null) {
            while (e.hasMoreElements ()) {
              l.add (e.nextElement ());
            }
          }
          String [] ret = (String []) l.toArray (new String [l.size ()]);
          return ret;
        }
        else {
          return null;
        }
      }

      public boolean isMutable ()
      {
        return false;
      }
    };
}
 
Example 13
Source File: TagUtils.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
     * <p>
     * {@code Spring MVC} のパス修飾機構によって指定されたURLパスを修飾します。<br/>
     * </p>
     * @param action パス
     * @param requestContext {@link RequestContext} インスタンス
     * @param pageContext {@link PageContext} インスタンス
     * @return 修飾されたパス
     */
    public static String processAction(String action, RequestContext requestContext, PageContext pageContext) {
        RequestDataValueProcessor processor = requestContext.getRequestDataValueProcessor();
        ServletRequest request = pageContext.getRequest();
        if ((processor != null) && (request instanceof HttpServletRequest)) {
//            return processor.processAction((HttpServletRequest) request, action);
            return processor.processAction((HttpServletRequest) request, action, ((HttpServletRequest) request).getMethod());
        }
        return action;
    }
 
Example 14
Source File: ImplicitObjectELResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * Creates the Map that maps parameter name to an array of parameter
 * values.
 **/
public static Map createParamsMap (PageContext pContext)
{
  final HttpServletRequest request =
    (HttpServletRequest) pContext.getRequest ();
  return new EnumeratedMap ()
    {
      public Enumeration enumerateKeys () 
      {
        return request.getParameterNames ();
      }

      public Object getValue (Object pKey) 
      {
        if (pKey instanceof String) {
          return request.getParameterValues ((String) pKey);
        }
        else {
          return null;
        }
      }

      public boolean isMutable ()
      {
        return false;
      }
    };
}
 
Example 15
Source File: ImplicitObjectELResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * Creates the Map that maps parameter name to single parameter
 * value.
 **/
public static Map createParamMap (PageContext pContext)
{
  final HttpServletRequest request =
    (HttpServletRequest) pContext.getRequest ();
  return new EnumeratedMap ()
    {
      public Enumeration enumerateKeys () 
      {
        return request.getParameterNames ();
      }

      public Object getValue (Object pKey) 
      {
        if (pKey instanceof String) {
          return request.getParameter ((String) pKey);
        }
        else {
          return null;
        }
      }

      public boolean isMutable ()
      {
        return false;
      }
    };
}
 
Example 16
Source File: JspToolContext.java    From velocity-tools with Apache License 2.0 5 votes vote down vote up
public JspToolContext(VelocityEngine velocity,
                      PageContext pageContext)
{
    super(velocity,
          (HttpServletRequest)pageContext.getRequest(),
          (HttpServletResponse)pageContext.getResponse(),
          pageContext.getServletContext());

    this.pageContext = pageContext;
}
 
Example 17
Source File: Util.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/** Utility methods
 * taken from org.apache.taglibs.standard.tag.common.core.UrlSupport
 */
public static String resolveUrl(
        String url, String context, PageContext pageContext)
throws JspException {
    // don't touch absolute URLs
    if (isAbsoluteUrl(url))
        return url;
    
    // normalize relative URLs against a context root
    HttpServletRequest request =
        (HttpServletRequest) pageContext.getRequest();
    if (context == null) {
        if (url.startsWith("/"))
            return (request.getContextPath() + url);
        else
            return url;
    } else {
        if (!context.startsWith("/") || !url.startsWith("/")) {
            throw new JspTagException(
            "In URL tags, when the \"context\" attribute is specified, values of both \"context\" and \"url\" must start with \"/\".");
        }
        if (context.equals("/")) {
            // Don't produce string starting with '//', many
            // browsers interpret this as host name, not as
            // path on same host.
            return url;
        } else {
            return (context + url);
        }
    }
}
 
Example 18
Source File: TagUtils.java    From ontopia with Apache License 2.0 5 votes vote down vote up
public static boolean isComponentReadOnly(PageContext pageContext,
                                          String compReadOnlyAttr) {
  ServletRequest request = pageContext.getRequest();
  if (compReadOnlyAttr == null)
    return isFormReadOnly(request);
  else if (compReadOnlyAttr.equals("false"))
    return false;
  else if (isFormReadOnly(request))
    return true;
  else
    return InteractionELSupport.getBooleanValue(compReadOnlyAttr, false, 
                                                pageContext);
}
 
Example 19
Source File: ListTagUtil.java    From spacewalk with GNU General Public License v2.0 4 votes vote down vote up
/**
    * Renders the filter UI
    * @param pageContext caller's page context
    * @param filter ListFilter instance
    * @param uniqueName name of the list
    * @param width width of the list
    * @param columnCount list's column count
    * @throws JspException if something bad happens writing to the page
    */
   public static void renderFilterUI(PageContext pageContext, ListFilter filter,
           String uniqueName, String width, int columnCount) throws JspException {
       LocalizationService ls = LocalizationService.getInstance();
       HttpServletRequest request = (HttpServletRequest) pageContext
               .getRequest();
       String filterByKey = makeFilterByLabel(uniqueName);
       String filterBy = request.getParameter(filterByKey);
       String filterValueKey = makeFilterValueByLabel(uniqueName);
       String filterName = makeFilterNameByLabel(uniqueName);
       String filterValue =  ListTagHelper.getFilterValue(pageContext.getRequest(),
               uniqueName);


       //We set this so we know next time around what the old filter value was
       ListTagUtil.write(pageContext, String.format(HIDDEN_TEXT,
                       makeOldFilterValueByLabel(uniqueName),
                       StringEscapeUtils.escapeHtml(filterValue)));


       List fields = filter.getFieldNames();
       if (fields == null || fields.size() == 0) {
           throw new JspException(
                   "ListFilter.getFieldNames() returned no field names");
       }
       else if (fields.size() == 1) {
           ListTagUtil.write(pageContext, "<input type=\"hidden\" name=\"");
           ListTagUtil.write(pageContext, filterByKey);
           ListTagUtil.write(pageContext, "\" value=\"");
           ListTagUtil.write(pageContext, fields.get(0).toString());
           ListTagUtil.write(pageContext, "\" />");
       }
       else {
           ListTagUtil.write(pageContext, ls.getMessage("message.filterby.multiple"));
           ListTagUtil.write(pageContext, "<select name=\"");
           ListTagUtil.write(pageContext, filterByKey);
           ListTagUtil.write(pageContext, "\">");
           for (Iterator iter = fields.iterator(); iter.hasNext();) {
               String field = (String) iter.next();
               ListTagUtil.write(pageContext, "<option value=\"");
               ListTagUtil.write(pageContext, field);
               ListTagUtil.write(pageContext, "\" ");
               if (field.equals(filterBy)) {
                   ListTagUtil.write(pageContext, "selected");
               }
               ListTagUtil.write(pageContext, ">");
               ListTagUtil.write(pageContext, field);
               ListTagUtil.write(pageContext, "</option>");
           }
           ListTagUtil.write(pageContext, "</select>");
       }

       filterValue = StringUtil.nullOrValue(filterValue);
       StringBuilder sb = new StringBuilder();

       // create a new row
       sb.append("<div class=\"input-group input-group-sm\">");

       String placeHolder = StringUtils.defaultString(ls.getMessage("message.filterby",
               fields.get(0).toString()));
       sb.append(String.format("<input autofocus=\"autofocus\" type=\"text\" " +
               " name=\"%s\" value=\"%s\" class=\"form-control\" placeholder=\"%s\"/>",
                               filterValueKey,
                               (filterValue != null ?
                                StringEscapeUtils.escapeHtml(filterValue) :
                                ""),
                                StringEscapeUtils.escapeHtml(placeHolder)
                                ));
       sb.append("<span class=\"input-group-btn\">");
       sb.append(String.format("<button value=\"%s\" type=\"submit\" name=\"%s\" " +
" class=\"btn btn-default spacewalk-button-filter\"><i class=\"fa fa-eye\"></i>",
                               ls.getMessage(RequestContext.FILTER_KEY),
                               filterName));
       sb.append("</button>");
       sb.append("</span>");

       sb.append("</div>");

       ListTagUtil.write(pageContext, sb.toString());

   }
 
Example 20
Source File: JspAwareRequestContext.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Create a new JspAwareRequestContext for the given page context,
 * using the given model attributes for Errors retrieval.
 * @param pageContext current JSP page context
 * @param model the model attributes for the current view
 * (can be {@code null}, using the request attributes for Errors retrieval)
 */
public JspAwareRequestContext(PageContext pageContext, @Nullable Map<String, Object> model) {
	super((HttpServletRequest) pageContext.getRequest(), (HttpServletResponse) pageContext.getResponse(),
			pageContext.getServletContext(), model);
	this.pageContext = pageContext;
}