JavaWeb study notes 20/10/12Servlet

Servlet

1. 1 Introduction to Servlet

  • Servlet is a technology developed by Sun to develop dynamic Web. The Java program that implements the Servlet interface is called Servlet.
  • Sun provides an interface in these APIs called: Servlet, if you want to develop a Servlet program, you only need to complete two small steps:
    • Write a class to implement the Servlet interface
    • Deploy the developed Java classes to the web server

1. 2 HelloServlet

Serlvet interface Sun has two default implementation classes: HttpServlet, GenericServlet

  1. Understanding of the Maven father and son project:

    There will be:

        <modules>
            <module>servlet-01</module>
        </modules>
    

    There will be:

        <parent>
            <artifactId>javaweb-02-servlet</artifactId>
            <groupId>com.weng</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
    

    The jar package subproject in the parent project can be used directly

    son extends father
    
  2. Maven environment optimization

    • Modify web.xml to the latest
    • Complete the structure of maven
  3. Write a Servlet program

    • Write a normal class
    • Implement Servlet interface, here directly inherit Http
    public class HelloServlet extends HttpServlet {
          
          
        //由于get或post只是请求实现的不同方式,可以相互调用,业务逻辑一样
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          
          
            System.out.println("进入doGet方法");
            //ServletOutputStream outputStream = resp.getOutputStream();
            PrintWriter writer = resp.getWriter();//响应流
            writer.print("Hello,Servlet");
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          
          
            doPost(req, resp);
        }
    }
    
  4. Write Servlet mapping

    Why do I need to map?

    We write a Java application, but we need to access it through a browser, and the browser needs to connect to the Web server, so we need to register the Servlet we wrote in the Web service, and we need to give it a path that the browser can access;

    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.weng.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    
  5. Configure Tomcat

    Pay attention to the path of project release

  6. Start the test

Guess you like

Origin blog.csdn.net/qq_44685947/article/details/109032793