Package com.groiss.servlet
Class ServletUtils
java.lang.Object
com.groiss.servlet.ServletUtils
Utility methods to use in servlets.
-
Field Summary
-
Method Summary
Modifier and TypeMethodDescriptionstatic void
addModificationInfo
(HttpServletRequest req, HttpServletResponse resp, long lastModified, Locale locale) Adds some header fields to the response so we can determine modification on the next request.static void
addModificationInfo
(HttpServletRequest req, HttpServletResponse resp, long lastModified, Locale locale, String ctx) Adds some header fields to the response so we can determine modification on the next request
adds anETag
and aLast-Modified
-Headerstatic void
check if the session is an admin session and throw exception if it is not.static void
checkSessionIP
(HttpServletRequest req, HttpServletResponse res, HttpSession s) Checks if the remote address of the request matches the address in session attribute "ip".static void
checkURL
(HttpServletRequest req, String url) Check the permissibility of the request with the URLChecker.static Locale
Read the locale from the browser.static String
Returns the context path of the web application.static String
getParameterFromQuery
(String queryString, String paramName) Parse a String in the same manner as a querystring of an HttpServletRequest would be parsed and extract one parameter from it.static String
getParameterFromURL
(String urlString, String paramName) Parse a String in the same manner as an URL of an HttpServletRequest would be parsed and extract one parameter from it (all elements up to and including the first question mark are removed first).static String
Returns the a string of the follwing form: <protocol>://<hostname>:<port>/<contextpath>static void
init()
Initialize the ServletUtils.static Boolean
This method return TRUE if admin port or address is specified and the request uses this connector.static boolean
check if the session is an admin sessionstatic boolean
isAllowed
(HttpServletRequest req, HttpServletResponse res, List<String> allowedMethods, String allowedMethodsString, org.slf4j.Logger effectiveLogger) Determines if the method of an HttpRequest is allowed.static boolean
isModifiedSince
(HttpServletRequest req, long lastModified, Locale l) returnstrue
if the requested resource has been modified since the last request.static boolean
isModifiedSince
(HttpServletRequest req, long lastModified, Locale l, String ctx) Returnstrue
if the requested resource has been modified since the last request.static void
logParameters
(HttpServletRequest req, org.slf4j.Logger effectiveLogger) Logs the parameters of an HttpRequest at log level INFO.static HttpServletRequest
logRequest
(HttpServletRequest req, HttpServletResponse res, org.slf4j.Logger effectiveLogger) Log the parameters of an HttpRequest.static void
logRequestProcessed
(long startTime, HttpServletRequest req, HttpServletResponse resp) Logs the duration of an HttpRequest.static void
If no user is currently logged in, it's required, that some resources are not cached, so the user gets the new files as soon he loggs in.static Locale
Deprecated.static Locale
setLocale
(HttpServletRequest req, Principal u) Set the threadcontext Locale and return it.static void
Sets appropriate headers on the response to avoid caching.static void
Sets appropriate headers on the response to avoid caching and to avoid intermediate transformations (e.g. compression).static void
Sets appropriate headers on the response to enable private caching This must be called before the response is committed.static void
setThreadTimeZone
(HttpServletRequest req, HttpSession s, TimeZone tz, org.slf4j.Logger l) Sets the time zone in the threadcontext from a number of sources.static void
writeHeaders
(HttpServletResponse res, Page page) Write the headers of a page to the response.static void
writeToResp
(HttpServletRequest req, HttpServletResponse res, Page page, String pageStr, Throwable t) Write a page to the response.static void
writeToResp
(HttpServletResponse res, Page page) Write a page to the response.static void
writeToResp
(HttpServletResponse res, String pageStr) Write a string to the response.
-
Field Details
-
ADMIN_SESSION
Name of the Session attribute to determine if it is an admin session.- See Also:
-
ADMIN_URL
Fully qualified name of the main entry method to the administration.- See Also:
-
-
Method Details
-
init
public static void init()Initialize the ServletUtils. Automatically called by startup and at configuration change. -
getContextPath
Returns the context path of the web application. -
getServerAddress
Returns the a string of the follwing form: <protocol>://<hostname>:<port>/<contextpath>- Parameters:
req
- the current request
-
isAdminSession
check if the session is an admin session -
isAdminConnector
This method return TRUE if admin port or address is specified and the request uses this connector. It returns FALSE if the connector is not used and null if no extra connector is defined. -
checkAdminSession
check if the session is an admin session and throw exception if it is not. -
logRequest
public static HttpServletRequest logRequest(HttpServletRequest req, HttpServletResponse res, org.slf4j.Logger effectiveLogger) Log the parameters of an HttpRequest. Will also wrap the request within a MultiPartRequest if it was "POST"ed and the content type was "multipart/form-data". Wrapping is avoided when the query string contains "preserveRequest". Will also add "Cache-Control: private" header to the response.- Parameters:
req
- the requestres
- the responseeffectiveLogger
- the loger to use. If it is null the logger of ServletUtils will be used.- Returns:
- the request.
-
logParameters
Logs the parameters of an HttpRequest at log level INFO. Single parameters longer than 128 characters are truncated in the output. Parameters named "password" or "avw_password" are masked as sequence of asterisks.- Parameters:
req
- the requesteffectiveLogger
- the logger to use.
-
logRequestProcessed
public static void logRequestProcessed(long startTime, HttpServletRequest req, HttpServletResponse resp) Logs the duration of an HttpRequest. If the duration of the request was longer than the configuration parameter "httpd.response.timeout.threshold", then it is logged at loglevel WARN. If the state of the response isHttpServletResponse.SC_INTERNAL_SERVER_ERROR
, is logged at level WARN, else loglevel DEBUG is being used.- Parameters:
startTime
- the start time of the request.req
- the requestresp
- the response
-
isAllowed
public static boolean isAllowed(HttpServletRequest req, HttpServletResponse res, List<String> allowedMethods, String allowedMethodsString, org.slf4j.Logger effectiveLogger) throws IOException Determines if the method of an HttpRequest is allowed. If the used method is not contained in the allowedMethods, then an error is send back withHttpServletResponse.SC_METHOD_NOT_ALLOWED
.- Parameters:
req
- the request to checkres
- the response to send the error backallowedMethods
- a list of Strings containing the permissible methods.allowedMethodsString
- the string of methods to be used foe the "allow" response header.effectiveLogger
- the logger to use. Requests with non permissible methods are logger at level WARN.- Returns:
- true if the methos is permissible, false else.
- Throws:
IOException
-
checkURL
Check the permissibility of the request with the URLChecker. ThreadPrincipal must be set before calling this method.- Parameters:
req
- the request as context for the checkurl
- the url to check
-
checkSessionIP
Checks if the remote address of the request matches the address in session attribute "ip". Throws ApplicationException 466 if it does not match. Check is only carried out if configuration parameter "ep.check.ip" is set. Also calls IpChangeListener.- Parameters:
req
-s
-
-
addModificationInfo
public static void addModificationInfo(HttpServletRequest req, HttpServletResponse resp, long lastModified, Locale locale) Adds some header fields to the response so we can determine modification on the next request. adds anETag
and aLast-Modified
-Header- Parameters:
req
- requestresp
- responselastModified
- last modification timestamplocale
- the current locale
-
addModificationInfo
public static void addModificationInfo(HttpServletRequest req, HttpServletResponse resp, long lastModified, Locale locale, String ctx) Adds some header fields to the response so we can determine modification on the next request
adds anETag
and aLast-Modified
-Header- Parameters:
req
- requestresp
- responselastModified
- last modification timestamplocale
- the current locale
-
isModifiedSince
returnstrue
if the requested resource has been modified since the last request. the following methods are used:- check the
ETag
-header - check the
if-modified-since
- header
- Parameters:
req
- requestlastModified
- last modification timestampl
- the current locale- Returns:
true
if the resource has been modified since the last request,false
otherwise
- check the
-
isModifiedSince
public static boolean isModifiedSince(HttpServletRequest req, long lastModified, Locale l, String ctx) Returnstrue
if the requested resource has been modified since the last request.
the following methods are used:- check the
ETag
-header - check the
if-modified-since
- header
- Parameters:
req
- requestlastModified
- last modification timestampl
- the current localectx
- an optional context-string to be appended to the etag- Returns:
true
if the resource has been modified since the last request,false
otherwise
- check the
-
setExpiresImmediatelyForGuest
If no user is currently logged in, it's required, that some resources are not cached, so the user gets the new files as soon he loggs in.- Parameters:
req
-res
-
-
writeToResp
Write a page to the response. First the headers are written, then the content is written.- Parameters:
res
- the response to write topage
- the page to write.
-
writeToResp
Write a string to the response. First tries to use the writer of the response. If the writer is not available, the output stream of the response is being used.- Parameters:
res
- the response to write topageStr
- the string to write
-
writeHeaders
Write the headers of a page to the response.- Parameters:
res
- the response to write topage
- the page which headers are to be written
-
writeToResp
public static void writeToResp(HttpServletRequest req, HttpServletResponse res, Page page, String pageStr, Throwable t) Write a page to the response. If the Throwable is not null, an error response will be generated. Else, First, the headers are written, then the content is dealt with. If pageStr is not null, it will be used, the page content is ignored. Else, the page Content will be written.- Parameters:
req
- the requestres
- the reponse to write topage
- the page to write (if pageStr is null)pageStr
- the string to writet
- the throwable
-
setLocale
Deprecated.UsesetLocale(HttpServletRequest,Principal)
insteadSets the threadcontext locale and return it. -
setLocale
Set the threadcontext Locale and return it. Also sets the HttpSession "locale" attribute. The locale is retrieved from the following locations, in the given order:- from the HttpSession "locale" attribute
- the browser locale (if "locale.from.browser" is configured)
- the locale of the user associated with the passed Principal (if not null)
- locale from the guest user
- locale from the "{serverid}_locale" cookie
- default locale
- Parameters:
req
- the request to useu
- the user to use (may be nul)- Returns:
- the locale
-
getBrowserLocale
Read the locale from the browser. The "Accept-Language" header of the request is used in combination with the available locales on the Server (seeSettings.getAvailableLocales()
). If no match with the available locales could be made or in case of a missing request header,Locale.getDefault()
is returned.- Parameters:
req
- the request to read the initial locale value from- Returns:
- the locale
-
setThreadTimeZone
public static void setThreadTimeZone(HttpServletRequest req, HttpSession s, TimeZone tz, org.slf4j.Logger l) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException Sets the time zone in the threadcontext from a number of sources.- Parameters:
req
- the HttpServletRequests
- the HttpSessiontz
- an initial time zonel
- the logger to use- Throws:
IllegalAccessException
InvocationTargetException
NoSuchMethodException
-
setNoCache
Sets appropriate headers on the response to avoid caching. This must be called before the response is committed.- Parameters:
res
- the HttpServletResponse
-
setNoTransform
Sets appropriate headers on the response to avoid caching and to avoid intermediate transformations (e.g. compression). This must be called before the response is committed.- Parameters:
res
- the HttpServletResponse
-
setPrivateCache
Sets appropriate headers on the response to enable private caching This must be called before the response is committed.- Parameters:
res
- the HttpServletResponse
-
getParameterFromURL
Parse a String in the same manner as an URL of an HttpServletRequest would be parsed and extract one parameter from it (all elements up to and including the first question mark are removed first).- Parameters:
urlString
- the string the parameter is to be extracted fromparamName
- the name of the parameter to extract from urlString- Returns:
- the extracted parameter value, or null
-
getParameterFromQuery
Parse a String in the same manner as a querystring of an HttpServletRequest would be parsed and extract one parameter from it. The query string is the part of the URL that starts after the first question mark.- Parameters:
queryString
- the string the parameter is to be extracted fromparamName
- the name of the parameter to extract from queryString- Returns:
- the extracted parameter value, or null
-
setLocale(HttpServletRequest,Principal)
instead