Servlet 01: 创建Servlet的两种方式

第一种创建方式:

1.  在Java Resources/src中, 创建一个Package: com.Jasper2003.servlet

2.

 Servlet 01: 创建Servlet的两种方式_第1张图片

 

 

     Servlet 01: 创建Servlet的两种方式_第2张图片

 

 

 3.  核心代码

@WebServlet("/RegisterServlet")  // 路径名(默认和类名保持一致)
public
class RegisterServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

如果将路径名改为:  @WebServlet("/register_do"), 则:

 

 第二种创建方式:

Servlet 01: 创建Servlet的两种方式_第3张图片

 

 在类中添加代码:

package com.Jasper2003.servlet;

import java.io.IOException;

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

@WebServlet("/demo_do")
public class DemoServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("I'm doGet method!");
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("I'm doPost method!");
    }
    
}

效果:

Servlet 01: 创建Servlet的两种方式_第4张图片

 

你可能感兴趣的:(Servlet 01: 创建Servlet的两种方式)