案例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>