通过映射方式,继承BaseServlet来继承HttpServlet并完成方法分发
package cn.itcast.travel.web.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class BaseServlet extends HttpServlet {
private ObjectMapper mapper = new ObjectMapper();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//完成方法分发
//1.获取请求路径
String uri = req.getRequestURI();
System.out.println("请求uri:"+uri);// /travel/user/add
//2.获取方法名称
String methodName = uri.substring(uri.lastIndexOf("/") + 1);
System.out.println("方法名称:"+methodName);
//3.获取方法对象Method
//谁调用我?我代表谁
System.out.println(this);//UserServlet的对象cn.itcast.travel.web.servlet.UserServlet@4903d97e
try {
//忽略修饰符获取
//getDeclaredMethod
Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
//4.执行方法
//暴力反射
//method.setAccessible(true);
method.invoke(this,req,resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* 直接将传入的对象序列化为json,并且写回客户端
* @param obj
* @param response
* @throws IOException
*/
public void writeValue(Object obj,HttpServletResponse response) throws IOException {
response.setContentType("application/json;charset=UTF-8");
mapper.writeValue(response.getOutputStream(),obj);
}
public String writeValue(Object obj) throws IOException {
return mapper.writeValueAsString(obj);
}
//声明UserServlet业务方法
//对象序列化为json 并写回客户端
public void jsonWrite(HttpServletRequest request,HttpServletResponse response ,Object info) throws IOException {
//将info对象序列化为json
String json = mapper.writeValueAsString(info);
//将json数据写回客户端
// 设置content-type
response.setContentType("application/json;charset=utf-8");
// response.getWriter().write(json);
response.getOutputStream().write(json.getBytes());
}
//三元运算
public int triadic(String num,int noNum){
return num != null && num.length() >0 ? Integer.parseInt(num) :noNum;
};
}