restful支持@PathVariable

This commit is contained in:
tanghc
2019-10-09 18:27:43 +08:00
parent caaff21876
commit 0cc8c0b991
6 changed files with 83 additions and 15 deletions

View File

@@ -19,13 +19,13 @@ import java.io.IOException;
@WebServlet(urlPatterns = "/rest/*")
public class RestServlet extends HttpServlet {
private static final String REST_PATH = "/rest";
private static final String EMPTY_VERSION = "";
@Value("${zuul.servlet-path:/zuul}")
private String path;
@Value("${zuul.rest-default-version:1.0}")
private String defaultVersion;
@Value("${sop.restful.path:/rest}")
private String restPath;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
@@ -35,16 +35,11 @@ public class RestServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = request.getRequestURL().toString();
int index = url.indexOf(REST_PATH);
int index = url.indexOf(restPath);
// 取/rest的后面部分
String path = url.substring(index + REST_PATH.length());
String method = path;
String version = request.getParameter(ParamNames.VERSION_NAME);
if (version == null) {
version = defaultVersion;
}
request.setAttribute(SopConstants.REDIRECT_METHOD_KEY, method);
request.setAttribute(SopConstants.REDIRECT_VERSION_KEY, version);
String path = url.substring(index + restPath.length());
request.setAttribute(SopConstants.REDIRECT_METHOD_KEY, path);
request.setAttribute(SopConstants.REDIRECT_VERSION_KEY, EMPTY_VERSION);
request.getRequestDispatcher(this.path).forward(request, response);
}

View File

@@ -0,0 +1,30 @@
package com.gitee.sop.gateway;
import junit.framework.TestCase;
import org.junit.Assert;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
/**
* @author tanghc
*/
public class UrlPatternTest extends TestCase {
private PathMatcher pathMatcher = new AntPathMatcher();
public void testA() {
Assert.assertTrue(match("/food/get/{id}", "/food/get/2"));
Assert.assertTrue(match("/food/get/{id}1.0", "/food/get/21.0"));
}
/**
* @param pattern food/get/{id}
* @param lookupPath /food/get/2
*
* @return
*/
public boolean match(String pattern, String lookupPath) {
return this.pathMatcher.match(pattern, lookupPath);
}
}