在环境Java EE 6 + GlassFish v3 + NetBeans IDE 6.8 下的一个简单的Servlet程序:
- /**
- *
- * @author pylxy
- */
- @WebServlet(name="MyServlet", urlPatterns={"/MyServlet"})
- public class MyServlet extends HttpServlet {
- protected void processRequest(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html;charset=UTF-8");
- PrintWriter out = response.getWriter();
- try {
- out.println("<html>");
- out.println("<head>");
- out.println("<title>Servlet3.0 HelloWorld</title>");
- out.println("</head>");
- out.println("<body>");
- out.println("<h1>Hello! Servlet3.0规范</h1>");
- out.println("</body>");
- out.println("</html>");
- } finally {
- out.close();
- }
- }
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- processRequest(request, response);
- }
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- processRequest(request, response);
- }
- @Override
- public String getServletInfo() {
- return "Short description";
- }
- }
/**
*
* @author pylxy
*/
@WebServlet(name="MyServlet", urlPatterns={"/MyServlet"})
public class MyServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet3.0 HelloWorld</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello! Servlet3.0规范</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}
注解@WebServlet(name="MyServlet", urlPatterns={"/MyServlet"}),标识这一个类为Servlet类,当然这个类也要继承HttpServlet 类.name是区分不同Servlet类的一个标识,urlPatterns表示此Servlet访问的路径: 在浏览器访问路径为
http://localhost:8080/HelloWorld/MyServlet ,输出内容为:
Hello! Servlet3.0规范
基于注解的方式简化了编写Servlet,提高了开发效率!
除此之外,Servlet 3.0 规范随带了许多 web 开发新时代所需的最令人兴奋的特性!