关于JSP静态化与伪静态

首先是静态化:

private static final String CONTENT_TYPE = "text/html; charset=utf-8";
public static String isStatus(String picName,String jspName,HttpSession session,HttpServletRequest request, HttpServletResponse response){
String uuid=java.util.UUID.randomUUID().toString();
session=request.getSession();
DAOFactory dao=DAOFactory.getInstance();
String name = "";
String htmlName="";
try {
response.setContentType(StatUtil.CONTENT_TYPE);
String url = "";

ServletContext sc =session.getServletContext();

// 你要访问的jsp文件,如index.jsp
// 则你访问这个servlet时加参数.如http://localhost/toHtml?file_name=index
url = "/"+jspName;
// 这是你要生成HTML的jsp文件,如


name = request.getRealPath("/")+"pic-name-"+uuid+".html";
htmlName="pic-name-"+uuid+".html";

// 这是生成的html文件名,如index.htm.
RequestDispatcher rd = sc.getRequestDispatcher(url);
final ByteArrayOutputStream os = 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();

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return htmlName;
}

以上是个方法,可以摘摘剪剪的放在自己的程序里。

但是要注意,request传值,一定要放在这个上面去做,否则得话,页面里将没有内容。反正我试的结果就是这样。

下面是伪静态。这块我也是从网上摘找的工具类,试了一下,很好使,很强大。

第一步,创建两个工具类。

代码如下,直接粘过去就可以用了。



public class Base64Coder {

private static char[] map1 = new char[64];
static {
int i = 0;
for (char c = 'a'; c <= 'z'; c++)
map1[i++] = c;
for (char c = '0'; c <= '9'; c++)
map1[i++] = c;
for (char c = 'A'; c <= 'Z'; c++)
map1[i++] = c;
map1[i++] = '+';
map1[i++] = '/';
}

private static byte[] map2 = new byte[128];
static {
for (int i = 0; i < map2.length; i++)
map2[i] = -1;
for (int i = 0; i < 64; i++)
map2[map1[i]] = (byte) i;
}

public static String encodeString(String s) {
return new String(encode(s.getBytes()));
}

public static char[] encode(byte[] in) {
return encode(in, in.length);
}

public static char[] encode(byte[] in, int iLen) {
int oDataLen = (iLen * 4 + 2) / 3; // output length without padding
int oLen = ((iLen + 2) / 3) * 4; // output length including padding
char[] out = new char[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++] & 0xff;
int i1 = ip < iLen ? in[ip++] & 0xff : 0;
int i2 = ip < iLen ? in[ip++] & 0xff : 0;
int o0 = i0 >>> 2;
int o1 = ((i0 & 3) << 4) | (i1 >>> 4);
int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
int o3 = i2 & 0x3F;
out[op++] = map1[o0];
out[op++] = map1[o1];
out[op] = op < oDataLen ? map1[o2] : '_';
op++;
out[op] = op < oDataLen ? map1[o3] : '_';
op++;
}
return out;
}

public static String decodeString(String s) {
return new String(decode(s));
}

public static byte[] decode(String s) {
return decode(s.toCharArray());
}

public static byte[] decode(char[] in) {
int iLen = in.length;
if (iLen % 4 != 0)
throw new IllegalArgumentException(
"Length of Base64 encoded input string is not a multiple of 4.");
while (iLen > 0 && in[iLen - 1] == '_')
iLen--;
int oLen = (iLen * 3) / 4;
byte[] out = new byte[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++];
int i1 = in[ip++];
int i2 = ip < iLen ? in[ip++] : 'A';
int i3 = ip < iLen ? in[ip++] : 'A';
if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
throw new IllegalArgumentException(
"Illegal character in Base64 encoded data.");
int b0 = map2[i0];
int b1 = map2[i1];
int b2 = map2[i2];
int b3 = map2[i3];
if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
throw new IllegalArgumentException(
"Illegal character in Base64 encoded data.");
int o0 = (b0 << 2) | (b1 >>> 4);
int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2);
int o2 = ((b2 & 3) << 6) | b3;
out[op++] = (byte) o0;
if (op < oLen)
out[op++] = (byte) o1;
if (op < oLen)
out[op++] = (byte) o2;
}
return out;
}

private Base64Coder() {
}

}

-----------------------------------------------------------------------------------------------

