当前位置:网站首页>Initial deployment of Servlet

Initial deployment of Servlet

2022-06-11 10:03:00 Fly upward

Catalog

1. servlet Main work

2.  first Servlet Program

2.1  Create project

 2.2 Introduce dependencies

 2.3 Create directory

2.4   Write code

2.5  packaged applications

 2.6  The deployment process

 2.7  Verification procedure

 2.8 summary

3. Easier deployment  

3.1  install Smart Tomcat plug-in unit

3.2 To configure Smart Tomcat plug-in unit

4. Common error problems

4.1  appear 404

4.2  appear 405

 4.3  appear 500

 4.4  appear " Blank page "

 4.5  appear " Can't access this website "

 5. summary


1. servlet Main work

       servlet Is a technology to realize dynamic pages , It's a group. Tomcat For programmers API, Help group programmers develop a simple and efficient web app. Without concern Socket,HTTP Form of agreement , Multithreading concurrency and other technical details , To reduce the web app The development threshold of , Improved development efficiency rate .

Servlet The main work is
      Allow programs to register a class ,, stay Tomcat Receive a specific HTTP On request ,, Execute some code in this class .
      The helper resolves HTTP request , hold HTTP The request parses from a string into a HttpRequest object .
      Help program ape construct HTTP Respond to . The program only needs to be assigned to HttpResponse Fill in some properties of the object  ,Servlet It will be installed automatically HTTP A protocol is constructed HTTP Response string ,, And pass Socket Write back to the client .

2.  first Servlet Program

2.1  Create project

Use IDEA Create a Maven project .
1) menu -> file -> New projects -> Maven

2) Select the directory where the project will be stored

 3) Project creation completed

 2.2 Introduce dependencies

Maven After the project is created , It will automatically generate a pom.xml file . We need to be in pom.xml Introduction in Servlet API Rely on the jar package . This API No JDK Built in , It's a third party Tomcat Provided .Maven Central warehouse address :
https://mvnrepository.com/ , It's going on inside Servlet API Copy , Copy the code from step 5 below to pom.xml Inside .

<dependencies>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

When it was first copied , It is marked in red , That's because of our IDEA Not downloaded yet .jar package . This requires us to manually click IDEA On the top right of Maven Refresh icon for , Just wait for the download .

 2.3 Create directory

When the project is created , IDEA Will help us automatically create some directories . Form like

however , These directories are not enough , We need to manually add some necessary directories .

1)webapp

2) establish web.xml
And then in webapp Create a... Inside the directory WEB-INF Catalog , And create a web.xml file
3) To write web.xml
Go to web.xml Copy the following code in
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
    <display-name>Archetype Created Web Application</display-name>
</web-app>

, If in IDEA in , The following code appears in red , Do the following .

2.4   Write code

stay java Create a class in the directory HelloServlet, The code is as follows

import javax.servlet.annotation.WebServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // This line of code needs to be commented out , Cannot reference a parent class's  doGet
        //super.doGet(req, resp);

        // This is to let the server print in its own console 
        System.out.println("hello world");
        // You can also print on the page  hello world  character string , Put it in  http  Responsive  body  in .  The browser will put  body  The content of 
        // Show on page 
        // If nothing is set in the response object ,  This is the time when   Blank page 
        resp.getWriter().write("hello world" + System.currentTimeMillis());
    }
}

In the above code :

- Create a class HelloServlet , Inherited from HttpServlet
- Add... Above this class @WebServlet("/hello") annotation , Express Tomcat Of the requests received , Path is /hello Will only call HelloServlet The code for this class . ( This path does not contain Context Path)
-   rewrite doGet Method . doGet There are two parameters to , Respectively represent the received HTTP request And the... To be constructed HTTP Respond to .. this individual Methods in Tomcat received GET Trigger on request
- HttpServletRequest Express HTTP request . Tomcat according to HTTP The format of the request is character string Format request to Become a HttpServletRequest object . Later, I want to get the information in the request ( Method , url, header, body etc. ) All are Get... Through this object
- HttpServletResponse Express HTTP Respond to . Construct the response object in the code ( Construct the status code of the response , header,
body etc. )
-resp.getWriter() Will get a stream object , Through this stream object, you can write some data , The written data will be Construct into a HTTP Responsive body part , Tomcat Will turn the entire response into a string , adopt socket Write back to browse device .
Be careful , The class you want to write Can be Tomcat call , You have to meet the following conditions
a) The created class needs to inherit from HttpServlet
b) This class needs to use @WebServlet The annotation is associated with the previous HTTP The path of
c) This class needs to implement doXXX Method

2.5  packaged applications

Current code , It can't run alone ( No, main Method ) Current code , It can't run alone ( No, Main Method )
Need to put the current code , pack , And then deploy to Tomcat. On , from Tomcat To make the call ,  Need to put the current code , pack , And then deploy to Tomcat. On , from Tomcat To make the call .

