//declarea"global"referencetoaninstanceofthehomeinterfaceofthesessionbeanAccountHomeaccHome=null;publi" />

如何在servlet中实时地创建图象

jsp与ejb通信

(编译/Blueski)

以下是一个snippet代码,演示了JSP页面如何与 EJB session bean进行相互作用。

<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account" %>
<%!
//declare a "global" reference to an instance of the home interface of the session bean
AccountHome accHome=null;

public void jspInit() {
//obtain an instance of the home interface
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
}
%>
<%
//instantiate the session bean
Account acct = accHome.create();
//invoke the remote methods
acct.doWhatever(...);
// etc etc...
%>
在JSP中java代码应该越少越好。
在以上例子中,JSP设计者不得不处理和理解存取EJB的机理。 代替 在一个Mediator中对EJB机制的压缩以及将EJB方法作为Mediator的方法,
可以在jsp中使用 Mediator。Mediator通常由EJB设计者编写。Mediator可以提供附加的值如attribute caching等.

*****

JSP scriptlet代码必须最小化。如果要在jsp中直接请求ejb可能要在jsp 中写许多代码,包括try...catch等函数块来进行操作。

使用一个标准的JavaBean作为一个jsp和EJB服务器的中介可以减少在jsp中的java代码的数量,并可提高可重用性。这个JavaBean必须是一个你所存取的EJB的覆盖(wrapper)。

如果你使用标准的JavaBean,你可以使用 jsp:useBean标记来初始化EJB参数,如服务器URL和服务器
安全参数等。

自定义标记也可以是一种选择。但是,这要求比一个简单JavaBean wrapper更多的编码。
该处必须被重新写为尽可能小的代码并保证JSP脚本内容尽可能轻(light)。


如何在servlet中实时地创建图象

---摘自互联网

在Java创建图象或进行图象处理,有几个包和类是需要用到的。详细请参阅Purple Servlet References。

当您的servlet有图象文件时您有两个选择。

把文件写入磁盘并提供连接。注意写在您的web服务器目录树下(不是在服务器磁盘的任何地方都行。)你可以用Java 2 JPEGCodec类,或Acme Labs' GIFEncoder类将Java Graphics 转换成图象文件或二进制流.
值得一提的是在一些servlet引擎设置中,servlet的目录不能通过web server进入,只能通过servlet引擎,也就是说您不能通过http:// URL登录,您可以向您的servlet输出的HTML传送IMG标签,或传送HTTP重新定位来让浏览器直接下载图象。
(CookieDetector (https://www.360docs.net/doc/7410829552.html,/code/CookieDetector.html) has an example, with source code, of sending a redirect.)
(CookieDetector (https://www.360docs.net/doc/7410829552.html,/code/CookieDetector.html) 有一个例子,有传送重新定位源代码。
图象可以被保存在浏览器的cache中,当再次请求时不必重新运行servlet,

因此减轻了服务器的负担。
).

图象不能从磁盘中删除,因此您必须写一段程序来定期清理图象目录,或进入目录后用手工删除。(或买一张大点的硬盘):-)

2.直接从servlet输出图象。通过给image/gif (for GIFs)或 image/jpeg (for JPEGs)设置Content-type头来实现它。然后打开HttpResponse output流作为原始流而不是打印流,用write()方法直接传送字节。

以下是一个用servlet实时创建图像的例子程序

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.sun.image.codec.jpeg.*;
import java.awt.image.*;
import java.awt.*;
public class JPEGServlet extends HttpServlet {
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/jpeg");
ServletOutputStream out = response.getOutputStream();
BufferedImage image = new BufferedImage(100,100, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.green);
g.fillRect(0, 0, 100, 100);
g.setColor(Color.red);
g.drawOval(0, 0, 100,100);
JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
//Get Servlet information
public String getServletInfo() {
return "JPEGServlet Information";
}
}



从数据库中读取并生成图片的Servlet

(文/邵望)
大体思路
1)创建ServletOutputStream对象out,用于以字节流的方式输出图像
2)查询数据库,用getBinaryStream方法返回InputStream对象in
3)创建byte数组用作缓冲,将in读入buf[],再由out输出

注:下面的例程中数据库连接用了ConnectionPool,以及参数的获得进行了预处理

package net.seasky.music;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import net.seasky.util.*;
import net.seasky.database.DbConnectionManager;

