Servlet summary

Why study Servlet

Java Web The evolution process can be divided into 4 Stages :

  • Servlet + jdbc + jsp
  • Spring + Struts2+ Hibernate(SSH)
  • Spring + SpringMVC + Mybatis(SSM)
  • Microservice stage

The first two stages are basically history , Today, Spring The family rules the world .

Now it is rarely used directly in actual development Servlet 了 , But the bottom layer of each framework is still heavily used Servlet, Study Servlet It is very helpful for the understanding and learning of the following frameworks .

What is? Servlet

Servlet Is running on the Web A program on a server or application server , It's as coming from Web Browser or something HTTP Client requests and HTTP The middle tier between databases or applications on the server .

Servlet It's really just a follow Servlet Developed java class .Serlvet yes Called by the server , Running on the server side .

Servlet The most important effect is to be able to Dealing with browsers brings HTTP request , And return a response to the browser , So as to realize the interaction between browser and server .

Workflow

  • Tomcat Encapsulate the request submitted by the browser as HttpServletRequest object , At the same time, the output stream is encapsulated as HttpServletResponse object

  • Tomcat hold request、response As a parameter , call Servlet The corresponding method of , for example doGet(request, response) etc.

  • Servlet It mainly deals with business logic


Life cycle

stay Web In the container ,Servlet The main experience 4 Stages , Here's the picture :

  1. load Servlet. When Tomcat First visit Servlet When ,Tomcat Will be responsible for creating Servlet Example
  2. initialization . When Servlet When instantiated ,Tomcat Meeting call init() Method to initialize this object
  3. Processing services . When browser visit Servlet When ,Servlet Meeting call service() Method to process the request
  4. The destruction . When Tomcat When closed or detected Servlet From you to Tomcat When you delete it, it will automatically call destroy() Method , Let the instance free up the occupied resources . One Servlet If it's not used for a long time , Will also be Tomcat Automatically destroy
  5. uninstall . When Servlet Call complete destroy() After the method , Waiting for garbage collection .

If It's necessary to use this again Servlet, Will recall init() Method to initialize .

Just visit Servlet,service() It will be called .init() Only the first visit Servlet When it is called .

destroy() Only in Tomcat It's called when it's closed .


How to handle the request

Servlet It is realized. Servlet Interface Class , Realization Servlet Interface When , Need to achieve 5 A way

public interface Servlet {
void init(ServletConfig var1) throws ServletException; ServletConfig getServletConfig(); void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException; String getServletInfo(); void destroy();
}

For ease of use, you can directly Inherit HttpServlet class , This class has been implemented by default Servlet All methods in the interface .

Writing Servlet When , Just rewrite the method you need .

And this class is still in the original Servlet The interface adds some and HTTP Protocol processing related methods .

  • Servlet There are three ways to handle requests :

    • Realization service() Method
    • rewrite doGet()
    • rewrite doPost()

HttpServletRequest and HttpServletResponse

about Each visit request ,Servlet engine Will create a new HttpServletRequest Request object And a new HttpServletResponse The response object , namely request and response object .

HttpServletRequest Common methods

  • String getContextPath()

    Get context path
  • String getHeader(String headName)

    Get the value of the corresponding request header according to the specified request header .
  • String getRequestURI()

    Returns the resource name of the current request . Context path / Resource name
  • StringBuffer getRequestURL()

    Return to the browser address bar
  • String getRemoteAddr()

    Return to the client of the requesting server IP

Method to get request parameters :

  • String getParameter(String name)

    According to the parameter name , Get the value of the corresponding parameter .
  • String[] getParameterValues(String name)

    According to the parameter name , Get multiple values of the parameter .
  • Enumeration getParameterNames()

    Get the names of all request parameters
  • Map<String,String[]> getParameterMap()

    Return the request parameter Map aggregate .

HttpServletResponse Common methods

  • OutputStream getOutputStream():

    Get byte output stream : File download

  • Writer getWriter()

    Get character output stream : Output content

  • resp.setContentType("text/html;charset=utf-8")

    Set the encoding format and content type of file output

  • resp.sendRedirect()

    302 Redirect , A temporary jump

    301 Use another method

Servlet Is a singleton

explain

