Servlets & JavaBean

Source: Internet
Author: User

1.servelet

    1. What is a servlet?
      ①servlet is the Java class
      ②servlet is a class that inherits the HttpServlet class
      ③ This server-side operation to process client requests
    2. Introduction to Servlet related packages
      --javax.servlet.*: Store generic servlet classes unrelated to the HTTP protocol;
      --javax.servlet.http.*: In addition to inheriting javax.servlet.*, it also adds functionality related to the HTTP protocol.
      (Note: It is necessary to learn the HTTP protocol, as Web development will involve)
      All servlets must implement the Javax.servlet.Servlet interface (Interface).
      If the servlet program is not related to the HTTP protocol, then the Javax.servlet.GenericServlet class must be inherited;
      If the servlet program is related to the HTTP protocol, then the Javax.servlet.http.HttpServlet class must be inherited.
      --httpservlet: An abstract class was provided to create an HTTP Servlet.
         Public void Doget () method:Used to handle a GET request made by a client
         Public void DoPost () method:Used to process post requests
      There are several ways to check the API Help files yourself.
      --Javax.servlet the interface of the package:
      ServletConfig Interface:
      Used by the servlet container during initialization
      ServletContext Interface:Defines a method that the servlet uses to obtain information from its container
      ServletRequest Interface:Request information from the server
      Servletresponse Interface:Responding to client requests
      Filter Interface:
      Class of--javax.servlet Package:
      ServletInputStream class
      : Used to read binary data from the client
         Servletoutputstream class: Used to send binary data to the client
      --javax.servlet.http the interface of the package:
      HttpServletRequest Interface:
      Provide HTTP request information
      HttpServletResponse Interface:Provide HTTP response
    3. Servlet life cycle
      The--servlet life cycle refers to the time that exists and when the servlet instance was created, and when the entire process was destroyed.
      The--servlet life cycle has three methods
        init () method :
        Service () method : Dispatches client requests to the protected method service
        Destroy () method : Called by the servlet container to indicate to a servlet, the servlet is being taken out of servi Ce.
      --servlet stages of the life cycle
      ---- instantiation : servlet container creation servlet instance
      ---- initialization : Calling the init () method
      ---- Service : If there is a request, call the service () method
      ---- Destroy : Call the Destroy () method before destroying the instance
      ---- garbage collection : destroying instances
    4. The basic structure of the servlet
       PackageCn.dragon.servlet;//The following is the import of the appropriate packageImportjava.io.IOException;ImportJava.io.PrintWriter;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/*** This is the first example of a servlet *@authorCn.dragon*/ Public classServletdemofirstextendsHttpServlet {//used to process a GET request sent by a client     Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {response.setcontenttype ("text/html;charset=gb2312");//This statement indicates the format of the content sent to the client and the character encoding used. PrintWriter out=Response.getwriter (); Out.println (Hello ");//to send data to the client using the method of the PrintWriter objectOut.close (); }//for handling post requests sent by clients     Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response);//The purpose of this statement is to call the Doget () method for processing when the client sends a POST request}}
    5. Deployment of Servlets
      <servlet>    <description> any </description>    <display-name> any </display-name>    <servlet-name>ServletDemoFirst</servlet-name>    <servlet-class> cn.dragon.servlet.servletdemofirst</servlet-class>  </servlet> <servlet-mapping>    <servlet-name>ServletDemoFirst</servlet-name>    <url-pattern>/servlet/ servletdemofirst</url-pattern>  </servlet-mapping> "Note" ① above two <servlet-name>  must be the same ② <servlet-class > back is referred to the corresponding class above.  Tip: You can copy it directly from your servlet class to avoid mistakes! ③ <url-pattern> must be/servlet to add the servlet name. Everybody just remember now.
    6. Servlet Instance Demo
       PackageCn.dragon.servlet;Importjava.io.IOException;ImportJava.io.PrintWriter;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classServletdemosecondextendsHttpServlet {//Initialize      Public voidInit ()throwsservletexception {System.out.println ("I Am the init () Method!" Used for initialization work "); }//Handling GET Requests      Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {System.out.println ("I Am the Doget () Method!" Used to process a GET request "); Response.setcontenttype ("text/html;charset=gb2312"); PrintWriter out=Response.getwriter (); Out.println ("<HTML>"); Out.println ("<BODY>"); Out.println ("This is an example of a servlet."); Out.println ("</BODY>"); Out.println ("</HTML>"); }//Processing Post Requests      Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }//Destroying Instances      Public voiddestroy () {Super. Destroy (); System.out.println ("I Am the Destroy () Method!" The work used to destroy the instance "); }} web. xml file<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.4"xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd "><servlet> <servlet-name>ServletDemoSecond</servlet-name> <servlet-class>cn.dragon.servlet.servletdemosecond</servlet-class> </servlet> <servlet-mapping> <servlet-name>ServletDemoSecond</servlet-name> <url-p Attern>/servlet/servletdemosecond</url-pattern> </servlet-mapping></web-app>

2.javabean

JavaBean is a Java component that conforms to a specification, that is, a Java class.

It must meet the following specifications:

1) must have a default constructor for a 0 parameter