public class CoverServlet extends HttpServlet {
private static final String CONTENT_TYPE = "image/gif";
public void init(ServletConfig config) throws ServletException {
super.init(config);
}

public void doGet(HttpServletRequest request, HttpServletResponse response
) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
int albumID;
ServletOutputStream out = response.getOutputStream();
try {
albumID = ParamManager.getIntParameter(request,"albumID",0);
}
catch (Exception e) {
response.sendRedirect("../ErroePage.jsp");
return;
}
try {
InputStream in=this.getCover(albumID);
int len;
byte buf[]=new byte

[1024];
while ((len=in.read(buf,0,1024))!=-1) {
out.write(buf,0,len);
}
}
catch (IOException ioe) {
ioe.printStackTrace() ;
}
}

private InputStream getCover(int albumID) {
InputStream in=null;
Connection cn = null;
PreparedStatement pst = null;
try {
cn=DbConnectionManager.getConnection();
cn.setCatalog("music");
pst=cn.prepareStatement("SELECT img FROM cover where ID =?");
pst.setInt(1,albumID);
ResultSet rs=pst.executeQuery();
rs.next() ;
in=rs.getBinaryStream("img");
}
catch (SQLException sqle) {
System.err.println("Error in CoverServlet : getCover()-" + sqle);
sqle.printStackTrace() ;
}
finally {
try {
pst.close() ;
cn.close() ;
}
catch (Exception e) {
e.printStackTrace();
}
}
return in;
}

public void destroy() {
}
}

JSP生成jpeg图片用于投票

---摘自https://www.360docs.net/doc/7410829552.html, (文/东方一蛇)

一、前言

本文原作者为Tony Wang ,该文章涉及到文件的读写和jpg图片的自动生成。利用jsp+servlet的技术,jsp调用servlet生成图片。

二、首文件index.jsp如下:

<%--

Author: Tony Wang

E-mail: lucky_tony@https://www.360docs.net/doc/7410829552.html,

Date: 2001-01-01

如果对程序有什么疑问,可以和我联系, 另外程序如果有什么bug,麻烦指出!!

--%>

<%@ page contentType="text/html;charSet=gb2312"%>
<%
response.setHeader("Cache-Control","no-store");
response.setDateHeader("Expires",0);
%>
<%!
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) {
strTemp = "None Question";
}
if(strTemp==null)strTemp = "None Question";
strQ = strTemp;
}
return strQ;
}

%>

<%
String s = null;
String[] question = new String[4];

s = request.getRealPath("question.txt");
question = getQuestion(s);
%>

























冰帆调查

<%
String ss = null;
for (int i=0;i<4;i++)
{
ss = ""+(char)('A'+i)+"、"+ question[i]+"
";
out.println(ss);
}
%>





三、写文件write.jsp

<%--
Author: Tony Wang
E-mail: lucky_tony@https://www.360docs.net/doc/7410829552.html,
Date: 2001-01-01
如果对程序有什么疑问,可以和我联系,
另外程序如果有什么bug,麻烦指出!!
--%>
<%!
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)
{
System.out.println(e);
System.exit(0);
}
for(i=0;i<4;i++)
{
try {
strTemp = rf.readLine();
} catch(Exception e) {
strTemp = "0";
}
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) {
System.out.println("Write file error:"+e.getMessage());
}
}
%>


<%
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");
%>
四、servlet原代码:VoteImage.java :

/*
Author: Tony Wang
E-mail: lucky_tony@https://www.360docs.net/doc/7410829552.html,
Date: 2001-01-01
如果对程序有什么疑问,可以和我联系,
另外程序如果有什么bug,麻烦指出!!
*/
import java.io.*;
import java.util.*;
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
{
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*https://www.360docs.net/doc/7410829552.html,ng.Math.PI)/180,45,37);
g.setTransform(at);

int r =6;
int dx = (int)(r*https://www.360docs.net/doc/7410829552.html,ng.Math.cos((baseAng+ang[0])/2.0*https://www.360docs.net/doc/7410829552.html,ng.Math.PI/180));
int dy = (int)(r*https://www.360docs.net/doc/7410829552.html,ng.Math.sin((baseAng+ang[0])/2.0*https://www.360docs.net/doc/7410829552.html,ng.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 void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
doGet(request,response);
}

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;
}
}

五、在index.jsp目录下建立question.txt和count.txt文件分别用来保存投票的问题和投票的数量,用户投票后,就修改count.txt的值。

为了对原作者表示感谢,这2个文件内容不变化,如下:


question.txt:

Yes,I think so!

No,I dont think so!

Sorry,I dont know the answer!


count.txt:

12

9

5

9

六、目录结构:

(1)jsp文件和txt文件同一个目录

(2).java文件是servlet目录下

七、测试:

http://[server:port]/dir/index.jsp

相关文档
最新文档