其他分享
首页 > 其他分享> > 8. 使用注解简化Servlet配置

8. 使用注解简化Servlet配置

作者:互联网

@WebServlet

通过使用注解,省去了去xml中配置的这一项,大大减轻工作量

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("/anno")
public class AnnotationServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.getWriter().print("这是一个 Annotation Servlet");
	}
}

启动时加载Servlet

在启动时就加载,提升运行速度

此处设置了loadOnStartup,同时还是必须设置urlPatterns地址才可以。
CreateServlet

@WebServlet(urlPatterns = "/create", loadOnStartup = 0)
public class CreateServlet extends HttpServlet {
	@Override
	public void init() throws ServletException {
		System.out.println("正在创建数据库");
	}
}

ImportServlet

@WebServlet(urlPatterns = "/import", loadOnStartup = 1)
public class ImportServlet extends HttpServlet {
	@Override
	public void init() throws ServletException {
		System.out.println("正在导入数据...");
	}
}

AnalysisServlet

@WebServlet(urlPatterns = "/analysis", loadOnStartup = 2)
public class AnalysisServlet extends HttpServlet {

	@Override
	public void init() throws ServletException {
		System.out.println("正在分析数据...");
	}
}

在这里插入图片描述
Servlet在启动的时候就进行了加载,常用作服务的启动加速

标签:ServletException,servlet,WebServlet,简化,import,注解,Servlet,public
来源: https://blog.csdn.net/qq_38496329/article/details/119336421