2) must have get and set methods, the fields of the class must pass the GET and set
method to access it.
(Get method no parameter, set method has parameters)

Let's look at a javabean example below.

General page login requires a user name and password, we can put the user name and password in the JavaBean.

The code is as follows:

 PackageMytrain.formbean; Public classUserBean {PrivateString name; PrivateString password;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }         PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; }}

There are 2 methods of access:Direct AccessAndJSP Tag Access
(However, we recommend access via tags)
1) Direct Access
A) declaring the bean
Import the JavaBean class at the top of the page: <%@ page import= "Mytrain.formbean.userBean"%>
Instantiate class in JSP segment: <% userBean user = new UserBean (); %>
b) Accessing the Bean
<% user.setxxx (aa);%>
<%=user.getxxx ();%>
2) Tag access (recommended)
a) declaring the bean
Use Userbean Tags:
<jsp:usebean id= "user" class= "Mytrain.formbean.userBean"/>
b) Accessing the Bean
set by setproperty tag:
<jsp:setproperty name= "user" property= "name" param= "Musername"/>
Through the GetProperty tag to obtain:
<jsp:getproperty name= "user" property= "name"/>
Let's take a look at the complete code.

Tag access method:<%@ page language= "java" pageencoding= "GBK"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >class= "Blue10" > User name:</span> </td> <td> <input type= "text" name= "Musername" size= "><br> </td> </tr> <tr> <td> <spanclass= "Blue10" > Password:</span> </td> <td> <input type= "password" name= "Mpassword" size= "><br" > </td> </tr> <tr> <td> </td> <td> &nbsp;&nbsp;&nbsp;&nbsp ;&nbsp;&nbsp;&nbsp;&nbsp; <input type=submit value= "Submit"/> </td> </tr> </table> </form> <jsp:usebean id= "us Erclass= "Mytrain.formbean.userBean"/> <jsp:setproperty name= "user" property= "name" param= "Musername"/> <jsp: SetProperty name= "user" property= "password" param= "Mpassword"/> User name:<jsp:getproperty name= "user" property= "name"/> <br>Password:<jsp:getproperty name= "user" property= "password"/> </body>
Direct access Method:<%@ page language= "java" pageencoding= "GBK"%><%@ pageImport= "Mytrain.formbean.userBean"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >class= "Blue10" > User name:</span> </td> <td> <input type= "text" name= "Musername" size= "><br> </td> </tr> <tr> <td> <spanclass= "Blue10" > Password:</span> </td> <td> <input type= "password" name= "Mpassword" size= "><br" > </td> </tr> <tr> <td> </td> <td> &nbsp;&nbsp;&nbsp;&nbsp ;&nbsp;&nbsp;&nbsp;&nbsp; <input type=submit value= "Submit"/> </td> </tr> </table> </form> <%UserBean User=NewUserBean (); User.setname (Request.getparameter ("Musername")); User.setpassword (Request.getparameter ("Mpassword")); %> User name:<%=user.getname ()%> <br>Password:<%=user.getpassword ()%> </body>

Servlet & JavaBean

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.