import java.util.*;
public class HtmlUtil {
protected static int JSP=20091;
protected static int ACTION=20092;
protected static int HTML=20093;
protected static int SEALED=404;
protected static String propertyName;//项目名称以及 前面得 那段文件夹路径
protected static String actionName;//action的名称
protected static String operate;//action执行的方 或则 jsp页面的名称
protected static int type;//类型
protected static HashMap<String, String> items=new HashMap<String, String>();
/**
* 把真实得url转换为html路径 (例:/Shopping/user.do?operate=doLogin&userName=xiaowu&password=19890104)
*/
public static synchronized String getHtmlUrl(String url){
//判断类型
type=getType(url);
propertyName=getPropertyName(url);
//如果是一个ACTION
if(type==ACTION){
actionName=getActionName(url,true);
operate=getFunctionName(url,true);
items=getItems(url,true);
}
if(type==JSP){
actionName=getJspName(url,true);
items=getItems(url,true);
}

//创建URL
return createHtmlUrl();
}
/**
* 创建Html路径
* @return
*/
protected static String createHtmlUrl(){
StringBuffer newUrl=new StringBuffer("");
newUrl.append(actionName);
newUrl.append("_");
if(operate!=null&&!operate.equals("")){
newUrl.append(operate);
}
newUrl.append("_");
newUrl.append(type);
newUrl.append("_");
Set<String> keys=items.keySet();
for (Object key : keys) {
newUrl.append(key+"_"+items.get(key)+"_");
}
//对字符串进行编码
String coding=Base64Coder.encodeString(newUrl.toString());
if(propertyName!=null&&!propertyName.equals("")){
return propertyName+coding+".html";
}
return coding+".html";
}
/**
* 把html路径转换为真实的路径
*/
public static synchronized String getRealityUrl(String url){
//判断类型
type=getType(url);
if(type==JSP||type==ACTION){
//路径为加密就直接返回
return url;
}
propertyName=getPropertyName(url);
String newUrl="";
if(type==HTML){
try{
newUrl=url.substring(url.lastIndexOf("/")+1,url.length()-5);
//对字符串进行解码
newUrl=Base64Coder.decodeString(newUrl);
actionName=getActionName(newUrl, false);
operate=getFunctionName(newUrl,false);
items=getItems(newUrl,false);
type=getUrlType(newUrl);
}catch(Exception ee){
//如果是html页面强制改为jsp
if(url.substring(url.length()-5).equalsIgnoreCase(".html")){
//newUrl被改写过 所有要重新取得
newUrl=url.substring(url.lastIndexOf("/")+1,url.length()-5);
return newUrl+".jsp";
}
//如果URL无法通过解码那么就直接返回
return url;
}
}
return createRealityUrl();
}
// /**
// * 动态创建
// */
// public static synchronized String getHtmlUrl(String url,boolean b){
// if(b==true){
// if(url.indexOf("?")==-1){
// url+="?";
// url+="id"+System.currentTimeMillis()+"="+new Random().nextFloat();
// }else{
// url+="&id"+System.currentTimeMillis()+"="+new Random().nextFloat();
// }
// }
// return getHtmlUrl(url);
// }
/**
* 还原真实路径
* @return
*/
protected static String createRealityUrl(){
StringBuffer newUrl=new StringBuffer("");
if(propertyName!=null&&!propertyName.equals("")){
newUrl.append(propertyName);
}
if(actionName!=null&&!actionName.equals("")){
if(type==ACTION){
if(!operate.equals("")){
newUrl.append(actionName+".do?operate="+operate);
}else{
newUrl.append(actionName+".do");
}
}else if(type==JSP){
newUrl.append(actionName+".jsp");
}else if(type==HTML){
newUrl.append(actionName+".html");
}else{
newUrl.append(actionName);
}
}
Set<String> keys=items.keySet();
boolean isInterrogation=newUrl.toString().indexOf("?")!=-1?true:false;
for (Object key : keys) {
if(isInterrogation==false){
newUrl.append("?");
isInterrogation=true;
}else{
newUrl.append("&");
}
newUrl.append(key+"="+items.get(key));
}
return newUrl.toString();
}
// public static void main(String[] args) {
// String strs[]={"/Shopping/user.do?operate=doLogin&userName=xiaowu&password=19890104",
// "/Shopping/user.jsp?userName=xiaowu&password=19890104",
// "user.do?operate=doLogin&userName=xiaowu&password=19890104",
// "user.jsp?userName=xiaowu&password=19890104",
// "/user.do?operate=doLogin&userName=xiaowu&password=19890104",
// "/user.jsp?userName=xiaowu&password=19890104",
// "user.do?operate=doLogin",
// "/user.jsp",
// "/Shopping/user.do",
// "/Shopping/user.jsp",
// "user.do",
// "/user.do",
// "user.jsp",
// "/user.jsp",
// "/Shopping/MyJsp.jsp"};
// for (int i = 0; i < strs.length; i++) {
// System.err.println("原路径"+strs[i]);
// String str=HtmlUtil.getHtmlUrl(strs[i]);
// System.err.println("加密后"+str);
// str=HtmlUtil.getRealityUrl(str);
// System.err.println("还原后"+str);
// System.err.println("-----------------------------------------");
// }
// }
/**
* 返回类型
*/
protected static int getUrlType(String url){
if(url.indexOf("__")!=-1){
return Integer.parseInt(getStr(url,1,"_"));
}
return Integer.parseInt(getStr(url,2,"_"));
}
/**
* 返回项目名称
*/
protected static String getPropertyName(String url){
if(url.indexOf("/")==-1){
return "";
}
return url.substring(0,url.lastIndexOf("/")+1);
}
/**
* 返回ACTION名称
*/
protected static String getActionName(String url,boolean b){
if(b==false){
return getStr(url,0,"_");
}
if(url.indexOf("/")==-1){
return url.substring(0,url.indexOf("."));
}
return url.substring(url.lastIndexOf("/")+1,url.indexOf("."));
}
/**
* 返回JSP名称
*/
protected static String getJspName(String url,boolean b){
if(url.indexOf("/")==-1){
return url.substring(0,url.indexOf("."));
}
return url.substring(url.lastIndexOf("/")+1,url.indexOf("."));
}
/**
* 返回方法名称
*/
protected static String getFunctionName(String url,boolean b){
if(b==false){
if(url.indexOf("__")!=-1){
return "";
}
return getStr(url,1,"_");
}
if(url.indexOf("?")==-1)
return "";
url=url.substring(url.lastIndexOf("operate=")+8,url.length());
if(url.indexOf("&")==-1){
return url;
}
return url.substring(0,url.indexOf("&"));
}

/**
*
*/
protected static String getStr(String str,int count,String condition){
java.util.StringTokenizer tok=new StringTokenizer(str,condition);
int index=0;
while(tok.hasMoreElements()){
String newStr=tok.nextElement().toString();
if(index==count){
return newStr;
}
index++;
}
return "";
}

/**
* 返回items
*/
protected static HashMap<String, String> getItems(String url,boolean b){
HashMap<String, String> items=new HashMap<String, String>();
if(b==false){
java.util.StringTokenizer tok=new StringTokenizer(url,"_");
int index=0;
if(url.indexOf("__")!=-1){
index++;
}
while(tok.hasMoreElements()){
String newStr=tok.nextToken();
if(index>=3){
String key=newStr;
String value=null;
try {
value=tok.nextToken();
} catch (Exception e) {
value="";
}
items.put(key, value);
}
index++;
}
return items;
}
url=url.substring(url.lastIndexOf("?")+1,url.length());
java.util.StringTokenizer tok=new StringTokenizer(url,"&");
while(tok.hasMoreElements()){
String str=tok.nextToken();
if(str.indexOf("operate=")==-1&&str.indexOf("=")!=-1){
StringTokenizer newTok=new StringTokenizer(str,"=");
if(newTok.hasMoreElements()){
String key=newTok.nextToken();
newTok.hasMoreElements();
String value=null;
try {
value=newTok.nextToken();
if(value.equals("")){
value=null;
}
} catch (Exception e) {
value=null;
}
if(key.equals("")){
key=null;
}
items.put(key, value);
}
}
}
return items;
}
/**
* 判断类型
*/
protected static int getType(String url){
if(url.toUpperCase().indexOf(".DO")!=-1){
return ACTION;
}else if(url.toUpperCase().indexOf(".JSP")!=-1){
return JSP;
}else if(url.toUpperCase().indexOf(".HTML")!=-1){
return HTML;
}else{
return SEALED;
}
}
}

