servlet小demo

新建一个javaweb项目,然后添加依赖


        
            javax.servlet
            javax.servlet-api
            3.0.1
        
package com.bruce;

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

@WebServlet(description = "Servlet示例", name = "hello", urlPatterns = {"/MyFirst"}, loadOnStartup = 1)
public class ServletDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().append("my frist servlet");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
        System.out.println("do post");
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("Servlet初期化" + config.getServletName());
    }

    @Override
    public ServletConfig getServletConfig() {
        return super.getServletConfig();
    }

    @Override
    public String getServletInfo() {
        return super.getServletInfo();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Servlet处理请求");
        response.setCharacterEncoding("UTF-8");
        //告诉浏览器输出的内容是html,并且以utf-8的编码来查看这个内容。
        response.setContentType("text/html;charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.println("你好,这是来自Servlet的消息:Hello World!");
    }

    @Override
    public void destroy() {
        System.out.println("Servlet销毁");
    }
}

在servlet3.0+可以不用在web.xml配置servlet,可以直接使用注解@WebServlet




    Archetype Created Web Application
    
        
        
    
    
        
        
    


你可能感兴趣的:(servlet小demo)