关于高负载高并发的服务器端应用,java解决方案(二)
一,页面静态化方案
当一个Servlet资源请求到达WEB服务器之后我们会填充指定的JSP页面来响应请求:
HTTP请求---Web服务器---Servlet--业务逻辑处理--访问数据--填充JSP--响应请求
HTML静态化之后:
HTTP请求---Web服务器---Servlet--HTML--响应请求
嘿嘿,是不是很爽?省去了业务逻辑处理和数据抓取直接响应。
Servlet:
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- if(request.getParameter("chapterId") != null){
- String chapterFileName = "bookChapterRead_"+request.getParameter("chapterId")+".html";
- String chapterFilePath = getServletContext().getRealPath("/") + chapterFileName;
- File chapterFile = new File(chapterFilePath);
- if(chapterFile.exists()){response.sendRedirect(chapterFileName);return;}//如果有这个文件就告诉浏览器转向
- INovelChapterBiz novelChapterBiz = new NovelChapterBizImpl();
- NovelChapter novelChapter = novelChapterBiz.searchNovelChapterById(Integer.parseInt(request.getParameter("chapterId")));//章节信息
- int lastPageId = novelChapterBiz.searchLastCHapterId(novelChapter.getNovelId().getId(), novelChapter.getId());
- int nextPageId = novelChapterBiz.searchNextChapterId(novelChapter.getNovelId().getId(), novelChapter.getId());
- request.setAttribute("novelChapter", novelChapter);
- request.setAttribute("lastPageId", lastPageId);
- request.setAttribute("nextPageId", nextPageId);
- new CreateStaticHTMLPage().createStaticHTMLPage(request, response, getServletContext(),
- chapterFileName, chapterFilePath, "/bookRead.jsp");
- }
- }
生成HTML静态页面的类:
- package com.jb.y2t034.thefifth.web.servlet;
- import java.io.ByteArrayOutputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import javax.servlet.RequestDispatcher;
- import javax.servlet.ServletContext;
- import javax.servlet.ServletException;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpServletResponseWrapper;
- /**
- * 创建HTML静态页面
- * 功能:创建HTML静态页面
- * 时间:2009年1011日
- * 地点:home
- * @author mavk
- *
- */
- public class CreateStaticHTMLPage {
- /**
- * 生成静态HTML页面的方法
- * @param request 请求对象
- * @param response 响应对象
- * @param servletContext Servlet上下文
- * @param fileName 文件名称
- * @param fileFullPath 文件完整路径
- * @param jspPath 需要生成静态文件的JSP路径(相对即可)
- * @throws IOException
- * @throws ServletException
- */
- public void createStaticHTMLPage(HttpServletRequest request, HttpServletResponse response,ServletContext servletContext,String fileName,String fileFullPath,String jspPath) throws ServletException, IOException{
- response.setContentType("text/html;charset=gb2312");//设置HTML结果流编码(即HTML文件编码)
- RequestDispatcher rd = servletContext.getRequestDispatcher(jspPath);//得到JSP资源
- final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();//用于从ServletOutputStream中接收资源
- final ServletOutputStream servletOuputStream = new ServletOutputStream(){//用于从HttpServletResponse中接收资源
- public void write(byte[] b, int off,int len){
- byteArrayOutputStream.write(b, off, len);
- }
- public void write(int b){
- byteArrayOutputStream.write(b);
- }
- };
- final PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(byteArrayOutputStream));//把转换字节流转换成字符流
- HttpServletResponse httpServletResponse = new HttpServletResponseWrapper(response){//用于从response获取结果流资源(重写了两个方法)
- public ServletOutputStream getOutputStream(){
- return servletOuputStream;
- }
- public PrintWriter getWriter(){
- return printWriter;
- }
- };
- rd.include(request, httpServletResponse);//发送结果流
- printWriter.flush();//刷新缓冲区,把缓冲区的数据输出
- FileOutputStream fileOutputStream = new FileOutputStream(fileFullPath);
- byteArrayOutputStream.writeTo(fileOutputStream);//把byteArrayOuputStream中的资源全部写入到fileOuputStream中
- fileOutputStream.close();//关闭输出流,并释放相关资源
- response.sendRedirect(fileName);//发送指定文件流到客户端
- }
- }
- view plaincopy to clipboardprint?
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLConnection;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import org.apache.commons.io.FileUtils;
- import org.apache.commons.lang.StringUtils;
- /**
- * @author Xing,XiuDong
- */
- public class HTMLGenerator {
- public static final String generate(final String url) {
- if (StringUtils.isBlank(url)) {
- return null;
- }
- Pattern pattern = Pattern.compile("(http://|https://){1}[\\w\\.\\-/:]+");
- Matcher matcher = pattern.matcher(url);
- if (!matcher.find()) {
- return null;
- }
- StringBuffer sb = new StringBuffer();
- try {
- URL _url = new URL(url);
- URLConnection urlConnection = _url.openConnection();
- BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
- String inputLine;
- while ((inputLine = in.readLine()) != null) {
- sb.append(inputLine);
- }
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return sb.toString();
- }
- /**
- * Test Code
- * Target : http://www.google.cn/
- */
- public static void main(String[] args) throws IOException {
- String src = HTMLGenerator.generate("http://www.google.cn/");
- File file = new File("C:" + File.separator + "index.html");
- FileUtils.writeStringToFile(file, src, "UTF-8");
- }
- }
- view plaincopy to clipboardprint?
- /**
- * generite html source code
- *
- * @author Xing,XiuDong
- * @date 2009.06.22
- * @param request
- * @param url
- * @param toWebRoot
- * @param encoding
- * @throws IOException
- */
- public void genHtml(HttpServletRequest request, String url, boolean toWebRoot, String encoding) throws IOException {
- if (null == url) {
- url = request.getRequestURL().toString();
- }
- String contextPath = request.getContextPath();
- String seq = StringUtils.substring(String.valueOf(new Date().getTime()), -6);
- String ctxPath = super.getServlet().getServletContext().getRealPath(File.separator);
- if (!ctxPath.endsWith(File.separator)) {
- ctxPath += File.separator;
- }
- String filePath = StringUtils.substringAfter(url, contextPath);
- filePath = filePath.replaceAll("\\.(do|jsp|html|shtml)$", ".html");
- String savePath = "";
- String autoCreatedDateDir = "";
- if (!toWebRoot) {
- savePath = StringUtils.join(new String[] { "files", "history", "" }, File.separator);
- String[] folderPatterns = new String[] { "yyyy", "MM", "dd", "" };
- autoCreatedDateDir = DateFormatUtils.format(new Date(), StringUtils.join(folderPatterns, File.separator));
- filePath = StringUtils.substringBefore(filePath, ".html") + "-" + seq + ".html";
- }
- File file = new File(ctxPath + savePath + autoCreatedDateDir + filePath);
- FileUtils.writeStringToFile(file, HTMLGenerator.generate(url), encoding);
- }
posted on 2011-10-09 09:46 苏桓(osbert) 阅读(675) 评论(0) 编辑 收藏 举报