介绍本篇内容前,先抛出我遇到的问题或者说是需求!(精读阅读本篇可能花费您15分钟,略读需5分钟左右)
一:需求说明
有一个Controller有两个方法
第一个方法通过指定的路径和参数去渲染jsp内容,并返回html数据
第二个方法获取第一个方法中的html进行封装
现在的做法是在第二个方法通过发送Http请求获取数据,然后返回进行封装!
问题:
需要优化的是 不通过Http请求,第二个方法可以拿到第一个方法中的Html数据
二:简化例子(待优化的例子)
注:使用的SpringMVC框架,使用贴出视图解析器 配置文件
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:order="2">
value="org.springframework.web.servlet.view.JstlView" />
1.简化请求图示说明
简单说明:一个Controller中有三个方法,访问/index 返回html输出到页面,
浏览器页面显示内容为:
hello
url = http://blog.csdn.net/u010648555
world
url = http://blog.csdn.net/u010648555
/index中通过Http去请求/hello ,渲染hello.jsp 返回 hello.jsp 对应的html代码,去请求/world ,渲染world.jsp 返回 world..jsp 对应的html代码!
2.简化代码说明
(1):Java代码
package com.dufy.web;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by dufy on 2017/3/21.
*/
@Controller
public class JspController {
/**
* 跳转到WEB_INF/jsp/welcome/index.jsp
* @param request
* @param response
* @return
*/
@RequestMapping("/index")
public String index(HttpServletRequest request ,HttpServletResponse response) {
List list = new ArrayList();
list.add("hello");
list.add("wrold");
String commonUrl = "http://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
StringBuilder pageHtml = new StringBuilder();//使用StringBuilder拼接字符串效率高
if (list != null && list.size() > 0) {
for (String str : list
) {
StringBuffer paramsBuffer = new StringBuffer();//线程安全
paramsBuffer .append(str + "=" + str);//hello=hello world=world
//如果参数中url 需要使用URLEncoder
paramsBuffer .append("url"+ "=" + URLEncoder.encode("http://blog.csdn.net/u010648555"));
//使用post请求 ,后台获取每个接口方法对应生成的html
String urlStr = commonUrl +"/" + str + "?jsppath=" + str;//reqest url 这里会调用 /hello /world
String urlSourceResult = getURLSourcePost(urlStr,paramsBuffer.toString());
pageHtml.append(urlSourceResult);
}
}
request.setAttribute("pageHtml",pageHtml);
return "welcome/index";
}
/**
* 跳转到WEB_INF/jsp/welcome/hello.jsp
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/hello",method = RequestMethod.POST)
public String hello(HttpServletRequest request,HttpServletResponse response){
String jsppath = request.getParameter("jsppath");
//处理一些业务逻辑
Map params = new HashMap<>();
for (Object p : request.getParameterMap().keySet()) {
try {
String s = request.getParameter(p.toString());
params.put(p.toString(), s);
} catch (Exception e) {
e.printStackTrace();
}
}
request.setAttribute("params",params);
return "welcome/" + jsppath;
}
/**
* 跳转到WEB_INF/jsp/welcome/world.jsp
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/wrold" ,method = RequestMethod.POST)
public String world(HttpServletRequest request,HttpServletResponse response){
String jsppath = request.getParameter("jsppath");
//处理一些业务逻辑
Map params = new HashMap<>();
for (Object p : request.getParameterMap().keySet()) {
try {
String s = request.getParameter(p.toString());
params.put(p.toString(), s);
} catch (Exception e) {
e.printStackTrace();
}
}
request.setAttribute("params",params);
return "welcome/" + jsppath;
}
/**
* 通过网站域名URL使用POST方式 获取该网站的源码
* @param url 请求的地址
* @param param 请求的参数
* @return 返回请求的结果
*/
private String getURLSourcePost(String url,String param) {
PrintWriter out = null;
BufferedReader in = null;
StringBuilder htmlResult = new StringBuilder();
try
{
URL realUrl = new URL(url);
//打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
//设置请求的方式
conn.setRequestMethod("POST");
conn.setConnectTimeout(5 * 1000);
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// charset=UTF-8以防止乱码!
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
//发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
//获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
//发送请求参数
out.print(param);
//flush输出流的缓冲
out.flush();
//定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine())!= null)
{
if(StringUtils.isNotBlank(line)){
htmlResult.append("\n" + line);
}
}
}
catch(Exception e)
{
throw new RuntimeException("发送POST请求出现异常!",e);
}
//使用finally块来关闭输出流、输入流
finally
{
try
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
return htmlResult.toString();
}
}
(2):对于的JSP页面
a:index.jsp
welcome index${pageHtml}