Package lazyj
Class ExtendedServlet
java.lang.Object
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
lazyj.ExtendedServlet
- All Implemented Interfaces:
Serializable,javax.servlet.Servlet,javax.servlet.ServletConfig,javax.servlet.SingleThreadModel
public abstract class ExtendedServlet
extends javax.servlet.http.HttpServlet
implements javax.servlet.SingleThreadModel
Probably the most important class in the world :)
This class is a wrapper over the original HttpServlet, adding caching and run time limit for the servlets. There are also other useful functions, like
This class is a wrapper over the original HttpServlet, adding caching and run time limit for the servlets. There are also other useful functions, like
initMultipartRequest(String, int) for
uploading files, getX (s/i/f/d) for parsing the parameters and getting the correct value, getCookie(String), setCookie(String, String), log(int, String)- Since:
- 2006-10-02
- Author:
- costing
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected booleanServlets can treat GET and POST differently based on the method they override or by looking at this variableprotected booleanRemember whether or not there was a redirect executed by the servletCurrent sessionstatic final longThis is when the server was startedprotected com.oreilly.servlet.MultipartRequestObject used for file uploading.protected OutputStreamOutputStream to the clientprotected PrintWriterPrintWriter to the client.protected javax.servlet.http.HttpServletRequestThe original request objectprotected javax.servlet.http.HttpServletResponseThe original response objectprotected StringCurrent servlet that is executedprotected StringThe zone of the currently executed servlet -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionfinal voiddoGet(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) Original request from servlet engine comes through here.protected voiddoInit()This is a hook provided for the servlets as a generic way to initialize their local variables, do authentication and so on.final voiddoPost(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) Original request from servlet engine comes through here.static final StringProduce safe SQL strings.static final StringProduce save HTML strings.abstract voidexecGet()A servlet must implement at least this method.voidexecPost()By default POST request are executed with the sameexecGet()function.protected intgetApp()Get the application number.final booleanstatic final longStatistics: get the total number of accesses to pages that could be cachedstatic final longStatistics: get the number of cache hitsprotected StringOverride this method to return any value that would alter the cache.protected longMethod to specify the maximum life time of the cached contents.final StringGet the value of a specific cookiefinal StringCompose the full URL to the current page.final doubleGet the value of a parameter as a double value.final doubleGet the value of a parameter as a double value.protected StringMethod to specify the domain for which the cookies will be set by default (session cookie included).final floatGet the value of a parameter as a float value.final floatGet the value of a parameter as a float value.static final longFramework statistics: get the total number of requests serviced by the framework.final StringGet the client host address (IP).final StringGet the nice host name for the client that made the current request.final intGet the value of a parameter as an integer value.final intGet the value of a parameter as an integer value.final longGet the value of a parameter as a long value.final longGet the value of a parameter as a long value.protected intMethod to specify the maximum run time for a page.protected intGet the number of online users for the current application.final StringGet the value of a parameter as a string.final StringGet the value of a parameter as a string.static final StringStatistics: get the server uptimefinal String[]Get all the values of a parameter.protected final booleaninitMultipartRequest(String sTempDir, int iFileSizeLimit) This method should be called when the servlet expects a file upload from the client.booleanisLoggable(int iLevel) Find out whether or not the current page is able to log this level of debug.booleanFlag to set whether or not the session is valid only when used from the first IP that generated the session.voidLog messages with a given level of the problem.voidSpecial logging for exceptions.voidOverride the method provided by the Java Servlet Api to log messages as DEBUGprotected final booleanWrapper method for the actual redirect, that keeps track if there was such an opperation.voidsetContentType(String sContentType) If you set the content type to something else than "text/html; charset=UTF-8" and you use the caching mechanism you should use this method instead of directly callingresponse.setContentTypebooleanSend a session cookie to the browser.booleanSend a cookie to the browser.booleanSend a cookie to the browser.protected voidzoneInit()Override this function to initialize local servlet or zone variables (pMaster for example)Methods inherited from class javax.servlet.http.HttpServlet
doDelete, doHead, doOptions, doPut, doTrace, getLastModified, service, serviceMethods inherited from class javax.servlet.GenericServlet
destroy, getInitParameter, getInitParameterNames, getServletConfig, getServletContext, getServletInfo, getServletName, init, init, log
-
Field Details
-
lServerStarted
public static final long lServerStartedThis is when the server was started -
request
protected javax.servlet.http.HttpServletRequest requestThe original request object -
response
protected javax.servlet.http.HttpServletResponse responseThe original response object -
osOut
OutputStream to the client -
pwOut
PrintWriter to the client. Same as osOut, but other interface -
sPage
Current servlet that is executed -
sZone
The zone of the currently executed servlet -
mpRequest
protected com.oreilly.servlet.MultipartRequest mpRequestObject used for file uploading. SeeinitMultipartRequest(String, int). -
bRedirect
protected boolean bRedirectRemember whether or not there was a redirect executed by the servlet -
bGet
protected boolean bGetServlets can treat GET and POST differently based on the method they override or by looking at this variable -
dbs
Current session
-
-
Constructor Details
-
ExtendedServlet
public ExtendedServlet()
-
-
Method Details
-
getCacheKeyModifier
Override this method to return any value that would alter the cache. Usually you will want to return here the username, if the user is logged. Or the value of some cookie, if it alters the contents of the caching ...- Returns:
- some string that is appended to the caching key.
-
getCacheAccesses
public static final long getCacheAccesses()Statistics: get the total number of accesses to pages that could be cached- Returns:
- the total number of pages served through this framework
-
getCacheHits
public static final long getCacheHits()Statistics: get the number of cache hits- Returns:
- the number of pages served from a memory cache by this framework
-
getServerUptime
Statistics: get the server uptime- Returns:
- Server uptime, as formatted string
-
getFrameworkRequests
public static final long getFrameworkRequests()Framework statistics: get the total number of requests serviced by the framework.- Returns:
- total number of requests to servlets that extend the framework
-
getCacheTimeout
protected long getCacheTimeout()Method to specify the maximum life time of the cached contents. You should override this method to return the number of seconds for which you know that the contents will not change and it's safe to serve the users the same contents.
This method returns 0 in the default implementation, meaning that the caching is by default disabled for all the servlets.- Returns:
- number of seconds for which the contents is valid, default is 0 (cache disabled)
-
getDomain
Method to specify the domain for which the cookies will be set by default (session cookie included). You should override this method to return something like ".acasa.ro".- Returns:
- the domain for which the cookies will be set by default
-
getMaxRunTime
protected int getMaxRunTime()Method to specify the maximum run time for a page. After this much time (in seconds) the thread that runs the page is forcefully killed. Override this method if you want to allow a maximum execution time different than the default 60 seconds.
In special (read very very unlikely cases) you can return 0 to disable the threads monitoring. This means that this thread is allowed to run forever, and if it does something bad, nobody will catch it. So, you've been warned ...- Returns:
- the maximum run time, in seconds, for the current page.
-
execGet
public abstract void execGet()A servlet must implement at least this method. -
execPost
public void execPost() -
getApp
protected int getApp()Get the application number. Each major application should have a different, unique, identifier. This is to distinguish between the sessions, which ones are for which application, when creating statistics. SeegetOnlineUsers()for example.- Returns:
- application unique number
-
isSessionIPProtected
public boolean isSessionIPProtected()Flag to set whether or not the session is valid only when used from the first IP that generated the session. In some cases (multiple load-balancing http proxies) this schema might not work.- Returns:
- true by default, but can be overriden by actual implementations
-
setContentType
If you set the content type to something else than "text/html; charset=UTF-8" and you use the caching mechanism you should use this method instead of directly callingresponse.setContentType- Parameters:
sContentType-
-
gets
Get the value of a parameter as a string.- Parameters:
sParam- the parameter name- Returns:
- the string value of this parameter, never null ("" is returned in the worst case)
-
gets
Get the value of a parameter as a string.- Parameters:
sParam- the parameter namesDefault- default value to return in case the value is not defined or is the empty string- Returns:
- the string value of this parameter
-
geti
Get the value of a parameter as an integer value. If there is a parsing error then return the given default value.- Parameters:
sParam- the name of the parameterdefaultVal- default value to return in case of an error- Returns:
- parsed value of the parameter, or the defaultValue if parameter is missing or is not an integer value representation
-
geti
Get the value of a parameter as an integer value. If there is a parsing error then the value 0 will be returned.- Parameters:
sParam- name of the parameter- Returns:
- parsed value of the request parameter, or 0 if there is any error in parsing, parameter not existing etc
-
getl
Get the value of a parameter as a long value. If there is a parsing error then return the given default value.- Parameters:
sParam- the name of the parameterdefaultVal- default value to return in case of an error- Returns:
- parsed value of the parameter, or the defaultValue if parameter is missing or is not a long value representation
-
getl
Get the value of a parameter as a long value. If there is a parsing error then the value 0 will be returned.- Parameters:
sParam- name of the parameter- Returns:
- parsed value of the request parameter, or 0 if there is any error in parsing, parameter not existing etc
-
getf
Get the value of a parameter as a float value. If there is a parsing error then return the given default value.- Parameters:
sParam- the name of the parameterdefaultVal- default value to return in case of an error- Returns:
- parsed value of the parameter, or the defaultValue if parameter is missing or is not a float value representation
-
getf
Get the value of a parameter as a float value. If there is a parsing error then the value 0 will be returned.- Parameters:
sParam- name of the parameter- Returns:
- parsed value of the request parameter, or 0 if there is any error in parsing, parameter not existing etc
-
getd
Get the value of a parameter as a double value. If there is a parsing error then return the given default value.- Parameters:
sParam- the name of the parameterdefaultVal- default value to return in case of an error- Returns:
- parsed value of the parameter, or the defaultValue if parameter is missing or is not a double value representation
-
getd
Get the value of a parameter as a double value. If there is a parsing error then the value 0 will be returned.- Parameters:
sParam- name of the parameter- Returns:
- parsed value of the request parameter, or 0 if there is any error in parsing, parameter not existing etc
-
getValues
Get all the values of a parameter.- Parameters:
sParam-- Returns:
- values array, possibly empty but never null
-
getb
- Parameters:
sParam-defaultValue-- Returns:
- the boolean value of this parameter
-
redirect
Wrapper method for the actual redirect, that keeps track if there was such an opperation. This is done in order to disable the caching in this case.- Parameters:
sURL- the URL to send the browser to- Returns:
- true if the operation was successfully, false if there was an error
-
esc
Produce safe SQL strings. Wrapper forFormat.escSQL(String)call.- Parameters:
s- the string to escape- Returns:
- the SQL-safe representation
-
escHtml
Produce save HTML strings. Wrapper forFormat.escHtml(String)call.- Parameters:
s- the string to escape- Returns:
- the HTML-safe representation
-
getCookie
Get the value of a specific cookie- Parameters:
sName- the name of the cookie- Returns:
- the value of the cookie, or "" if there was an error (cookie not existing ...)
-
setCookie
Send a session cookie to the browser. The cookie is made available to the domain returned by thegetDomain()function- Parameters:
sName- name of the cookiesValue- value- Returns:
- true on success, false on error
-
setCookie
Send a cookie to the browser. The cookie is made available to the domain returned by thegetDomain()function- Parameters:
sName- name of the cookiesValue- valueiAge- lifetime of the cookie, in seconds, relative to "now". Negative=session cookie. Zero=delete this cookie.- Returns:
- true on success, false on error
-
setCookie
Send a cookie to the browser.- Parameters:
sName- name of the cookiesValue- valuesDomain- the domain for which this cookie is setiAge- lifetime of the cookie, in seconds, relative to "now". Negative=session cookie. Zero=delete this cookie.- Returns:
- true on success, false on error
-
doInit
protected void doInit()This is a hook provided for the servlets as a generic way to initialize their local variables, do authentication and so on. Generally this is implemented in each zone's local master servlet and checks for user's session. You probably want to override this. Use this to initialize only the variables used ingetCacheTimeout()andgetCacheKeyModifier(). For IO-related variables (eg pMaster) usezoneInit(). -
zoneInit
protected void zoneInit()Override this function to initialize local servlet or zone variables (pMaster for example) -
doGet
public final void doGet(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) Original request from servlet engine comes through here. It will be handled internally.- Overrides:
doGetin classjavax.servlet.http.HttpServlet- Parameters:
req- servlet requestresp- servlet response
-
doPost
public final void doPost(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) Original request from servlet engine comes through here. It will be handled internally.- Overrides:
doPostin classjavax.servlet.http.HttpServlet- Parameters:
req- servlet requestresp- servlet response
-
initMultipartRequest
This method should be called when the servlet expects a file upload from the client. It will initialize thempRequestobject. If the file is too big or there is another problem uploading the file then the method will return false, if everything is ok then it will return true.- Parameters:
sTempDir- temporary folder for the files that are uploadediFileSizeLimit- maximum size of a file- Returns:
- true if the request is indeed a file upload, the file size is <= iFileSizeLimit and the weather outside is fine
-
getOnlineUsers
protected int getOnlineUsers()Get the number of online users for the current application. SeegetApp()for this.- Returns:
- the number of online users (active sessions)
-
getHostName
Get the nice host name for the client that made the current request. If possible this will return the reversed DNS name, or if this is not available the plain IP address.- Returns:
- client's address
-
getHostAddr
Get the client host address (IP).- Returns:
- the client's IP address
-
getCurrentPage
Compose the full URL to the current page. Use this when you want for example to force the user to first authenticate, and when this operation succeeds to return it to the page it was initially trying to access.- Returns:
- the URL of the current page
- See Also:
-
log
Override the method provided by the Java Servlet Api to log messages as DEBUG- Overrides:
login classjavax.servlet.GenericServlet- See Also:
-
GenericServlet.log(java.lang.String)log(int, String)
-
log
Log messages with a given level of the problem. SeeLogfor possible logging levels.- Parameters:
level- problem levelsMessage- error message
-
log
Special logging for exceptions. It can be used to log any other objects too, but if the passed object is not a Throwable instance it will simply call toString() for it and that's it.- Parameters:
level- problem levelsMessage- error messageo- object to be logged, special case when the object is a Throwable instance
-
isLoggable
public boolean isLoggable(int iLevel) Find out whether or not the current page is able to log this level of debug. You should check for this function's result prior to actually logging something big or something that would require some processing power.- Parameters:
iLevel- desired logging level- Returns:
- true if a message at this level would be logged, false if not
-