------------------------------------------

第二步,创建一个servlet。嗯,我的程序时用status做的,只要在web.xml里面添加一个servlet标签就可以了。如下:

<servlet>
<servlet-name>HtmlDecode</servlet-name>
<servlet-class>
com.clothes.util.statUtil.HtmlDecode ///这是你的servlet的位置
</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HtmlDecode</servlet-name>
<url-pattern>*.html</url-pattern>

</servlet-mapping>

///这是让你的所有以*.html跳转都跑到这个servlet里面,当然,也可以改成别的。都可以的。只要在htmlUtil类里去修改一下就可以了。用起来很舒服的。

第三步,就是使用咯。很简单,如下:

<A href="<%=HtmlUtil.getHtmlUrl("findProject.do?goodsid=123“)%>" >啦啦啦</a>

直接使用HtmlUtil里面的getHtmlUrl方法,他会在servlet编译的时候,将你要跳转的地址栏加密,同时在提交的时候,先跑到我们上面配置的哪个servlet里面,进行解密,然后跳转到你的.do或者其他的里面。挺好用的,不过一定要注意一点,就是那个goodsid这最好别加“_”,前面也最好别加。否则得话,就不灵了。嗯,这也是亲身经历。当然,这个传中文。。。我先试下!

嗯,不错,刚试了<a>提交和表单提交。结果是都可以的。如果用<a>提交出现乱码的话,就用我之前发的那个转乱码的工具类转一下就好了。可以支持中文
可以了。以上就这些,希望可以对大家有些帮助。

哎呀。。发现servlet忘了写进去了。现在加上,第二步的servlet:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.*;

public class HtmlDecode extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("GBK");
request.setCharacterEncoding("GBK");
//取出URL
String url=request.getRequestURI();
//对URL进行解码
String newUrl=HtmlUtil.getRealityUrl(url);
System.out.println(newUrl);
newUrl=newUrl.replaceAll(request.getContextPath()+"/", "");
//跳转到解码后的页面
request.getRequestDispatcher(newUrl).forward(request, response);
}
}

OK。就是这些。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值