新加入的项目组,没有引入web模块,也不敢瞎添加包。 test里模拟一个服务器,感觉比加依赖方便些,不过这些代码不要提交上去,万一打包的时候,没有skipTest, 就多了个bug
启动后, post直接访问 http://localhost:8080/xxx/query 类似这样的接口, 类映射名 + 方法名。 参数默认当泛型处理了, 因为入参封装了起来。不是泛型简单改下转json的地方 objectMapper.readValue 就行了。
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
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;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = StartApplication.class)
public class ServerTest {
private static final ObjectMapper objectMapper = new ObjectMapper();
// 首路径-类 映射,存在才能访问
private static final Map> FIRSTPATH_CLASS_MAPPING = new HashMap<>();
static {
FIRSTPATH_CLASS_MAPPING.put("test1", Test1.class);
FIRSTPATH_CLASS_MAPPING.put("test2", Test1.class);
FIRSTPATH_CLASS_MAPPING.put("test3", Test1.class);
}
//http://localhost:8080/promotionRuleQuery/queryFetchCoupons
@Test
public void server() throws Exception {
Server server = new Server(8080);
server.setHandler(initServletContextHandler());
server.start();
server.join();
}
private Handler initServletContextHandler() {
ServletContextHandler handler = new ServletContextHandler();
handler.addServlet(new ServletHolder(mediator()), "/*");
return handler;
}
private HttpServlet mediator() {
return new HttpServlet() {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doTransfer(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doTransfer(req, resp);
}
};
}
private void doTransfer(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
String pathInfo = req.getPathInfo();
if (pathInfo.equals("/favicon.ico")) {
resp.getWriter().write("");
return;
}
String[] split = pathInfo.split("/");
String firstPath = split[split.length - 2];
String secondPath = split[split.length - 1];
resp.setContentType("application/json;charset=utf-8");
req.setCharacterEncoding(StandardCharsets.UTF_8.toString());
Object o = getReq(firstPath, secondPath, req.getMethod()).doReq(req);
resp.getWriter().write(objectMapper.writeValueAsString(o));
} catch (Exception e) {
e.printStackTrace();
resp.getWriter().write(e.toString());
}
}
private static class MyT extends TypeReference {
protected final Type _type;
protected MyT(Type type) {
this._type = type;
}
public Type getType() {
return this._type;
}
}
private static final Map ReqMap = new HashMap<>();
private static MyRequest getReq(String firstPath, String secondPath, String httpMethod) {
return ReqMap.computeIfAbsent(firstPath + secondPath + httpMethod, s -> {
Class> aClass = FIRSTPATH_CLASS_MAPPING.get(firstPath);
if (aClass == null) throw new RuntimeException("无效路径1");
Object bean = SpringTool.getBean(aClass);
Method[] declaredMethods = aClass.getDeclaredMethods();
Method method = Arrays.stream(declaredMethods).filter(m -> m.getName().equals(secondPath)).findFirst().orElseThrow(() -> new RuntimeException("无效路径2"));
Type[] types = null;
String[] typeNames = null;
Parameter[] parameters = method.getParameters();
if (parameters != null && parameters.length != 0) {
if ("post".equalsIgnoreCase(httpMethod)) {
types = new Type[]{ parameters[0].getParameterizedType() };
typeNames = new String[]{parameters[0].getName() };
}else {
types = new Class>[parameters.length];
typeNames = new String[parameters.length];
for (int i = 0; i < parameters.length; i++) {
types[i] = parameters[i].getType();
typeNames[i] = parameters[i].getName();
}
}
}
MyRequest myRequest = new MyRequest();
myRequest.bean = bean;
myRequest.method = method;
myRequest.types = types;
myRequest.typeNames = typeNames;
return myRequest;
});
}
private static class MyRequest {
Object bean;
Method method;
// post存泛型,get存class
Type[] types;
String[] typeNames;
public Object doReq(HttpServletRequest req) throws Exception {
return types == null
? method.invoke(bean)
: "post".equalsIgnoreCase(req.getMethod())
? doPost(req)
: doGet(req);
}
private Object doPost(HttpServletRequest req) throws Exception {
Object o = objectMapper.readValue(IOUtils.toString(req.getInputStream()), new MyT<>(types[0]));
return method.invoke(bean, o);
}
private Object doGet(HttpServletRequest req) throws Exception {
Object[] paramValues = new Object[types.length];
for (int i = 0; i < types.length; i++) {
paramValues[i] = req.getParameter(typeNames[i]);
}
return method.invoke(bean, paramValues);
}
}
@Test
public void test() {
}
}



