问题:
a标签href不以http开头,会默认增加当前目录路径为前缀,导致连接错误
如:
<a href="www.baidu.com" target="_blank">www.baidu.com</a>
点击时,跳转的是http://localhost:9090/message/siteMessage/www.baidu.com
解决:
给url地址增加http前缀
js:
String.prototype.formatUrl = function(){
if(this == null || this == "") return this;
var reg = /(http:\/\/|https:\/\/)((\w|=|\?|\.|\/|&|-)+)/g;
if (reg.test(this)) {
return this;
}
return 'http://' + this;
}
使用:
console.log('www.baidu.com'.formatUrl())
//http://www.baidu.com
java代码:
import org.apache.commons.lang.StringUtils;
/**
* http工具类
*/
public class HttpUtils {
/**
* url前缀增加http
* @param url url地址
* @return url地址
*/
public static String addHttp(String url) {
if (StringUtils.isBlank(url)) {
return url;
}
String newUrl = url;
if (url.indexOf("http") != 0) { //不以http开头
newUrl = "http://" + url;
}
return newUrl;
}
public static void main(String[] args) {
String addHttp = addHttp("www.baidu.com");
//http://www.baidu.com
System.out.println(addHttp);
}
}