一、web.xml配置文件
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
二、JSP页面
<a href="find.do"> Find</a>
<p />
<a href="add.do"> Add</a>
<p />
<a href="delete.do"> Delete</a>
三、Servlet页面
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
// 获得提交的路径 :/find.do
String path = request.getServletPath();
// 截取出query
String methodName = path.substring(1, path.indexOf("."));
// out.println(methodName);
try {
// 利用反射
Method method = getClass().getDeclaredMethod(methodName,
HttpServletRequest.class, HttpServletResponse.class);
// 执行相应的方法
method.invoke(this, request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.flush();
out.close();
}
private void add(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("add action!");
}
private void delete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("del action!");
}
private void find(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("find action!");
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
效果图: