以下是文件index.jsp的代码:
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%
response.setHeader("Cache-Control","no-store");
response.setDateHeader("Expires",0);
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%!
public String[] getQuestion(String s)
{
String[] strQ = new String[4];
String strTemp = null;
int i;
java.io.RandomAccessFile rf = null;
try
{
rf = new java.io.RandomAccessFile(s,"r");
} catch(Exception e)
{
System.out.println(e);
System.exit(0);
}
for(i=0;i<4;i++)
{
try
{
strTemp = rf.readLine();
} catch(Exception e){}
if(strTemp==null)strTemp = "";
strQ[i] = strTemp;
}
return strQ;
}
%>
<%
String s = null;
String[] question = new String[4];
s = request.getRealPath("question.txt");
question = getQuestion(s);
%>
<html>
<head>
<title></title>
</head>
<body>
你喜欢清风阁论坛吗?
<br>
<form name="frm" method="post" action="write.jsp">
<tr>
<td>
<%
String ss = null;
for (int i=0;i<4;i++)
{
ss = "<input type=\"radio\" name=\"choice\" value=" + i+">"+(char)('A'+i)+"、"+ question[i]+"<br>";
out.println(ss);
}
%>
</td>
</tr>
<tr>
<td align=center><input type=submit value="投 票"></td>
</tr>
<tr>
<td align=center>
<img src="<%=basePath%>VoteImage" width=150 height=100>
<br>
<img src="yang.jpg" width=150 height=100>
</td>
</tr>
</form>
</body>
</html>
index.jsp文件中设定了4个选项(ABCD),每个选项都通过Request对象的getRealPath()方法来从question.txt文件中获得了一个问题。当选中一个选项投票后,由VoteImage.java文件生成的图片就会显示该选项的投票比例。write.jsp文件设定了投票数值的计算方法,并将结果输出到count.txt文件中,下面是write.jsp文件的代码:
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%!
public int[] getNumber(String s)
{
int[] mCount = new int[4];
String strTemp = null;
int i;
java.io.RandomAccessFile rf = null;
try
{
rf = new java.io.RandomAccessFile(s,"r");
} catch(Exception e){}
for(i=0;i<4;i++)
{
try {
strTemp = rf.readLine();
} catch(Exception e) {}
if(strTemp==null)strTemp = "0";
mCount[i] = new Integer(strTemp).intValue();
}
return mCount;
}
public void setNumber(String s,int[] x)
{
try
{
java.io.PrintWriter pw = new java.io.PrintWriter(new java.io.FileOutputStream(s));
for (int i=0;i<4;i++)
{
pw.println(x[i]+"");
}
pw.close();
} catch(Exception e) {}
}
%>
<%
String tmp = null;
int choice = -1;
int[] count = new int[4];
tmp = request.getParameter("choice");
if (tmp==null)
{
} else
{
choice = new Integer(tmp).intValue();
}
String s = request.getRealPath("count.txt");
if(choice>=0)
{
count = getNumber(s);
count[choice]++;
setNumber(s,count);
}
response.sendRedirect("index.jsp");
%>
write.jsp文件是对投票的计算以及输出。当在index.jsp页面中进行投票后,write.jsp文件会对投票进行计算、总结、并修改count.txt文件中的投票结果,然后通过Response对象的sendRedirect()方法将页面重定向到index.jsp页面上,以便继续投票。
以下是VoteImage.java文件代码,该文件设定了图片比例的显示方式和比例计算方法,是图片能在index.jsp页面投票的同时,立即显示投票后图片的比例改动。
package servlet;
import java.io.*;
import com.sun.image.codec.jpeg.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
public class VoteImage extends HttpServlet
{
private String strFile = null;
private Color color[]={Color.red,Color.black,Color.orange,Color.green};
private int baseAng = 30;
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
System.out.println("VoteImage.doGet()");
doPost(request,response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
System.out.println("VoteImage.doPost()");
strFile = request.getRealPath("count.txt");
float[][] xy = new float[4][2];
xy = getNumAndPercent(strFile);
int[] ang = new int[4];
ang[0] = (int)(xy[0][1]*360);
ang[1] = (int)(xy[1][1]*360);
ang[2] = (int)(xy[2][1]*360);
ang[3] = 360-ang[0]-ang[1]-ang[2];
response.setHeader("Cache-Control","no-store");
response.setDateHeader("Expires",0);
response.setContentType("image/jpeg");
ServletOutputStream out=response.getOutputStream();
BufferedImage image=new BufferedImage(150,100,BufferedImage.TYPE_INT_RGB);
Graphics2D g=(Graphics2D)image.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.white);
g.fillRect(0,0,150,100);
AffineTransform at = null;
Arc2D arc = null;
int fromAng = baseAng;
at = AffineTransform.getRotateInstance((-20*java.lang.Math.PI)/180,45,37);
g.setTransform(at);
int r =6;
int dx = (int)(r*java.lang.Math.cos((baseAng+ang[0])/2.0*java.lang.Math.PI/180));
int dy = (int)(r*java.lang.Math.sin((baseAng+ang[0])/2.0*java.lang.Math.PI/180));
arc = new Arc2D.Double(10+dx,24-dy,80,50,fromAng,ang[0],Arc2D.PIE);
g.setColor(color[0]);
g.fill(arc);
fromAng+=ang[0];
for (int i=1;i<4;i++)
{
g.setColor(color[i]);
arc = new Arc2D.Double(10,24,80,50,fromAng,ang[i],Arc2D.PIE);
g.fill(arc);
fromAng+=ang[i];
if (fromAng>360)
{
fromAng-=360;
}
}
at = AffineTransform.getRotateInstance(0,arc.getCenterX(),arc.getCenterY());
g.setTransform(at);
for (int i=0;i<4;i++){
g.setColor(color[i]);
g.fillRect(100,15*i+20,10,10);
g.drawString((char)('A'+i)+"",120,15*i+20+8);
}
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
}
public synchronized float[][] getNumAndPercent(String sFileName)
{
float xx[][] = new float[4][2];
int totalNum = 0 ;
String strTemp = null;
int i = 0;
java.io.RandomAccessFile rf = null;
try
{
rf = new java.io.RandomAccessFile (sFileName,"r");
} catch(Exception e)
{
System.out.println(e);
System.exit(0);
}
for (i=0;i<4;i++)
{
int m=0;
try {
strTemp = rf.readLine();
} catch (Exception e){
strTemp = "0";
}
if (strTemp == null) strTemp = "0";
m = new Integer(strTemp).intValue();
xx[i][0]=m;
totalNum += m;
}
if (totalNum==0) totalNum=1;
for ( i=0;i<4;i++){
xx[i][1] = xx[i][0]/totalNum;
}
return xx;
}
}
当进行投票时,count.txt文件中的数据被修改,相应地VoteImage.java文件中的JSP调用servlet生成的图片比例也将被修改。
代码(vote.rar)可见附件,下载后直接用myeclipse导入即可测试。
测试效果可查看图片附件
来源:书籍《JSP实用简明教程》中第九章【JSP与Servlet编程】