Details of how servlets are used

Source: Internet
Author: User

The life cycle approach of the servlet:

Init () Destroy () doget (httpservletrequest request,httpservletresponse response) client requests are encapsulated in the request, The server response is encapsulated in the response
-------------------------------------------------------------------------------configuration of Web. XML (multiple servlets configured with multiple Servlets and servlet-mapping tags)
<servlet>  <Servlet-name>Servelettest1</Servlet-name>       <Servlet-class>Com.web.servlet.Servelettest1</Servlet-class>//full path</servlet>  <servlet-mapping>                                                                    <Servlet-name>Servelettest1</Servlet-name>  <Url-pattern>/servelettest1</Url-pattern>//Browse request alias, preceded by Slash</servlet-mapping>
 Public void throws ioexception{               = Response.getwriter ();                              // This output stream is from the Web server to the browser, printed on the Web server        Pw.print ("Hello World");        Pw.close ();    }      Public void throws ioexception{        = response.getwriter ();        Pw.print ("Hello World");        Pw.close ();    }

In the index.jsp

<a href= "./servelettest1" >hello world<a><form action= "Servelettest1" method= "POST" >     //  Servelettest1 is <url-pattern>/Servelettest1</url-pattern><input type= "Submit" value= " Submit ">
Http://localhost:8088/Servelettest1//servelettest1 is <url-pattern>/servelettest1</url-pattern>http://localhost:8088/ index.jsp-----------------------------------------------------------------------------------using Request and responseresponse.ge Twriter ();             Get the client parameter method Request.getparameter ("username"); Get the parameter index.jsp corresponding code snippet for <a href= "Servelettest1?username=boyce" >hello world<a> The Servlet accepts the request encapsulation information:
 Public void throws ioexception{        = Request.getparameter ("username");                                          // Get user name        String Password = request.getparameter ("password");         = Response.getwriter ();        Pw.print ("Hello World" +username+password);        Pw.close ();    }

Corresponding JSP:

<form action= "Servelettest1" method= "POST" >              User account:<input type= "text" name= "username" >  User password:<input type= "password" name= "password" ><input type= "Submit" value= "Submit" ></form>
----------------------------------------------------------- Server.xml: Chinese garbled from client to server<connector port= "8080" protocol= "http/1.1" connectiontimeout= "20000"uriencoding= "Utf-8"redirectport= "8443"/> encountered Server.xml denied access solution: Go in and select Edit, and then select the user permission check Full Control can// Chinese garbled response.setcharacterencoding from server to client ("Utf-8"); Response.setcontenttype (Text/html;charset=utf-8) The servlet implements the page jump:
 PackageCom.web.servlet;Importjava.io.IOException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classServelettest2extendshttpservlet{ Public voidinit () {} Public voiddestroy () {} Public voidDoPost (httpservletrequest request,httpservletresponse response)throwsioexception{String uname= Request.getparameter ("username"); String Password= Request.getparameter ("Password"); System.out.println ("Servelet2 is called"); //page JumpResponse.sendredirect ("Servelettest3");//implement a page jump    }}

Method Two:

RequestDispatcher rd = Request.getrequestdispatcher ("Servelettest3"); Rd.forward (request,response);

INDEX.JSP:

<form action= "Servelettest2" method= "POST" >              User account:<input type= "text" name= "username" >  User password:<input type= "password" name= "password" ><input type= "Submit" value= "Submit" ></form>
dopost Chinese garbled solution:
 Public voidDoPost (httpservletrequest request,httpservletresponse response)throwsioexception{request.setcharacterencoding ("UTF-8");//troubleshoot the request server Chinese charactersResponse.setcharacterencoding ("UTF-8");//troubleshoot server-to-client garbled issuesResponse.setcontenttype ("text/html; Charset=utf-8 ");//troubleshoot server-to-client garbled issuesString username = request.getparameter ("username"); String Password= Request.getparameter ("Password"); PrintWriter PW=Response.getwriter (); Pw.print ("Hello World" +username+password); SYSTEM.OUT.PRINTLN (username+password);    Pw.close (); }

Filter:

<filter>  <filter-name>/filter1</filter-name>  <filter-class> com.web.servlet.characterfilter</filter-class>  </filter>  <filter-mapping>  <filter-name>/filter1</filter-name>  <url-pattern>/*</ Url-pattern>                                                       //asterisk means that all transmissions go through it  </filter-mapping>
 PackageCom.web.servlet;Importjava.io.IOException;ImportJavax.servlet.Filter;ImportJavax.servlet.FilterChain;ImportJavax.servlet.FilterConfig;Importjavax.servlet.ServletException;Importjavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse; Public classCharacterfilterImplementsfilter{@Override Public voiddestroy () {//TODO auto-generated Method Stub} @Override Public voidDoFilter (ServletRequest arg0, Servletresponse arg1, Filterchain arg2)throwsIOException, servletexception {//TODO auto-generated Method StubArg0.setcharacterencoding ("Utf-8"); Arg1.setcharacterencoding ("Utf-8"); Arg1.setcontenttype ("Text/html; Charset=utf-8 ");    Arg2.dofilter (arg0, arg1); } @Override Public voidInit (Filterconfig arg0)throwsservletexception {//TODO auto-generated Method Stub    }}
Listener: The servlet defines a variety of class listeners that are primarily used to listen on the three domain objects of servletcontext,httpsession and ServletRequest:   Httpsessionlistener interface for monitoring the creation and destruction of HttpSession   (1) When a session is created, the sessioncreated (httpsessionevent se) method is called. (2) When a session is destroyed, the Sessiondestroy (httpsessionevent se) method is called. session domain object creation and destruction timing created: Yoghurt when first accessed, the server creates a session destroy: If the user 30 minutes will be used, the server will be destroyed session, we can also in Web. XML The session Expiration time
<session-config>  <session-timeout>1</session-timeout>            // Set the listening time to one minute, If not modified, default is 30 minutes </session-config>
 PackageCom.web.servlet;ImportJavax.servlet.http.HttpSessionAttributeListener;Importjavax.servlet.http.HttpSessionBindingEvent;Importjavax.servlet.http.HttpSessionEvent;ImportJavax.servlet.http.HttpSessionListener;//Implement Interface Httpsessionlistener Public classOnlinecounterlistenerImplementshttpsessionlistener,httpsessionattributelistener{Private intCount=0; @Override Public voidsessioncreated (httpsessionevent arg0) {//TODO auto-generated Method Stubcount++; System.out.println ("There is a new user access, the current number of visitors is:" +count); } @Override Public voidsessiondestroyed (httpsessionevent arg0) {//TODO auto-generated Method Stubcount--; System.out.println ("There is an exit, the current number is:" +count); } @Override Public voidattributeadded (httpsessionbindingevent arg0) {//TODO auto-generated Method Stub} @Override Public voidattributeremoved (httpsessionbindingevent arg0) {//TODO auto-generated Method Stub} @Override Public voidattributereplaced (httpsessionbindingevent arg0) {//TODO auto-generated Method Stub    }}
Summary: Servlet step 1. Create a servlet Class (inherited from HttpServlet) 2. Three methods: public void init () {} public void Destroy () {} public void DoPost (HttpServletRequest request, httpservletresponse response) {}3. Gets the value in the JSP by GetParameter string username = Request. GetParameter ("username"); 4. Then call the JDBC or Hibernate class (Dao) to add or delete the object 5. Jump page//forward to the Registration results page Request.getrequestdispatcher ("result.jsp"). Forward (request, response);

Details of how servlets are used

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.