Servlet Clear Understanding

Source: Internet
Author: User

servlet Introduction

The servlet looks like a common Java program. It is the predecessor of JSP, the role of controller in the MVC architecture, namely the control layer. The main data processing operations and process control, and the results are stored in the JavaBean, and then the servlet use request forwarding or redirection request the view of the Touch JSP page update display.

Servlets are mainly used to process user requests, get the parameters of a user request, and, after processing them, return different JSP view pages to the user in different situations. Its core value is the process control. You should try to avoid using out streams in the servlet to enter a large number of HTML tags to display the data because this is the responsibility of the JSP page. Servle Frame

The framework of a servlet is comprised of two Java packages:

–javax.servlet package: Defines common interfaces and classes that all servlet classes must implement or extend.

–javax.servlet.http Package: Defines the HttpServlet class that communicates with the HTTP protocol.

The core of the servlet's framework is the Javax.servlet.Servlet interface, which all servlets must implement. There are five methods defined in the Servlet interface, three of which represent the life cycle of the servlet:

–init Method: Responsible for initializing the Servlet object;

The init () method is executed only once during the lifetime of the servlet. It is executed when the server loads the servlet. You can configure the server to get the servlet into the servlet at the start of the server or client for the first time. Init () is not repeated regardless of how many clients access the servlet.

–service Method: Responsible for responding to customer requests;

The Service () method is the entry point for the servlet program, and the servlet enters the method when the user calls the servlet from the browser. Service () contains two parameters, the HttpServletRequest object contains the information requested by the client, which can be used to obtain some information about the client (such as IP address, browser type, etc.) and the type of HTTP request (e.g., POST, put, etc.); The HttpServletResponse object is used to complete the interaction of the servlet with the client by calling HttpServletResponse. Getoutputstream () The client obtains an output stream to the client and sends an HTML page to the client.

In the service method of HttpServlet, first get the information of the HTTP request from the HttpServletRequest object, and then call the corresponding method according to the request mode. For example, if the request method is get, then the Doget method is called and the Dopost method is called if the request mode is post.

If your servlet class inherits the HttpServlet class, you usually do not have to implement the service method because the HttpServlet class has implemented the service method.

–destroy Method: When the Servlet object exits the life cycle, it is responsible for releasing the resource that is occupied.

The Destroy () method executes only once, which is executed when the server is stopped and the servlet is dismounted. Typically, the servlet is shut down as part of the server process. Servlet Small Example-Calculator

1. View (JSP page)

Used to interact with users and submit user requests.

calculation.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

Show processing results

calculationresult.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

2. Model (JavaBean)

The object used to store the data, mainly provides a simple setter and getter method, does not involve the processing details of the data.

Calculator.java

Package Com.kl.bean;public class Calculator {    String operator;    Double One,two,result;            Public String Getoperator () {        return operator;    }    Public Calculator () {        super ();    }    Public Calculator (String operator, double one, double, double, result) {        super ();        This.operator = operator;        This.one = one;        This.two = both;        This.result = result;    }    public void Setoperator (String operator) {        this.operator = operator;    }    Public double GetOne () {        return one;    }    public void Setone (double one) {        this.one = one;    }    Public double Gettwo () {        return;    }    public void Settwo (double) {        this.two = both;    }    Public double GetResult () {        return result;    }    public void Setresult (double result) {        This.result = result;    }    }

3. Controller (servlet)

Gets the user's request, parses the arithmetic expression, and evaluates the result. The request is then forwarded to the results page.

Calculatorhandler.java

Package Com.kl.servlet;import Java.io.ioexception;import Javax.servlet.servletexception;import javax.servlet.http. *;import Com.kl.bean.calculator;public class Calculatorhandler extends HttpServlet {public void doget (Httpservletreque St request, httpservletresponse Response) throws Servletexception, IOException {doPost (Request, respons    e); } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioex        ception {String expression=request.getparameter ("expression");//Get user request parameter double one=0;        Double two=0;        String operator= "";        SYSTEM.OUT.PRINTLN (expression); Parse arithmetic expression for (String S:operatorarr ()) {if (Expression.contains (s)) {one=double.parsed                Ouble (expression.split ("\ \" +s) [0]);                Two=double.parsedouble (expression.split ("\ \" +s) [1]);                Operator=s;  System.out.println (one+ "\ t" +two+ "\ T" +operator);              Break                }}//create JavaBean Storage data Calculator calculator=new Calculator (Operator,one,two,        Arithmetic (one, both, operator));        Store the created JavaBean object in the Request object and make the JavaBean name Request.setattribute ("Calculator", calculator);            Forward the request to the results page request.getrequestdispatcher ("calculationresult.jsp"). Forward (request, response);        }//Arithmetic method private double arithmetic (double one,double two,string operator) {double result = 0;        if (operator.equals ("+")) {result=one+two;        }else if (operator.equals ("-")) {result=one-two;        }else if (operator.equals ("*")) {result=one*two;        }else if (operator.equals ("/")) {result=one/two;    } return result;        } private string[] Operatorarr () {string[] arr={"+", "-", "*", "/"};    return arr; }}

Servlet clearly understood

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.