首先写一个前端页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="/hello" method="post">
<input type="text" name="method"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
web.xml:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.hh.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
HelloServlet.java文件:
public class HelloServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//取得参数
String method = request.getParameter("method");
if (method.equals("add")){
request.getSession().setAttribute("msg","执行了add方法");
}
if (method.equals("delete")){
request.getSession().setAttribute("msg","执行了delete方法");
}
//业务逻辑
//视图跳转
request.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
hello.jsp文件:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>