您的位置:首页 > 其它

Servlet中通用的service方法

2017-12-08 16:01 225 查看
package com.itliuwei.store.utils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
* 以后创建Servlet的时候不需要继承HttpServlet了,而是继承这个类(BaseServlet)
* 这样每个Servlet都不用写service方法了
* 只需要写那些真正用于处理业务的方法即可,默认调用父类的service方法
* 而父类service方法中获取请求要执行的方法名然后通过反射调用并执行方法
*/

public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

try {
String runMethodName = req.getParameter("method");
Class clazz = this.getClass();

Method method = clazz.getMethod(runMethodName, HttpServletRequest.class,
HttpServletResponse.class);

if (method != null) {
String url = (String) method.invoke(this, req, resp);
if (url != null) {
req.getRequestDispatcher(url).forward(req, resp);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  servlet 通用 service