/** |
* @file_name 文件名及文件之后的参数.最好为a.jsf?fileId=aaaa |
* @path 文件所在的路径.相对于根目录而言的. |
* @realName文件要保存的名字 |
* @realPath文件要保存的真实路径。默认与文件所在的目录相同。 |
*/ |
public class ToHtmlPath extends HttpServlet { |
public void service(HttpServletRequest request, HttpServletResponse response) |
throws ServletException, IOException { |
String url = "" ; |
String name = "" ; |
ServletContext sc = getServletContext(); |
String file_name = request.getParameter( "file_name" ); // 你要访问的jsp文件,如news.jsf。 |
// file_name如:fileDetail.jsf?fileId=56.要是有参数, 只有一个参数。并且以参数名作为文件名。 |
String realName = request.getParameter( "realName" ); // 要保存的文件名。如aaa;注意可以没有这个参数。 |
String path = request.getParameter( "path" ); // 你要访问的jsp文件路径。如news。注意可以没有这个参数。 |
String realPath = request.getParameter( "realPath" ); // 你要保存的文件路径,如htmlNews.注意可以没有这个参数。 |
// 下面确定要保存的文件名字。 |
if (realName == null || realName == "" ) { |
int a = 0 ; |
a = file_name.indexOf( "=" ) + 1 ; |
realName = file_name.substring(a); |
if (realName.indexOf( "." ) > 0 ) { |
realName = file_name.substring( 0 , file_name.indexOf( "." )); |
} |
} |
// 下面构造要访问的页面。 |
if (path == null || path == "" ) { |
url = "/" + file_name; // 这是你要生成HTML的jsp文件,如 |
} else { |
url = "/" + path + "/" + file_name; // 这是你要生成HTML的jsp文件,如 |
} |
// 下面构造要保存的文件名,及路径。 |
// 1、如果有realPath,则保存在realPath下。 |
// 2、如果有path则保存在path下。 |
// 3、否则,保存在根目录下。 |
if (realPath == null || realPath == "" ) { |
if (path == null || path == "" ) { |
name = ConfConstants.CONTEXT_PATH + "\\" + realName + ".htm" ; // 这是生成的html文件名,如index.htm.说明: |
// ConfConstants.CONTEXT_PATH为你的上下文路径。 |
} else { |
name = ConfConstants.CONTEXT_PATH + "\\" + path + "\\" |
+ realName + ".htm" ; // 这是生成的html文件名,如index.htm. |
} |
} else { |
name = ConfConstants.CONTEXT_PATH + "\\" + realPath + "\\" |
+ realName + ".htm" ; // 这是生成的html文件名,如index.htm. |
} |
// 访问请求的页面,并生成指定的文件。 |
RequestDispatcher rd = sc.getRequestDispatcher(url); |
final ByteArrayOutputStream ōs = new ByteArrayOutputStream(); |
final ServletOutputStream stream = new ServletOutputStream() { |
public void write( byte [] data, int offset, int length) { |
os.write(data, offset, length); |
} |
public void write( int b) throws IOException { |
os.write(b); |
} |
}; |
final PrintWriter pw = new PrintWriter( new OutputStreamWriter(os)); |
HttpServletResponse rep = new HttpServletResponseWrapper(response) { |
public ServletOutputStream getOutputStream() { |
return stream; |
} |
public PrintWriter getWriter() { |
return pw; |
} |
}; |
rd.include(request, rep); |
pw.flush(); |
FileOutputStream fos = new FileOutputStream(name); // 把jsp输出的内容写到xxx.htm |
os.writeTo(fos); |
fos.close(); |
PrintWriter ōut = response.getWriter(); |
out.print( "<p align=center><font size=3 color=red>success!</font></p>" ); |
} |
} |