网站开发后期要解决的问题青岛seo关键词排名
Controller分发器工具类
- 一. 设计逻辑
- 二. 简单设计:
- 三. BaseServlet 的 service()的设计
一. 设计逻辑
我们设计一个分发器,对于不同的操作,进入不同的方法,但是他们的请求的是同一个servlet,只是参数不同
1. 删除操作:news?action=del
2. 查询: news?action=list
3. 增加: news?action=add
4. 修改: news?action=toUpdate
那么:对于参数 action对应的value的不同我们可以调用对应的方法
二. 简单设计:
进入这个servlet的请求,经过service,分发到对应的方法,方法名与请求的value要相同
需要注意,请求必须是post,要不然数据会丢失
@WebServlet("/news")
public class NewsServlet extends BaseServlet {private NewsService service = new NewsService();public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("=========添加=======");}public void del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("=========删除=======");}/*** 修改*/public void mod(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("=========提交修改=======");}/*** 查询记录并转发到修改页面*/public void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("=========去修改=======");} /*** 查看详情*/public void detail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("=========明细=======");}/*** 新闻列表 带分页* news?action=list*/public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("=========明细=======");}
}
三. BaseServlet 的 service()的设计
public class BaseServlet extends HttpServlet{@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String methodName = request.getParameter("action");//反射 方法:方法名,参数列表 (确定唯一的方法)try {Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);//执行对应方法 调用method.invoke(this, request,response);
// 对象方法调用时
// this.add(request,response);} catch (Exception e) {e.printStackTrace();}}
}