我正在创建一个自定义组件,它是给定产品编号的图像查看器。我使用BalusC的ImageServlet的修改版本访问这些文件:
@WebServlet(name="ImageLoader", urlPatterns={"/ImageLoader"})
public class ImageLoader extends HttpServlet {
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
private static String imagePath = "\\\\xxx.xxx.x.x\\root\\path\\to\\images\\";
/**
* This code is a modified version of the ImageServlet found at balusc.blogspot.com.
* It expects the parameters id and n.
* <ul>
* <li><b>id:</b> the product number</li>
* <li><b>n:</b> the image number to load.</li>
*/
public void goGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String productNumber = URLDecoder.decode(request.getParameter("id"),"utf-8");
String img = URLDecoder.decode(request.getParameter("n"),"utf-8");
if (productNumber == null || img == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
String path = generatePath(productNumber);
File image = new File(generatePath(productNumber), generateImageName(img));
// Check if file actually exists in filesystem.
if (!image.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
String contentType = getServletContext().getMimeType(image.getName());
if (contentType == null || !contentType.startsWith("image")) {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
// Init servlet response.
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(image.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams.
input = new BufferedInputStream(new FileInputStream(image), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
close(output);
close(input);
}
}
private String generateImageName(String n) {
int imageNum = Integer.parseInt(n);
StringBuilder ret = new StringBuilder("img-");
if (imageNum < 10) {
ret.append("00");
}
else if(imageNum < 100) {
ret.append("0");
}
ret.append(n);
ret.append(".jpg");
return ret.toString();
}
public static String generatePath(String productNumber) {
Long productNumberLng = Long.parseLong(productNumber);
StringBuilder ret = new StringBuilder(imagePath);
Long thousandPath = productNumberLng - (productNumberLng % 1000);
ret.append(thousandPath);
ret.append("s\\");
ret.append(productNumber);
ret.append("\\");
ret.append(productNumber);
ret.append("\\");
return ret.toString();
}
private static void close(Closeable resource) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
接下来我创建了一个复合组件:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:cc="http://java.sun.com/jsf/composite"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<!-- INTERFACE -->
<cc:interface>
<cc:attribute name="productNumber" shortDescription="The product number whose images should be displayed."
type="java.lang.Long" />
<cc:attribute name="listID" shortDescription="This ID is the html ID of the <ul> element." />
</cc:interface>
<!-- IMPLEMENTATION -->
<cc:implementation>
<div id="#{cc.clientId}">
<ul id="#{cc.attrs.listID}">
<ui:repeat value="#{imageLoaderUtilBean.images}" var="image">
<li>
<h:graphicImage value="#{image.url}" alt="#{image.name}" />
</li>
</ui:repeat>
</ul>
</div>
</cc:implementation>
</html>
正如您所看到的,我只是从托管bean中获取图像列表。这是真正必要的唯一原因是因为我需要知道给定产品有多少图像。这可以变化很大(从8到100)。这是代码:
@ManagedBean
@RequestScoped
public class ImageLoaderUtilBean {
@ManagedProperty(value = "#{param.id}")
private Long productNumber;
private List<EvfImage> images;
public List<EvfImage> getImages() {
if (images == null) {
setImages(findImages());
}
return images;
}
public void setImages(List<EvfImage> images) {
this.images = images;
}
public Long getProductNumber() {
return productNumber;
}
public void setProductNumber(Long productNumber) {
this.productNumber = productNumber;
}
private List<EvfImage> findImages() {
FilenameFilter jpegFilter = new FilenameFilter() {
@Override
public boolean accept(File directory, String filename) {
return filename.toLowerCase().endsWith(".jpg");
}
};
File directory = new File(ImageLoader.generatePath(productNumber.toString()));
if (!directory.exists()) {
return new ArrayList<EvfImage>();
}
File[] files = directory.listFiles(jpegFilter);
List<EvfImage> ret = new ArrayList<EvfImage>();
for (int i = 1; i <= files.length; i++) {
EvfImage img = new EvfImage();
img.setName("file.getName()");
img.setUrl("/ImageLoader?id=" + productNumber + "&n=" + i);
ret.add(img);
}
return ret;
}
}
有一个简单的对象用于保存迭代的数据:
public class EvfImage {
private String url;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
最后,我使用http://localhost:8080/project-name/testImages.xhtml?id=213123的URL测试此复合组件。这是testImages.xhtml的代码:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:sdCom="http://java.sun.com/jsf/composite/components/sd">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<sdCom:imageViewer listID="test" />
</h:body>
</html>
问题在于:应用程序和复合组件之间唯一的交互点应该是标记<sdCom:imageViewer listID="test" />
。然而,这是一个漏洞的抽象。根据请求的id
参数为托管bean提供产品编号。这非常不合需要。它在组件和正在使用它的应用程序之间创建了更紧密的耦合。理想情况下,我应该使用以下标记:<sdCom:imageViewer listID="test" productNumber="213123"/>
。但是,我无法想办法做到这一点,仍然知道需要创建多少图像。
提前致谢, 扎克
编辑:调用一个接收产品编号并返回该产品所具有的图像数量的servlet是完全可以接受的。但是,我还没有找到一种方法来运行循环n
次(for循环),而不是为Collection(foreach循环)中的每个对象运行一次。我对任何涉及从支持bean中删除@ManagedProperty("#{param.id}")
的解决方案感到非常满意。
答案 0 :(得分:2)
替换@ManagedProperty(value="#{param.id}")
中的ImageLoaderUtilBean
将是
<sdCom:imageViewer listID="test" productNumber="#{param.id}" />
在<{em> cc:implementation
之前与ui:repeat
中的以下内容结合使用:
<c:set target="#{imageLoaderUtilBean}" property="productNumber" value="#{cc.attrs.productNumber}" />
c:
是(实际上不鼓励的)Facelets的内置JSTL库,其声明如下:
xmlns:c="http://java.sun.com/jsp/jstl/core"
Facelets无法取代c:set
(还有?)。