The browser has done this many times Servlet Request , In general , The server only creates one Servlet object , in other words ,Servlet object Once created , will Resident in memory , Serve subsequent requests , Until the server shuts down .

Every time you access the request object and the response object are new

For each access request ,Servlet The engine will create a new HttpServletRequest Request object and a new HttpServletResponse The response object , And then we put these two objects As a parameter Passed to it to call Servlet Of service() Method ,service() Method and then call other methods according to the request mode .

Thread safety problem

When multiple users access Servlet When , The server creates a thread for each user . When multiple users access concurrently Servlet When sharing resources, there will be thread safety problems .

principle

  1. If a variable It needs to be shared by multiple users , When accessing the variable , It needs to be locked
  2. If a variable No need to share , be Directly in doGet() perhaps doPost() Definition , There will be no thread safety issues

Configure by annotation Servlet

In previous development work , Write one at a time Servlet Need to be in web.xml File to configure

<servlet>
<servlet-name>ActionServlet</servlet-name>
<servlet-class>com.web.controller.ActionServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>ActionServlet</servlet-name>
<url-pattern>/servlet/ActionServlet</url-pattern>
</servlet-mapping>

And when there's a lot in a project Servlet, Then the configuration file will become very messy , stay Servlet 3.0 After launch , We can use annotations to configure Servlet

@WebServlet(name = "ActionServlet", urlPatterns = "/servlet/ActionServlet")

Web How to jump between components

Request forwarding (forward)

Also known as Direct forwarding , Clients and browsers Only one request ,Servlet、HTML、JSP Or other information resources , from The second information resource responds to the request , In the request object request in , Saved objects for Every information resource is shared .

such as : from AServlet Request forwarding to BServlet

  • grammar :
request.getRequestDispatcher(path).forward(request, response);

Parameters :path, The resource path to jump to : Context path / Resource path

  • characteristic :

    • The address in the address bar remains unchanged
    • There's only one request
    • Resources are shared
    • You can visit WEB-INF The resource
    • Request forwarding You can't Cross domain access

URl Redirect (redirect)

Also known as Indirect forwarding (Redirect) the truth is that two HTTP request , When the server responds to the first request , Let the browser go to another URL Request , So as to achieve the purpose of forwarding .

such as : from AServlet Redirect to BServlet

  • grammar :
response.sendRedirect(String location);

Parameters :location, Resource path to forward to

  • characteristic :

    • The address in the address bar 【 Meeting 】 Change
    • There are two requests
    • In two Servlet The data in the request cannot be shared in
    • The final response is given by BServlet To decide , and AServlet It doesn't matter.
    • No access WEB-INF The resource
    • Request forwarding Sure Cross domain access

Reference resources

Java-Servlet More articles on knowledge summary

  1. Java Servlet Complete tutorial

    Servlet It's some compliance Java Servlet API Of Java class , these Java Class can respond to requests . Even though Servlet Can respond to any type of request , But the most widely used of them is response web A request from . Servle ...

  2. Java Servlet Technical introduction

    Java Servlet Technical introduction Java Developer and trainer Roy Miller Take what we have servlet The introduction material has been modified into this easy to learn practical course .Roy Will introduce and explain servlet What is it? ...

  3. 【Java】Java Servlet Technical introduction

    Java Developer and trainer Roy Miller Take what we have servlet The introduction material has been modified into this easy to learn practical course .Roy Will introduce and explain servlet What is it? , How they work , How to use them to create ...

  4. JavaWeb And Java Servlet Complete tutorial ( turn )

    Servlet It's some compliance Java Servlet API Of Java class , these Java Class can respond to requests . Even though Servlet Can respond to any type of request , But the most widely used of them is response web A request from . Servle ...

  5. Java Basic knowledge summary ( Super classic )

    Java Basic knowledge summary ( Super classic ) Write code : 1, Clear requirements . What should I do ? 2, Analysis methods . What should I am going to do? ?1,2,3. 3, Determine steps . What statements are used in each thinking part , Method , And the object . 4, Code implementation . Use specific java ...

  6. Java To develop knowledge Java introduction

    Java To develop knowledge Java introduction 1. Understand JAVA Version of JAVA There are three versions JAVA SE: The standard version , Developing desktop and business applications JAVA SE It includes Java Core class library of , aggregate ,IO Database connection And the net ...

  7. Bi Xiangdong —Java Basic knowledge summary ( Super classic )

    Java Basic knowledge summary ( Super classic ) Write code : 1, Clear requirements . What should I do ? 2, Analysis methods . What should I am going to do? ?1,2,3. 3, Determine steps . What statements are used in each thinking part , Method , And the object . 4, Code implementation . Use specific java ...

  8. Java Interview knowledge 1

    JAVA Interview question set Basic knowledge of : 1.C++ or Java The simple principle and application of exception handling mechanism in .     When JAVA The procedure violated JAVA The semantic rules of ,JAVA The virtual machine will express the error as an exception . Semantic violations include 2 ...

  9. precipitation , Start again :Java Basic knowledge summary

    precipitation , Start again :Java Basic knowledge summary One . Preface No matter how far you go , Basic knowledge is the most important , This knowledge is the foundation stone and reinforced concrete for building high-rise buildings . about Java This language covers all aspects of programming , There's too much basic knowledge , From the initial ...

  10. Black horse Bi Xiangdong Java Basic knowledge summary

    Java Basic knowledge summary ( Super classic ) from : Baidu library   Black horse Bi Xiangdong JAVA Basic summary notes     Invasion and deletion ! Write code : 1, Clear requirements . What should I do ? 2, Analysis methods . What should I am going to do? ?1,2,3. 3, Determine steps . Every thought Department ...

