Package org.javalite.activeweb
Class HttpSupport
java.lang.Object
org.javalite.activeweb.HttpSupport
- All Implemented Interfaces:
RequestAccess
- Direct Known Subclasses:
AppController
,HttpSupportFilter
- Author:
- Igor Polevoy
-
Nested Class Summary
-
Field Summary
Fields inherited from interface org.javalite.activeweb.RequestAccess
LOGGER
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionprotected void
A convenience method.protected void
Assigns a value for a view.protected boolean
Returns true if any named request parameter is blank.protected void
Synonym forsetEncoding(String)
protected void
Flash method to display multiple flash messages.protected void
Sets a flash name for a flash with a body.protected void
Sends value to flash.protected void
Flash method to display multiple flash messages.protected String
Controllers can override this method to return encoding they require.protected FileItem
Convenience method to get file content frommultipart/form-data
request.protected javax.servlet.http.HttpServletRequest
Direct access to currentHttpServletRequest
for low level operations.protected javax.servlet.http.HttpServletResponse
Direct access to currentHttpServletResponse
for low level operations.Returns a map parsed from a request if parameter names have a "hash" syntax:Convenience method to get parameter map in casemultipart/form-data
request was used.protected String
getRealPath(String path)
Returns a String containing the real path for a given virtual path.protected byte[]
Reads entire request data as byte array.protected InputStream
Returns InputStream of the request.protected InputStream
Alias togetRequestInputStream()
.protected String
Reads entire request data as String.Returns response headersprotected void
Adds a header to response.protected void
Adds a header to response.protected List
jsonList()
Converts posted JSON array to a Java List.protected Map
jsonMap()
Converts posted JSON map to a Java Map.protected Map[]
jsonMaps()
Converts posted JSON maps to a Java Maps array.protected void
Same assetLocale(java.util.Locale)
protected void
protected void
protected void
protected void
protected void
protected void
logWarning(String info)
protected void
logWarning(String info, Throwable e)
protected String
Will merge a template and return resulting string.protected MultipartForm
protected MultipartForm
multipartForm(String encoding, long maxUploadSize)
Convenience method, callsmultipartFormItems(String)
.multipartFormItems(String encoding)
Returns a collection of uploaded files and form fields from a multi-part request.multipartFormItems(String encoding, long maxUploadSize)
Returns a collection of uploaded files and form fields from a multi-part request.protected OutputStream
Use to send raw data to HTTP client.protected OutputStream
outputStream(String contentType)
Use to send raw data to HTTP client.protected OutputStream
outputStream(String contentType, Map headers, int status)
Use to send raw data to HTTP client.protected HttpSupport.HttpBuilder
redirect()
Redirects to the same controller, and action "index".protected <T extends AppController>
HttpSupport.HttpBuilderRedirects to given controller, action "index" without any parameters.protected <T extends AppController>
HttpSupport.HttpBuilderConvenience method forredirect(Class, java.util.Map)
.protected <T extends AppController>
HttpSupport.HttpBuilderConvenience method forredirect(Class, java.util.Map)
.protected <T extends AppController>
HttpSupport.HttpBuilderConvenience method forredirect(Class, java.util.Map)
.protected <T extends AppController>
HttpSupport.HttpBuilderRedirects to a controller, generates appropriate redirect path.protected HttpSupport.HttpBuilder
Redirects to a an action of this controller, or an action of a different controller.protected HttpSupport.HttpBuilder
Redirects to another URL (usually another site).protected HttpSupport.HttpBuilder
Redirects to referrer if one exists.protected HttpSupport.HttpBuilder
redirectToReferrer(String defaultReference)
Redirects to referrer if one exists.protected HttpSupport.RenderBuilder
Renders results with a template.protected HttpSupport.HttpBuilder
This method will send the text to a client verbatim.protected String
Cleans HTML from harmful tags, making XSS impossible.protected void
sendCookie(String name, String value)
Sends cookie to browse with response.protected void
sendCookie(Cookie cookie)
Sends cookie to browse with response.protected HttpSupport.HttpBuilder
Convenience method for downloading files.protected HttpSupport.HttpBuilder
Convenience method for downloading files.protected void
sendPermanentCookie(String name, String value)
Sends long to live cookie to browse with response.protected SessionFacade
session()
Returns reference to a current session.protected void
session(String name, Serializable value)
Convenience method, sets an object on a session.protected Boolean
sessionBoolean(String name)
Convenience method, returns object from session, equivalent of:protected Double
sessionDouble(String name)
Convenience method, returns object from session, equivalent of:protected Float
sessionFloat(String name)
Convenience method, returns object from session, equivalent of:protected boolean
sessionHas(String name)
Returns true if session has named object, false if not.protected Integer
sessionInteger(String name)
Convenience method, returns object from session, equivalent of:protected Long
sessionLong(String name)
Convenience method, returns object from session, equivalent of:protected Object
sessionObject(String name)
Convenience method, returns object from session, equivalent of:protected String
sessionString(String name)
Convenience method, returns object from session, equivalent of:protected void
setContentLength(int length)
Sets content length of response.protected void
setEncoding(String encoding)
Sets character encoding on the response.protected void
Sets locale on response.protected void
setRequestEncoding(String encoding)
Sets character encoding for request.protected void
setResponseEncoding(String encoding)
Sets character encoding for response.protected int
status()
Returns status code from current response.protected HttpSupport.HttpBuilder
streamOut(InputStream in)
Streams content of thereader
to the HTTP client.Returns a collection of uploaded files from a multi-part port request.uploadedFiles(String encoding)
Returns a collection of uploaded files from a multi-part port request.uploadedFiles(String encoding, long maxFileSize)
Returns a collection of uploaded files from a multi-part port request.protected Map
values()
Returns a mutable Map with all the values from the current request context.protected void
Convenience method to pass multiple names and corresponding values to a view.protected void
Alias toassign(String, Object)
.protected void
Convenience method, callsassign(String, Object)
internally.protected PrintWriter
writer()
Produces a writer for sending raw data to HTTP clients.protected PrintWriter
Produces a writer for sending raw data to HTTP clients.Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface org.javalite.activeweb.RequestAccess
appContext, context, cookie, cookies, cookieValue, exists, format, getId, getLocale, getRequestHost, getRequestPort, getRequestProperties, getRequestProtocol, getRoute, header, headers, host, ipAddress, ipForwardedFor, isDelete, isGet, isHead, isMethod, isMultipartContent, isPost, isPut, isXhr, locale, method, param, param, params, params, params, params1st, params1st, path, port, protocol, queryString, remoteAddress, remoteHost, requestHas, servletPath, session, session, uri, url, userAgent, xhr
-
Constructor Details
-
HttpSupport
public HttpSupport()
-
-
Method Details
-
logInfo
-
logDebug
-
logWarning
-
logWarning
-
logError
-
logError
-
logError
-
assign
Assigns a value for a view.- Parameters:
name
- name of valuevalue
- value.
-
view
Alias toassign(String, Object)
.- Parameters:
name
- name of object to be passed to viewvalue
- object to be passed to view
-
status
protected int status()Returns status code from current response.- Returns:
- status code or -1 if controller response was not generated (error)
-
view
Convenience method, callsassign(String, Object)
internally. The keys in teh map are converted to String values.- Parameters:
values
- map with values to pass to view.
-
view
Convenience method to pass multiple names and corresponding values to a view.- Parameters:
values
- - pairs of names and values. such as: name1, value1, name2, value2, etc. Number of arguments must be even.
-
flash
Flash method to display multiple flash messages. Takes in a map of names and values for a flash. Keys act like names, and values act like... ehr.. values.- Parameters:
values
- values to flash.- See Also:
flash(String, Object)
-
flash
Flash method to display multiple flash messages. Takes in a vararg of values for flash. Number of arguments must be even. Format: name, value, name, value, etc.- Parameters:
values
- values to flash.- See Also:
flash(String, Object)
-
flash
Sets a flash name for a flash with a body. Here is a how to use a tag with a body:<@flash name="warning"> <div class="warning">${message}</div> </@flash>
If body refers to variables (as in this example), then such variables need to be passed in to the template as usual using theview(String, Object)
method.- Parameters:
name
- name of a flash
-
flash
Sends value to flash. Flash survives one more request. Using flash is typical for POST/GET pattern,- Parameters:
name
- name of value to flashvalue
- value to live for one more request in current session.
-
render
Renders results with a template. This call must be the last call in the action.- Parameters:
template
- - template name, must be "absolute", starting with slash, such as: "/controller_dir/action_template".values
- map with values to pass to view.- Returns:
- instance of
HttpSupport.RenderBuilder
, which is used to provide additional parameters.
-
redirect
Redirects to a an action of this controller, or an action of a different controller. This method does not expect a full URL.- Parameters:
path
- - expected to be a path within the application.- Returns:
- instance of
HttpSupport.HttpBuilder
to accept additional information.
-
redirect
Redirects to another URL (usually another site).- Parameters:
url
- absolute URL:http://domain/path...
.- Returns:
HttpSupport.HttpBuilder
, to accept additional information.
-
redirectToReferrer
Redirects to referrer if one exists. If a referrer does not exist, it will be redirected to thedefaultReference
.- Parameters:
defaultReference
- where to redirect - can be absolute or relative; this will be used in case the request does not provide a "Referrer" header.- Returns:
HttpSupport.HttpBuilder
, to accept additional information.
-
redirectToReferrer
Redirects to referrer if one exists. If a referrer does not exist, it will be redirected to the root of the application.- Returns:
HttpSupport.HttpBuilder
, to accept additional information.
-
redirect
protected <T extends AppController> HttpSupport.HttpBuilder redirect(Class<T> controllerClass, String action, Object id)Convenience method forredirect(Class, java.util.Map)
.- Parameters:
controllerClass
- controller class where to send redirect.action
- action to redirect to.id
- id to redirect to.- Returns:
HttpSupport.HttpBuilder
, to accept additional information.
-
redirect
protected <T extends AppController> HttpSupport.HttpBuilder redirect(Class<T> controllerClass, Object id)Convenience method forredirect(Class, java.util.Map)
.- Parameters:
controllerClass
- controller class where to send redirect.id
- id to redirect to.- Returns:
HttpSupport.HttpBuilder
, to accept additional information.
-
redirect
protected <T extends AppController> HttpSupport.HttpBuilder redirect(Class<T> controllerClass, String action)Convenience method forredirect(Class, java.util.Map)
.- Parameters:
controllerClass
- controller class where to send redirect.action
- action to redirect to.- Returns:
HttpSupport.HttpBuilder
, to accept additional information.
-
redirect
Redirects to the same controller, and action "index". This is equivalent toredirect(BooksController.class);
given that the current controller isBooksController
.- Returns:
HttpSupport.HttpBuilder
, to accept additional information.
-
redirect
Redirects to given controller, action "index" without any parameters.- Parameters:
controllerClass
- controller class where to send redirect.- Returns:
HttpSupport.HttpBuilder
, to accept additional information.
-
redirect
protected <T extends AppController> HttpSupport.HttpBuilder redirect(Class<T> controllerClass, Map params)Redirects to a controller, generates appropriate redirect path. There are two keyword keys expected in the params map: "action" and "id". Both are optional. This method will generate appropriate URLs for regular as well as RESTful controllers. The "action" and "id" values in the map will be treated as parts of URI such as:/controller/action/id
/controller/id/action
RESTful
and allowed on a GET URLs, which are: "edit_form" and "new_form". The map may contain any number of other key/value pairs, which will be converted to a query string for the redirect URI. Example: Method:redirect(app.controllers.PersonController.class, org.javalite.common.Collections.map("action", "show", "id", 123, "format", "json", "restrict", "true"));
/person/show/123?format=json&restrict=true
- Parameters:
controllerClass
- controller classparams
- map with request parameters.- Returns:
HttpSupport.HttpBuilder
, to accept additional information.
-
respond
This method will send the text to a client verbatim. It will not use any layouts. Use it to build app.services and to support AJAX.- Parameters:
text
- text of response.- Returns:
HttpSupport.HttpBuilder
, to accept additional information.
-
sendFile
Convenience method for downloading files. This method will force the browser to find a handler(external program) for this file (content type) and will provide a name of file to the browser. This method sets an HTTP header "Content-Disposition" based on a file name.- Parameters:
file
- file to download.delete
- true to delete the file after processing- Returns:
- builder instance.
-
sendFile
Convenience method for downloading files. This method will force the browser to find a handler(external program) for this file (content type) and will provide a name of file to the browser. This method sets an HTTP header "Content-Disposition" based on a file name.- Parameters:
file
- file to download.- Returns:
- builder instance.
-
getFile
Convenience method to get file content frommultipart/form-data
request. If more than one files with the same name are submitted, only one is returned.- Parameters:
fieldName
- name of form field from themultipart/form-data
request corresponding to the uploaded file.formItems
- form items retrieved frommultipart/form-data
request.- Returns:
InputStream
from which to read content of uploaded file or null if FileItem with this name is not found.
-
getHttpServletRequest
protected javax.servlet.http.HttpServletRequest getHttpServletRequest()Direct access to currentHttpServletRequest
for low level operations.- Returns:
- instance of current
HttpServletRequest
.
-
getHttpServletResponse
protected javax.servlet.http.HttpServletResponse getHttpServletResponse()Direct access to currentHttpServletResponse
for low level operations.- Returns:
- instance of current
HttpServletResponse
.
-
uploadedFiles
Returns a collection of uploaded files from a multi-part port request. Uses request encoding if one provided, and sets no limit on the size of upload.- Returns:
- a collection of uploaded files from a multi-part port request.
-
uploadedFiles
Returns a collection of uploaded files from a multi-part port request. Sets no limit on the size of upload.- Parameters:
encoding
- specifies the character encoding to be used when reading the headers of individual part. When not specified, or null, the request encoding is used. If that is also not specified, or null, the platform default encoding is used.- Returns:
- a collection of uploaded files from a multi-part port request.
-
uploadedFiles
Returns a collection of uploaded files from a multi-part port request.- Parameters:
encoding
- specifies the character encoding to be used when reading the headers of individual part. When not specified, or null, the request encoding is used. If that is also not specified, or null, the platform default encoding is used.maxFileSize
- maximum file size in the upload in bytes. -1 indicates no limit.- Returns:
- a collection of uploaded files from a multi-part port request.
-
multipartFormItems
Convenience method, callsmultipartFormItems(String)
. Does not set encoding before reading request.- Returns:
- a collection of uploaded files/fields from a multi-part request.
- See Also:
multipartFormItems(String)
-
multipartFormItems
Returns a collection of uploaded files and form fields from a multi-part request. This method uses DiskFileItemFactory. As a result, it is recommended to add the following to your web.xml file:<listener> <listener-class> org.apache.commons.fileupload.servlet.FileCleanerCleanup </listener-class> </listener>
For more information, see: Using FileUpload The size of upload defaults to max of 20mb. Files greater than that will be rejected. If you want to accept larger files, create a file calledactiveweb.properties
, add it to your classpath and place this property to the file:#max upload size maxUploadSize = 20000000
Alternatively, just call this method and pass a per-request parameter for the size:multipartFormItems(String, long)
.- Parameters:
encoding
- specifies the character encoding to be used when reading the headers of individual part. When not specified, or null, the request encoding is used. If that is also not specified, or null, the platform default encoding is used.- Returns:
- a collection of uploaded files from a multi-part request.
-
multipartForm
- Returns:
MultipartForm
object for convenience.
-
multipartForm
- Parameters:
encoding
- encoding to use to read values from requestmaxUploadSize
- set max upload size- Returns:
MultipartForm
object for convenience.
-
multipartFormItems
Returns a collection of uploaded files and form fields from a multi-part request. This method uses DiskFileItemFactory. As a result, it is recommended to add the following to your web.xml file:<listener> <listener-class> org.apache.commons.fileupload.servlet.FileCleanerCleanup </listener-class> </listener>
For more information, see: Using FileUpload- Parameters:
encoding
- specifies the character encoding to be used when reading the headers of individual part. When not specified, or null, the request encoding is used. If that is also not specified, or null, the platform default encoding is used.maxUploadSize
- maximum size of the upload in bytes. A value of -1 indicates no maximum.- Returns:
- a collection of uploaded files from a multi-part request.
-
getMap
Returns a map parsed from a request if parameter names have a "hash" syntax:<input type="text" name="account[name]" /> <input type="text" name="account[number]" />
will result in a map where keys are names of hash elements, and values are values of these elements from request. For the example above, the map will have these values:{ "name":"John", "number": "123" }
- Parameters:
hashName
- - name of a hash. In the example above, it will be "account".- Returns:
- map with name/value pairs parsed from request.
-
getMap
Convenience method to get parameter map in casemultipart/form-data
request was used. This method will skip files, and will only return form fields that are not files. Returns a map parsed from a request if parameter names have a "hash" syntax:<input type="text" name="account[name]" /> <input type="text" name="account[number]" />
will result in a map where keys are names of hash elements, and values are values of these elements from request. For the example above, the map will have these values:{ "name":"John", "number": "123" }
- Parameters:
hashName
- - name of a hash. In the example above, it will be "account".formItems
- form items retrieved frommultipart/form-data
request.- Returns:
- map with name/value pairs parsed from request.
-
setRequestEncoding
Sets character encoding for request. Has to be called before reading any parameters of getting input stream.- Parameters:
encoding
- encoding to be set.
-
setResponseEncoding
Sets character encoding for response.- Parameters:
encoding
- encoding to be set.
-
setEncoding
Sets character encoding on the response.- Parameters:
encoding
- character encoding for response.
-
encoding
Synonym forsetEncoding(String)
- Parameters:
encoding
- encoding of response to client
-
getEncoding
Controllers can override this method to return encoding they require. Encoding set in methodsetEncoding(String)
trumps this setting.- Returns:
- null. If this method is not overridden and encoding is not set from an action or filter, encoding will be set according to container implementation.
-
setContentLength
protected void setContentLength(int length)Sets content length of response.- Parameters:
length
- content length of response.
-
setLocale
Sets locale on response.- Parameters:
locale
- locale for response.
-
locale
Same assetLocale(java.util.Locale)
- Parameters:
locale
- locale for response
-
session
Returns reference to a current session. Creates a new session of one does not exist.- Returns:
- reference to a current session.
-
session
Convenience method, sets an object on a session. Equivalent of:session().put(name, value)
- Parameters:
name
- name of objectvalue
- object itself.
-
sessionObject
Convenience method, returns object from session, equivalent of:session().get(name)
- Parameters:
name
- name of object,- Returns:
- session object.
-
sessionString
Convenience method, returns object from session, equivalent of:String val = (String)session().get(name)
- Parameters:
name
- name of object- Returns:
- value
-
sessionInteger
Convenience method, returns object from session, equivalent of:Integer val = (Integer)session().get(name)
- Parameters:
name
- name of object- Returns:
- value
-
sessionBoolean
Convenience method, returns object from session, equivalent of:Boolean val = (Boolean)session().get(name)
- Parameters:
name
- name of object- Returns:
- value
-
sessionDouble
Convenience method, returns object from session, equivalent of:Double val = (Double)session().get(name)
- Parameters:
name
- name of object- Returns:
- value
-
sessionFloat
Convenience method, returns object from session, equivalent of:Float val = (Float)session().get(name)
- Parameters:
name
- name of object- Returns:
- value
-
sessionLong
Convenience method, returns object from session, equivalent of:Long val = (Long)session().get(name)
- Parameters:
name
- name of object- Returns:
- value
-
sessionHas
Returns true if session has named object, false if not.- Parameters:
name
- name of object.- Returns:
- true if session has named object, false if not.
-
sendCookie
Sends cookie to browse with response.- Parameters:
cookie
- cookie to send.
-
sendCookie
Sends cookie to browse with response.- Parameters:
name
- name of cookievalue
- value of cookie.
-
sendPermanentCookie
Sends long to live cookie to browse with response. This cookie will be asked to live for 20 years.- Parameters:
name
- name of cookievalue
- value of cookie.
-
header
Adds a header to response.- Parameters:
name
- name of header.value
- value of header.
-
applicationJSON
protected void applicationJSON()A convenience method. Sets the"Content-Type"
header on the response to"application/json"
. -
header
Adds a header to response.- Parameters:
name
- name of header.value
- value of header.
-
streamOut
Streams content of thereader
to the HTTP client.- Parameters:
in
- input stream to read bytes from.- Returns:
HttpSupport.HttpBuilder
, to accept additional information.
-
getRealPath
Returns a String containing the real path for a given virtual path. For example, the path "/index.html" returns the absolute file path on the server's filesystem would be served by a request for "http://host/contextPath/index.html", where contextPath is the context path of this ServletContext.. The real path returned will be in a form appropriate to the computer and operating system on which the servlet container is running, including the proper path separators. This method returns null if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive). JavaDoc copied from: http://download.oracle.com/javaee/1.3/api/javax/servlet/ServletContext.html#getRealPath%28java.lang.String%29- Parameters:
path
- a String specifying a virtual path- Returns:
- a String specifying the real path, or null if the translation cannot be performed
-
outputStream
Use to send raw data to HTTP client. Content type and headers will not be set. Response code will be set to 200.- Returns:
- instance of output stream to send raw data directly to HTTP client.
-
outputStream
Use to send raw data to HTTP client. Status will be set to 200.- Parameters:
contentType
- content type- Returns:
- instance of output stream to send raw data directly to HTTP client.
-
outputStream
Use to send raw data to HTTP client.- Parameters:
contentType
- content typeheaders
- set of headers.status
- status.- Returns:
- instance of output stream to send raw data directly to HTTP client.
-
writer
Produces a writer for sending raw data to HTTP clients. Content type content type not be set on the response. Headers will not be send to client. Status will be set to 200.- Returns:
- instance of a writer for writing content to HTTP client.
-
writer
Produces a writer for sending raw data to HTTP clients.- Parameters:
contentType
- content type. If null - will not be set on the responseheaders
- headers. If null - will not be set on the responsestatus
- will be sent to browser.- Returns:
- instance of a writer for writing content to HTTP client.
-
blank
Returns true if any named request parameter is blank.- Parameters:
names
- names of request parameters.- Returns:
- true if any request parameter is blank.
-
merge
Will merge a template and return resulting string. This method is used for just merging some text with dynamic values. Once you have the result, you can send it by email, external web service, save it to a database, etc.- Parameters:
template
- name of template - same as in regular templates. Example:"/email-templates/welcome"
.values
- values to be merged into template.- Returns:
- merged string
-
getResponseHeaders
Returns response headers- Returns:
- map with response headers.
-
sanitize
Cleans HTML from harmful tags, making XSS impossible.For example, input like this:
<html><script> alert('hello');</script><div>this is a clean part</div></html>
Will produce output like this:this is a clean part
- Parameters:
unsafeContent
- unsafe content. Something that an end user typed into a text area, or input that may include a script tag or other garbage.- Returns:
- sanitized version of input
-
getRequestInputStream
Returns InputStream of the request.- Returns:
- InputStream of the request
-
getRequestStream
Alias togetRequestInputStream()
.- Returns:
- input stream to read data sent by client.
-
getRequestString
Reads entire request data as String. Do not use for large data sets to avoid memory issues, instead usegetRequestInputStream()
.- Returns:
- data sent by client as string.
-
getRequestBytes
protected byte[] getRequestBytes()Reads entire request data as byte array. Do not use for large data sets to avoid memory issues.- Returns:
- data sent by client as string.
-
jsonList
Converts posted JSON array to a Java List. Example of a JSON array:[1, 2, 3]
.- Returns:
- Java List converted from posted JSON string.
-
jsonMap
Converts posted JSON map to a Java Map. Example JSON map:{"name":"John", "age":21}
.- Returns:
- Java Map converted from posted JSON string map.
-
jsonMaps
Converts posted JSON maps to a Java Maps array. Example JSON map:[{"name":"John", "age":21}, {"name":"Jane", "age":20}]
.- Returns:
- Java Maps converted from posted JSON string maps.
-
values
Returns a mutable Map with all the values from the current request context. Use this to get/put/modify values from current place on the stack down stream (from filters to controllers, to views).- Returns:
- a mutable
Map
with all values from/for current request context.
-