最近看到很多同学在问freemarker或者velocity 怎么包含动态页面,我这里有一个很简单的方法,如下:
freemarker 、velocity 都不能包含动态的页面,下面实例原理就是:根据传入的动态链接获取网页内容返回给页面(只支持get方式请求的链接)
自定义工具类:
import org.apache.commons.lang.StringUtils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
public class GetUrlContext {
public static String getString(String urlPath) {
try {
if (StringUtils.isEmpty(urlPath)) {
return "";
}
URL url = new URL(urlPath.trim());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int state = connection.getResponseCode();
if (state != 200) {
return "";
}
connection.connect();
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(reader);
String str = null;
StringBuilder sb = new StringBuilder();
while ((str = bufferedReader.readLine()) != null) {
sb.append(str);
}
reader.close();
connection.disconnect();
return sb.toString();
} catch (Exception e) {
return "";
}
}
}
我这里使用的是springmvc,直接把工具类丢到ModelAndView中,就可以直接在页面中引用了,
//测试的动态页面
@RequestMapping(value = "/")
public ModelAndView getFirstPage(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("welcom");
mv.addObject("name", "hello word!");
return mv;
}
@RequestMapping(value = "/test")
public ModelAndView getTest(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("test");
mv.addObject("getContext", new GetUrlContext());
return mv;
}
页面:
welcom.ftl
内容为:${name}
test.ftl
内容为:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
我是test <br/>
${getContext.getString("http://localhost:8080/demo")}
</body>
</html>
访问:http://localhost:8080/demo/test,结果如下:
我是test
hello word!