案例1:Servlet發送非網頁文檔
前言
Servlet編程可以將HTML文件發送到客戶端瀏覽器。當然還有很多站點還允許訪問非HTML格式的文檔(例如:Microsoft Word、Microsoft Excel、Adobe PDF等)只要這些非HTML格式的文檔能夠用MIME類型表示,就可以將該文件寫在Servlet的輸出流中,再通過Servlet在瀏覽器中打開這個文件。
程序
通過以下的程序示例,我們用MyEclipse創建一個新的Servlet類WordExample。
package demo;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servler.http.HttpServletRequest;
import javax.servler.http.HttpServletResponse;
/**
* Servlet implementation class WordExample
*/
public class WordExample extends HttpServlet {
private static final long serialVersionUID=1L;
/**
*
*@ see HttpServlet#HttpServlet()
*/
public WordExample() {
super();
//TODO Auto - generated constructor stub
}
/**
*@see HttpServlet#doGet(HttpServletRquest request,HttpServletRespinse
* response)
*/
protected void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
try {
File f =new File("C:\\test\Sleep.docx");
String filename=f.getName();
int length=0;
ServletOutputStream op = response.getOutputStream();
response.setContentLength((int)f.length());
response.setContentType("application/msword");
//response.setContentType("application/vnd.ms - excel");
//response.setContentType("Content - type","application/pdf");
response.setHeader("Content - Disposition","inline;filename=\""+"filename+"\"");
response.setHeader("Pragma","No - cache");
response.setHeader("Cache - Control","No-cache");
response.setHeader("Expires",0);
byte[ ] bytes = new byte[1024];
DataInputStream in = new DataInputStream(new FileInputStream(f));
while((in ! = null)&&((length = in.read(bytes))! = -1)){
op.write(bytes,0,length);
}
op.close();
response.flushBuffer();
}
catch(Exception e){
e.printStackTrace();
}
}
/**
*@ see HttpServlet#doPost(HttpServletRequest request,HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
//TODO Auto - generated method stub
doGet(request,response);
}
}
在web.xml文件中創建以下條目
<servlet>
<description>
</description>
<display - name>WordExample</display - name>
<servlet - name>WordExample</servlet - name>
</servlet>
<servlet - mapping>
<servlet -name>WordExample</servlet - name>
<url -pattern>WordExample</url -pattern>
</servlet - mapping>
查看效果
部署並訪問http://localhost:8080/ch04/CookieExample?first_name=La&Last_name=Tim 頁面,即可顯示文件下載的彈窗。
案例2:應用Servlet生成4位隨機驗證碼
CheckCode.java文件內容如下
public Color getRandColor(int s,int e) {
Random random =new Random();
if (s>255)s=255;
if(e>255)e=255;
int r =s+random.nextInt(e-s);
int g=s+random.nextInt(e-s);
int b=s+random.nextInt(e-s);
return new Color(r,g,b);
}
public void service(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","No-cache");
response.setDateHeader("Expires",0);
response.setContentType("imge/jpge");
int width=166;
int height=45;
BufferedImage image =new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
Random random=new Random();
Font mFont =new Font("宋體",Font.ITALIC,26);
g.setColor(getRandColor(180,220));
g.fillRect(0,0,width,height);
g.setFont(mFont);
String sRand="";
for(int i=0;i<4;i++){
char ctmp =(char)(random.nextInt(26)+65);
sRand+=ctmp;
Color color =new
Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110));
g.setColor(color);
g.drawString(String.valueOf(ctmp),width/6*i,height/2+10);
}
HttpSession session =request.getSession(true);
session.setAttribute("randCheckCode",sRand);
g.dispose();
ImageIO.write(image,"jpeg",response.getOutputStream());
}
}
Check Code.jsp文件內容如下
<%@page contentType ="text/html;charset=gbk"%>
<html>
<head><title>驗證碼</title><head>
<script language ="javascript">
function myReload(){
document.getElementById("myCheckCode").src
+="?nocache="+new Date().getTime();
}
</script>
<body>
<form name="f1" method="post" action="docheckcode.jsp">
驗證碼:<input type ="text" name="CheckCode" id="CheckCode" size="8"/>
<img src="CheckCode" name="myCheckCode" id="myCheckCode" width="166"
height ="45" border="1"/>
<a style ="cursor:hand;"onClick="myReload()">看不清?換一個</a><br>
<input type="submit" name="s1" value="提交"/>
</form>
</body>
</html>
doCheckCode.jsp文件內容如下
<%@ page contentType="text/html;charset=gbk"%>
<html>
<head><title>系統提示</title></head>
<body>
<%
if(request.getParameter("CheckCode")
equals(session.getAttribute("randCheckCode")))
{%>
<script language="javascript">
alert("驗證碼正確!");
window.location.href="checkcode.jsp";
</script>
<%}else{%>
<script language="javascript">
alert("您輸入的驗證碼不正確!");
windo.location.href="checkcode.jsp";
</script>
<%}%>
</body>
</html>