关于高负载高并发的服务器端应用,java解决方案(二)

一,页面静态化方案

当一个Servlet资源请求到达WEB服务器之后我们会填充指定的JSP页面来响应请求:

HTTP请求---Web服务器---Servlet--业务逻辑处理--访问数据--填充JSP--响应请求

HTML静态化之后:

HTTP请求---Web服务器---Servlet--HTML--响应请求

 

嘿嘿,是不是很爽?省去了业务逻辑处理和数据抓取直接响应。

 

 

Servlet:

  1. public void doGet(HttpServletRequest request, HttpServletResponse response)  
  2.         throws ServletException, IOException {  
  3.     if(request.getParameter("chapterId") != null){  
  4.         String chapterFileName = "bookChapterRead_"+request.getParameter("chapterId")+".html";  
  5.         String chapterFilePath = getServletContext().getRealPath("/") + chapterFileName;  
  6.         File chapterFile = new File(chapterFilePath);  
  7.         if(chapterFile.exists()){response.sendRedirect(chapterFileName);return;}//如果有这个文件就告诉浏览器转向  
  8.         INovelChapterBiz novelChapterBiz = new NovelChapterBizImpl();  
  9.         NovelChapter novelChapter = novelChapterBiz.searchNovelChapterById(Integer.parseInt(request.getParameter("chapterId")));//章节信息  
  10.         int lastPageId = novelChapterBiz.searchLastCHapterId(novelChapter.getNovelId().getId(), novelChapter.getId());  
  11.         int nextPageId = novelChapterBiz.searchNextChapterId(novelChapter.getNovelId().getId(), novelChapter.getId());  
  12.         request.setAttribute("novelChapter", novelChapter);  
  13.         request.setAttribute("lastPageId", lastPageId);  
  14.         request.setAttribute("nextPageId", nextPageId);  
  15.         new CreateStaticHTMLPage().createStaticHTMLPage(request, response, getServletContext(),   
  16.                 chapterFileName, chapterFilePath, "/bookRead.jsp");  
  17.     }  
  18. }  
 

