Servlet

Servlet - 图1

配置文件 web.xml

  1. <servlet>
  2. <servlet-name>HelloServlet</servlet-name>
  3. <servlet-class>com.zmy.HelloServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>HelloServlet</servlet-name>
  7. <url-pattern>/helloServlet</url-pattern>
  8. </servlet-mapping>
  9. <!--<session-config>
  10. <session-timeout
  11. </session-config>-->
  12. <!--<welcome-file-list>
  13. <welcome-file>index.jsp</welcome-file>
  14. </welcome-file-list>-->

注解 Servlet.java

  1. @WebServlet(name = "HelloServlet",urlPatterns = "/hello")
  2. public class HelloServlet extends HttpServlet {
  3. @Override
  4. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  5. //1.获取前端参数
  6. String method = req.getParameter("method");
  7. if (method.equals("add")){
  8. req.getSession().setAttribute("msg","执行了add方法");
  9. }
  10. if (method.equals("delete")){
  11. req.getSession().setAttribute("msg","执行了delete方法");
  12. }
  13. //2.调用业务层
  14. //3.视图转发或者重定向
  15. req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp);
  16. }
  17. @Override
  18. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  19. super.doPost(req, resp);
  20. }
  21. }

test.jsp

  1. <html>
  2. <head>
  3. <title>Title</title>
  4. </head>
  5. <body>
  6. ${msg}
  7. </body>
  8. </html>