*** 经测有效 ***
package springbootTest;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import com.project.controller.DemoController;
public class Test1 {
public static void main(String[] args) {
UriComponents uriComponents = null;
String uri = "";
/**
* 1、URI动态拼接
*/
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
List<String> list = new ArrayList<String>();
list.add("张三");
list.add("李四");
params.put("name", list);
uriComponents = UriComponentsBuilder
.fromHttpUrl("http://localhost:8080/hello")
.queryParam("key", "xxxx")
.queryParams(params)
.build();
System.out.println(uriComponents.toUriString());
//输出:http://localhost:8080/helllo?key=xxxx&name=张三&name=李四
/**
* 2、URI参数替换
* expand(……):替换参数,URL中有多少大括号,就要放多少参数,必须一一对应
* encode():编码,默认使用UTF-8
*
* uriComponents 值不会改变,执行expand()/encode()方法,会返回新的UriComponents实例
* *uriComponents值可复用
*/
uriComponents = UriComponentsBuilder
.fromHttpUrl("http://localhost:8080/hello/{path1}/add/{path2}")
.build();
uri = uriComponents.expand("11","22").encode().toUriString();
System.out.println(uri);
//输出:http://localhost:8080/hello/11/add/22
uri = uriComponents.expand("33","44").encode().toUriString();
System.out.println(uri);
//输出:http://localhost:8080/hello/33/add/44
/**
* 3、使用下面的方式
*/
uriComponents = UriComponentsBuilder.newInstance()
.scheme("http").host("localhost").port("8080").path("/hello/{path1}/delete/{path2}")
.build();
uri = uriComponents.expand("aa","bb").encode().toUriString();
System.out.println(uri);
//输出:http://localhost:8080/hello/aa/delete/bb
/**
* 4、使用子类1:ServletUriComponentsBuilder构建
*/
HttpServletRequest request =null;
uriComponents = ServletUriComponentsBuilder
.fromRequest(request)
.replaceQueryParam("aId", "{id}")
.build();
uri = uriComponents.expand("123").encode().toUriString();
System.out.println(uri);
/**
* 4、使用子类2:MvcUriComponentsBuilder构建
*/
uriComponents = MvcUriComponentsBuilder
.fromMethodName(DemoController.class, "index", 22)
.buildAndExpand(42);
uri = uriComponents.toUriString();
System.out.println(uri);
}
}