生成HTML静态页面的类:

  1. package com.jb.y2t034.thefifth.web.servlet;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.OutputStreamWriter;  
  6. import java.io.PrintWriter;  
  7. import javax.servlet.RequestDispatcher;  
  8. import javax.servlet.ServletContext;  
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.ServletOutputStream;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13. import javax.servlet.http.HttpServletResponseWrapper;  
  14. /** 
  15.  * 创建HTML静态页面 
  16.  * 功能:创建HTML静态页面 
  17.  * 时间:2009年1011日 
  18.  * 地点:home 
  19.  * @author mavk 
  20.  * 
  21.  */  
  22. public class CreateStaticHTMLPage {  
  23.     /** 
  24.      * 生成静态HTML页面的方法 
  25.      * @param request 请求对象 
  26.      * @param response 响应对象 
  27.      * @param servletContext Servlet上下文 
  28.      * @param fileName 文件名称 
  29.      * @param fileFullPath 文件完整路径 
  30.      * @param jspPath 需要生成静态文件的JSP路径(相对即可) 
  31.      * @throws IOException 
  32.      * @throws ServletException 
  33.      */  
  34.     public void createStaticHTMLPage(HttpServletRequest request, HttpServletResponse response,ServletContext servletContext,String fileName,String fileFullPath,String jspPath) throws ServletException, IOException{  
  35.         response.setContentType("text/html;charset=gb2312");//设置HTML结果流编码(即HTML文件编码)  
  36.         RequestDispatcher rd = servletContext.getRequestDispatcher(jspPath);//得到JSP资源  
  37.         final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();//用于从ServletOutputStream中接收资源  
  38.         final ServletOutputStream servletOuputStream = new ServletOutputStream(){//用于从HttpServletResponse中接收资源  
  39.             public void write(byte[] b, int off,int len){  
  40.                 byteArrayOutputStream.write(b, off, len);  
  41.             }  
  42.             public void write(int b){  
  43.                 byteArrayOutputStream.write(b);  
  44.             }  
  45.         };  
  46.         final PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(byteArrayOutputStream));//把转换字节流转换成字符流  
  47.         HttpServletResponse httpServletResponse = new HttpServletResponseWrapper(response){//用于从response获取结果流资源(重写了两个方法)  
  48.             public ServletOutputStream getOutputStream(){  
  49.                 return servletOuputStream;  
  50.             }  
  51.             public PrintWriter getWriter(){  
  52.                 return printWriter;  
  53.             }  
  54.         };  
  55.         rd.include(request, httpServletResponse);//发送结果流  
  56.         printWriter.flush();//刷新缓冲区,把缓冲区的数据输出  
  57.         FileOutputStream fileOutputStream = new FileOutputStream(fileFullPath);  
  58.         byteArrayOutputStream.writeTo(fileOutputStream);//把byteArrayOuputStream中的资源全部写入到fileOuputStream中  
  59.         fileOutputStream.close();//关闭输出流,并释放相关资源  
  60.         response.sendRedirect(fileName);//发送指定文件流到客户端  
  61.     }  
  62. }  
 Java代码  收藏代码

  1. view plaincopy to clipboardprint?  
  2. import java.io.BufferedReader;     
  3. import java.io.File;     
  4. import java.io.IOException;     
  5. import java.io.InputStreamReader;     
  6. import java.net.MalformedURLException;     
  7. import java.net.URL;     
  8. import java.net.URLConnection;     
  9. import java.util.regex.Matcher;     
  10. import java.util.regex.Pattern;     
  11.     
  12. import org.apache.commons.io.FileUtils;     
  13. import org.apache.commons.lang.StringUtils;     
  14.     
  15. /**   
  16.  * @author Xing,XiuDong   
  17.  */    
  18. public class HTMLGenerator {     
  19.     
  20.     public static final String generate(final String url) {     
  21.         if (StringUtils.isBlank(url)) {     
  22.             return null;     
  23.         }     
  24.     
  25.         Pattern pattern = Pattern.compile("(http://|https://){1}[\\w\\.\\-/:]+");     
  26.         Matcher matcher = pattern.matcher(url);     
  27.         if (!matcher.find()) {     
  28.             return null;     
  29.         }     
  30.     
  31.         StringBuffer sb = new StringBuffer();     
  32.     
  33.         try {     
  34.             URL _url = new URL(url);     
  35.             URLConnection urlConnection = _url.openConnection();     
  36.             BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));     
  37.     
  38.             String inputLine;     
  39.             while ((inputLine = in.readLine()) != null) {     
  40.                 sb.append(inputLine);     
  41.             }     
  42.         } catch (MalformedURLException e) {     
  43.             e.printStackTrace();     
  44.         } catch (IOException e) {     
  45.             e.printStackTrace();     
  46.         }     
  47.     
  48.         return sb.toString();     
  49.     }     
  50.     
  51.     /**   
  52.      * Test Code   
  53.      * Target : http://www.google.cn/   
  54.      */    
  55.     public static void main(String[] args) throws IOException {     
  56.         String src = HTMLGenerator.generate("http://www.google.cn/");     
  57.     
  58.         File file = new File("C:" + File.separator + "index.html");     
  59.         FileUtils.writeStringToFile(file, src, "UTF-8");     
  60.     }     
  61.     
  62. }    


  1. view plaincopy to clipboardprint?  
  2. /**   
  3.  * generite html source code   
  4.  *    
  5.  * @author Xing,XiuDong   
  6.  * @date 2009.06.22   
  7.  * @param request   
  8.  * @param url   
  9.  * @param toWebRoot   
  10.  * @param encoding   
  11.  * @throws IOException   
  12.  */    
  13. public void genHtml(HttpServletRequest request, String url, boolean toWebRoot, String encoding) throws IOException {     
  14.     
  15.     if (null == url) {     
  16.         url = request.getRequestURL().toString();     
  17.     }     
  18.     
  19.     String contextPath = request.getContextPath();     
  20.     String seq = StringUtils.substring(String.valueOf(new Date().getTime()), -6);     
  21.     
  22.     String ctxPath = super.getServlet().getServletContext().getRealPath(File.separator);     
  23.     if (!ctxPath.endsWith(File.separator)) {     
  24.         ctxPath += File.separator;     
  25.     }     
  26.     
  27.     String filePath = StringUtils.substringAfter(url, contextPath);     
  28.     filePath = filePath.replaceAll("\\.(do|jsp|html|shtml)$"".html");     
  29.     
  30.     String savePath = "";     
  31.     String autoCreatedDateDir = "";     
  32.     if (!toWebRoot) {     
  33.         savePath = StringUtils.join(new String[] { "files""history""" }, File.separator);     
  34.     
  35.         String[] folderPatterns = new String[] { "yyyy""MM""dd""" };     
  36.         autoCreatedDateDir = DateFormatUtils.format(new Date(), StringUtils.join(folderPatterns, File.separator));     
  37.     
  38.         filePath = StringUtils.substringBefore(filePath, ".html") + "-" + seq + ".html";     
  39.     }     
  40.     
  41.     File file = new File(ctxPath + savePath + autoCreatedDateDir + filePath);     
  42.     FileUtils.writeStringToFile(file, HTMLGenerator.generate(url), encoding);     
  43. }    
  44.   

posted on 2011-10-09 09:46  苏桓(osbert)  阅读(675)  评论(0编辑  收藏  举报

导航