Servlet3.0版本之后,推出了Servlet基于注解式开发。
优点:开发效率高,直接在java类上使用注解进行标注,可直接省略WEB.xml文件配置
import javax.servlet.annotation.WebServlet;
@WebServlet
使用@WebServlet注解标注
@WebServlet的属性
name属性:用来指定Servlet的名字 == <servlet-name>
urlPatterns属性:用来指定Servlet的映射路径。可以指定多个路径 == <url-pattern>
loadOnstartUp属性:用来指定在服务器启动阶段是否加载该类。 == <load-on-startup>
value属性:和urlPatterns属性一样,都是用来指定Servlet映射路径(若使用value,则属性名可以省略)
@WebServlet(name ="demo" ,urlPatterns = {"/qgs/demoServlet1","/qgs/demoServlet2"}, loadOnStartup = 1,
initParams = {@WebInitParam(name ="demo1",value = "111"),@WebInitParam(name ="demo2",value = "222")})
public class DemoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//获取初始化参数
Enumeration<String> Names = request.getParameterNames();
while (Names.hasMoreElements()) {
String name = Names.nextElement();
String value = getInitParameter(name);
}
out.print("hello world :"+request.getContextPath());
}
}