@WebServlet使用注解来实现servlet和url的映射。
1、HelloServlet.java。
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("/hello") public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setAttribute("usercode", "9001"); req.getRequestDispatcher("/WEB-INF/view/hello.jsp").forward(req, resp); } }
2、WEB-INF/view/hello.jsp。
<%@ page pageEncoding="UTF-8" %> <html> <head> <title>Hello</title> </head> <body> <h1>Hello ${usercode}</h1> </body> </html>
3、http://localhost:8080/demo/hello