* 目的:
减少Servlet的数量,现在是一个功能一个Servlet,将其优化为一个模块一个Servlet,
相当于在数据库中一张表对应一个Servlet,在Servlet中提供不同的方法,完成用户的请求。
* 思路:
我们可以参考HttpServlet的doGet,doPost等方法的分发
创建一个BaseServlet继承HttpServlet,实现service方法
package cn.itcast.travel.web.servlet;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* HttpServlet的子类,其他类的基类,用来进行方法的分发
*/
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取uri
String uri = req.getRequestURI();
//对uri进行字符串的截断
String methodName = uri.substring(uri.lastIndexOf("/") + 1);
//使用反射来进行方法的执行
//this代表调用方法的对象
try {
//获取方法
Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
//如果是私有方法,需要使用暴力反射
//Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
//method.setAccessible(true);
//执行方法
method.invoke(this,req,resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
//抽取方法,写回json
public void writeValue(HttpServletResponse response,Object object) throws IOException {
//创建jackson对象
ObjectMapper mapper = new ObjectMapper();
//设置写回字符串的格式
response.setContentType("application/json;charset=utf-8");
//写回数据
mapper.writeValue(response.getWriter(),object);
}
//抽取方法,获取json字符串
public String getJson(Object obj) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(obj);
}
}
* 以user的servlet为例
package cn.itcast.travel.web.servlet;
import ...;
@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
private UserService service = new UserServiceImpl();
/**
* 用户注册
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//逻辑处理
}
* 此时请求localhost:port/user/register就可以访问到register方法
* 注意: 方法的修饰符必须是public,否则需要使用暴力反射
|
|