First, servlet package
Web development
Javax.Servlet. * and javax.servlet.http. * Two packages and interfaces. There is only one genericservlet class in the Javax.Servlet package, which is inherited by httpservlet. Others belong to javax.servlet.http
Declare servlet class aaservlet
Public class aaservlet
Extends httpservlet {
}
Second, the life cycle of sevlet
1, loading and initialization.
INIT () method
The servlet can only perform an init () method before the end. The init method loads running when the browser requests servlet or web server.
Public void init () throws servletexception {}
Public void init (servletConfig conf) throws servletexception {super.init (conf); // init method must have this code when the servletconfig parameter must have
// Write some initialization operations. Such as connecting the database, etc.
}
Public void init (servletconfig conf) throws servletexception {
Super.init (conf); // init method must have this code when the servletconfig parameter
UserName = GetInitParameter ("UserName"); if (username == null) {throw new unavailableException (this, "error!");}} 2, servlet (often use DOPOST, Doget method)
Use service () to process customer requests. The frequent usage is: do not use the service () method, with the dopost, doget method to process the request. Other methods have dotrace (), doOptions (). Dohead () method, due to trace, options.Head information is already in dopost, doget method, do not have to be used, doPut (), Dodelete () method is not often in Web App use
3, end
Recycled with Destroy () method.
Public void design () {} public void design () {super.dedtroy (conf);}, there is also common dopost (), doget (), doget (), and service () method, these methods require HTTPSERVLETREQUEST and HTTPSERVLETRESPONSE objects make parameters, throws servletexception and ioException exception.
Fourth, HTTPSERVLETREQUEST common method:
GetRealPath, GetInputStream, GetContentType, getContentlengh ...
Get the root of the server
String path = Request.getRealPath ("."); Get input stream
DataInputStream DIN = New DataInputStream ());
V. HTTPSERVLETRESPONSE objects commonly used:
Sendredirect, GetWriter, SetContentType, GetOutputStream.
Set file type
Private static final string content_type = "text / html; charset = GB2312"; response.setContentType (content_type); output HTML file header information:
PrintWriter out = response.getwriter ();
Out.close (); httpsession encapsulates the details of the session, gets a session object with the GetSession () method of the HTTPServletRequest object, and returns null.getations () equivalent and getsession (TRUE) when using getSession (false).
When is the session established? Create when the browser is started, only to the browser close, called a session.
HttpSession session = reg.getsession (false); if (session == null) {res. extendedirect ("error.htm");}