Random recommendation

  1. sizeof Learn to understand

    The following is from : http://www.cnblogs.com/ComputerG/archive/2012/02/02/2335611.html Bo asked Flash memory home page New essay contact management essays - 72  ...

  2. 【iOS Development must collect 】 Detailed explanation iOS Within the application IAP/StoreKit pay 、 Sandbox (SandBox) test 、 Create test account process !【2012-12-11 Daily update to get ” The number of products paid is equal to 0 The problem of ”】

    It's someone else's Seeing many children's shoes, I asked , Why does the quantity returned each time equal to 0?? In fact, some children's shoes have been found out , The reason is that you are ItunesConnect Inside “Contracts, Tax, and Banking” Not completed ...

  3. android Set up eclipse Automatic prompt function in

    menu window->Preferences->Java->Editor->Content Assist->Enable auto activation  Check the options ( and ...

  4. HDU 4337 King Arthur&amp;#39;s Knights It outputs a Hamiltonian circuit

    n integral m The article has no direction It outputs a Hamiltonian circuit #include <cstdio> #include <cstring> #include <iostream> usin ...

  5. Android Some knowledge of process recycling

    About OOM_ADJ explain : Android A situation in which a process is easily killed : Reference resources :Android A complete set of moves to keep the process alive

  6. ●BZOJ 2669 [cqoi2012] Local minima

    Question chain : http://www.lydsy.com/JudgeOnline/problem.php?id=2669 Answer key : A class ,DP,DFS Have a look first dp part : First of all ,X The number of will not exceed 8 individual . The number is very ...

  7. Scrapy Crawler encounter ‘Forbidden by robots.txt’ The problem of

    Today is climbing the essence , There is ‘Forbidden by robots.txt’ The problem of Learn that scrapy In the crawler settings url Before , It will first request a txt file , This document specifies the scope of crawling scra ...

  8. reg and wire difference

    reg Equivalent to a storage unit ,wire It's equivalent to a physical connection Verilog The physical data of variables in are divided into line type and register type . These two types of variables are defined with bit width , Default is 1 position . Each bit of the variable can be 0,1,X,Z. among x It represents an unprepared ...

  9. github ignore standard

    from :https://www.cnblogs.com/xuld gitignore It should contain 5 Block content : Files that need to be ignored in the current project Files that need to be ignored by the nature of the project ( For example nodejs project , Some documents need to be ignored ...

  10. bzoj1002/luogu2144 Rotavirus (dp)

    Number the points around 1 To n We set up f[i] by (1 To i And the middle point ) The number of connected blocks , So there are $f[i]=\sum{f[i-j]*j}$, It's from i-j+1 To i Choose one of them to connect to the center , Then take it. i-j+1 To i Chain up but ...