Before packing , First in pom.xml Add a  <packaging>war</packaging> , Because we packed war package , If not , Will default to jar package .

jar and war All are java The compressed package format used by the publisher .war It's for Tomcat Specialized in . There will not only be some .class, You can also include configuration files , And the second 3 Tripartite jar , also html, Css, js....
Add location as follows

Use maven package . open maven window ( Generally in IDEA On the right you can see Maven window , If you can't see it , Can pass menu -> View -> Tool Window -> Maven open
And then unfold Lifecycle , double-click package You can pack it .

  When the console appears  BUILD SUCCESS, And the directory list appears servlet_hello.war It indicates that the packaging is successful

 2.6  The deployment process

  After the open hold war Package copy to Tomcat Of webapps Under the table of contents . Then start Tomcat , Tomcat Will automatically put war Packet decompression .

 2.7  Verification procedure

Enter the URL of the direct deployment through the browser , You can get a response  http://127.0.0.1:8080/servlet_hello/hello, as follows

  Be careful : URL Medium PATH Divided into two parts , among servlet_hello  by Context Path, hello by Servlet Path

 2.8 summary

These seven steps , This is for a new project , After the project is created , Subsequent modification code , The first three steps need not be repeated . Directly from 4—7 Just operate .

3. Easier deployment  

Copy manually war Package to Tomcat The process is quite troublesome . We have a more convenient way . Here we use IDEA Medium Smart Tomcat The plug-in does the job .

3.1  install Smart Tomcat plug-in unit

menu -> file -> Settings -> choice Plugins, choice Marketplace, Search for "tomcat", Click on "Install".
After installation , Will prompt " restart IDEA"

3.2 To configure Smart Tomcat plug-in unit

1) Click on the "Add Configuration. 2) Click on + Number ,3) Choose the one on the left "Smart Tomcat"
4) stay Name Fill in a name in this column ( I could just write ).5) choice Tomcat Installation path for

  Click the green triangle , IDEA Will automatically compile , Deploy

start-up Tomcat The process of , The font is red , It is not an error that makes it red .

Use Smart Tomcat When deployed , We found that Tomcat Of webapps There is no copy inside war package ,
I didn't see the decompressed content .Smart Tomcat Quite so in Tomcat When starting, it directly refers to... In the project webapp and target Catalog .

4. Common error problems

4.1  appear 404

404 Indicates that the resource accessed by the user does not exist . The approximate rate is URL The path of is not written correctly .
 1) Write less. Context Path namely servlet_hello

 2) Write less. Servlet Path namely hello

 3)Servlet Path It's written and URL No match

modify @WebServlet Path to annotation , The correct here is as follows

  Error is as follows

 4)web.xml Write the wrong

4.2  appear 405

405 Indicates the corresponding HTTP The request method is not implemented .
1) It didn't come true doGet Method .
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
// Be annotated out , So it didn't come true doGet  Method 
  //@Override
    //protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { }
}

 4.3  appear 500

To be Servlet The exception thrown in the code results in .
Error instance : Modify the code
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServlet Requestreq, HttpServlet Responseresp) throws Servlet Exception, IOException {
        String s = null;
        resp.getWriter().write(s.length());
    }
}

 4.4  appear " Blank page "

Error instance : Modify the code , Comment out  resp.getWritter().write() operation .

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // This line of code needs to be commented out , Cannot reference a parent class's  doGet
        //super.doGet(req, resp);

        // This is to let the server print in its own console 
        System.out.println("hello world");
        // You can also print on the page  hello world  character string , Put it in  http  Responsive  body  in .  The browser will put  body  The content of 
        // Show on page 
        // If nothing is set in the response object ,  This is the time when   Blank page 
        //resp.getWriter().write("hello world" + System.currentTimeMillis());
    }
}

 4.5  appear " Can't access this website "

It's usually Tomcat The startup failed .
 
Error instance : Servlet Path Write the wrong .
// hold 
@WebServlet("/hello")
// It has been written. , Just missing one  /
@WebServlet("hello")

 5. summary

Beginners Servlet, There will be many such problems . We don't just have to learn Servlet The basic way of writing code , Also learn Troubleshoot the wrong .
4xx The status code of indicates that the path does not exist , Often need to check URL Whether it is right , And the... Set in the code Context Path as well as
Servlet Path Is it consistent .
5xx The status code of indicates that the server has an error , You often need to observe the content and content of the page prompt Tomcat Your own journal , Observe if
There is an error .
A connection failure often means Tomcat Not started correctly , Also need to observe Tomcat Whether there is an error prompt in your own log .
This situation of blank pages requires us to use the packet capture tool to analyze HTTP The specific interaction process of request response .
原网站

版权声明
本文为[Fly upward]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110936387517.html