1、准备:
先新建工程,如JSFX,并引入commons- fileupload.jar和commons-io.jar两个包(版本为1.2),源文件目录结构如下:
jsf官方实现默认是不支持multipart/form -data类型的表单的,为了使jsf能够解析multipart/form-data表单的数据,我参考了myfaces1.1的方式,然 后按照commons-fileupload1.2重构了部分代码(myfaces1.1使用的是commons-fileupload1.1)
myfaces之所以能处理multipart/form-data类型的 表单,关键就在于MultipartFilter和MultipartRequestWrapper这两个类,下面是我的代码:
MultipartFilter.java:
- package com.jsfx.filter;
- import java.io.IOException;
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
- /**
- * 用以解析multipart表单的过滤器
- * 代码主要来自myFaces1.1的MultipartFilter类
- * 主要区别是使用了commons-fileupload1.2处理文件上传
- * */
- public class MultipartFilter implements Filter {
- private int uploadMaxFileSize = 10 * 1024 * 1024; // 默认文件最大大小为10 MB
- private int uploadThresholdSize = 1 * 1024 * 1024; // 默认临界值大小为1 MB(即超过1m的文件将使用缓存)
- private String uploadRepositoryPath = null;//临时文件夹,默认为空,由虚拟机分配
- public void init(FilterConfig filterConfig) {
- uploadMaxFileSize = resolveSize(filterConfig
- .getInitParameter("uploadMaxFileSize"), uploadMaxFileSize);
- uploadThresholdSize = resolveSize(filterConfig
- .getInitParameter("uploadThresholdSize"), uploadThresholdSize);
- uploadRepositoryPath = filterConfig
- .getInitParameter("uploadRepositoryPath");
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- if (!(response instanceof HttpServletResponse)) {
- chain.doFilter(request, response);
- return;
- }
- HttpServletRequest httpRequest = (HttpServletRequest) request;
- if (ServletFileUpload.isMultipartContent(httpRequest)) {//判断表单类型
- chain.doFilter(new MultipartRequestWrapper(httpRequest,
- uploadMaxFileSize, uploadThresholdSize,
- uploadRepositoryPath), response);
- //如果为multipart类型,对request进行包装,使jsf能解析表单数据
- } else {
- chain.doFilter(request, response);
- }
- }
- public void destroy() {
- }
- private int resolveSize(String param, int defaultValue) {
- int numberParam = defaultValue;
- if (param != null) {
- param = param.toLowerCase();
- int factor = 1;
- String number = param;
- if (param.endsWith("g")) {
- factor = 1024 * 1024 * 1024;
- number = param.substring(0, param.length() - 1);
- } else if (param.endsWith("m")) {
- factor = 1024 * 1024;
- number = param.substring(0, param.length() - 1);
- } else if (param.endsWith("k")) {
- factor = 1024;
- number = param.substring(0, param.length() - 1);
- }
- numberParam = Integer.parseInt(number) * factor;
- }
- return numberParam;
- }
- }
MultipartRequestWrapper.java
- package com.jsfx.filter;
- import java.io.File;
- import java.io.UnsupportedEncodingException;
- import java.util.Collections;
- import java.util.Enumeration;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import javax.faces.application.FacesMessage;
- import javax.faces.context.FacesContext;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletRequestWrapper;
- import org.apache.commons.fileupload.FileItem;
- import org.apache.commons.fileupload.FileUploadBase;
- import org.apache.commons.fileupload.FileUploadException;
- import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
- /**
- * Request的包装类,使jsf能解析表单数据 代码主要来自myFaces1.1的MultipartRequestWrapper类
- * 主要区别是使用了commons-fileupload1.2处理文件上传
- */
- @SuppressWarnings("unchecked")
- public class MultipartRequestWrapper extends HttpServletRequestWrapper {
- public static final String UPLOADED_FILES_ATTRIBUTE = "org.apache.myfaces.uploadedFiles";
- public static final String WWW_FORM_URLENCODED_TYPE = "application/x-www-form-urlencoded";
- HttpServletRequest request = null;
- HashMap parametersMap = null;// 参数表
- ServletFileUpload fileUpload = null;
- HashMap fileItems = null;// 上传文件表
- int maxSize;// 表单最大大小
- int thresholdSize;// 临界值大小
- String repositoryPath;// 临时文件夹位置
- public MultipartRequestWrapper(HttpServletRequest request, int maxSize,
- int thresholdSize, String repositoryPath) {
- super(request);
- this.request = request;
- this.maxSize = maxSize;
- this.thresholdSize = thresholdSize;
- this.repositoryPath = repositoryPath;
- }
- @Override
- public Enumeration getParameterNames() {
- if (parametersMap == null)
- parseRequest();
- return Collections.enumeration(parametersMap.keySet());
- }
- @Override
- public String getParameter(String name) {
- if (parametersMap == null)
- parseRequest();
- String[] values = (String[]) parametersMap.get(name);
- if (values == null)
- return null;
- return values[0];
- }
- @Override
- public String[] getParameterValues(String name) {
- if (parametersMap == null)
- parseRequest();
- return (String[]) parametersMap.get(name);
- }
- @Override
- public Map getParameterMap() {
- if (parametersMap == null)
- parseRequest();
- return parametersMap;
- }
- /**
- * 获取请求中的FileItem
- */
- public FileItem getFileItem(String fieldName) {
- if (fileItems == null)
- parseRequest();
- return (FileItem) fileItems.get(fieldName);
- }
- /**
- * 获取请求中的FileItem表
- */
- public Map getFileItems() {
- if (fileItems == null)
- parseRequest();
- return fileItems;
- }
- @Override
- public Object getAttribute(String string) {
- if (string.equals(UPLOADED_FILES_ATTRIBUTE)) {
- return getFileItems();
- }
- return super.getAttribute(string);
- }
- @Override
- public String getContentType() {
- return WWW_FORM_URLENCODED_TYPE;
- }
- /**
- * 最关键的部分,解析表单数据
- */
- private void parseRequest() {
- DiskFileItemFactory factory = new DiskFileItemFactory();
- factory.setSizeThreshold(thresholdSize);// 设置临届大小
- if (repositoryPath != null && repositoryPath.trim().length() > 0)
- factory.setRepository(new File(repositoryPath));// 设置临时文件夹
- fileUpload = new ServletFileUpload();
- fileUpload.setFileItemFactory(factory);
- fileUpload.setSizeMax(maxSize);// 设置表单最大大小
- String charset = request.getCharacterEncoding();
- fileUpload.setHeaderEncoding(charset);
- List requestParameters = null;
- try {
- requestParameters = fileUpload.parseRequest(request);
- } catch (FileUploadBase.SizeLimitExceededException e) {
- e.printStackTrace();
- FacesContext.getCurrentInstance().addMessage("",
- new FacesMessage(e.getMessage()));// 文件超过大小时提示用户
- requestParameters = Collections.EMPTY_LIST;
- } catch (FileUploadException fue) {
- fue.printStackTrace();
- FacesContext.getCurrentInstance().addMessage("",
- new FacesMessage(fue.getMessage()));
- requestParameters = Collections.EMPTY_LIST;
- }
- parametersMap = new HashMap(requestParameters.size());// 建立参数表
- fileItems = new HashMap();
- for (Iterator iter = requestParameters.iterator(); iter.hasNext();) {
- FileItem fileItem = (FileItem) iter.next();
- if (fileItem.isFormField()) {// 普通参数处理
- String name = fileItem.getFieldName();
- String value = null;
- if (charset == null) {
- value = fileItem.getString();
- } else {
- try {
- value = new String(fileItem.get(), charset);
- } catch (UnsupportedEncodingException e) {
- value = fileItem.getString();
- }
- }
- addTextParameter(name, value);// 添加参数
- } else {// 参数是一个文件
- if (fileItem.getName() != null) {
- fileItems.put(fileItem.getFieldName(), fileItem);// 添加Fileitem
- }
- }
- }
- for (Iterator it = request.getParameterMap().entrySet().iterator(); it
- .hasNext();) {
- Map.Entry entry = (Map.Entry) it.next();
- Object value = entry.getValue();
- if (value instanceof String[]) {
- String[] valuesArray = (String[]) entry.getValue();
- for (int i = 0; i < valuesArray.length; i++) {
- addTextParameter((String) entry.getKey(), valuesArray[i]);
- }
- } else if (value instanceof String) {
- String strValue = (String) entry.getValue();
- addTextParameter((String) entry.getKey(), strValue);
- } else if (value != null)
- throw new IllegalStateException("value of type : "
- + value.getClass() + " for key : " + entry.getKey()
- + " cannot be handled.");
- }
- }
- private void addTextParameter(String name, String value) {
- if (!parametersMap.containsKey(name)) {
- String[] valuesArray = { value };
- parametersMap.put(name, valuesArray);
- } else {
- String[] storedValues = (String[]) parametersMap.get(name);
- int lengthSrc = storedValues.length;
- String[] valuesArray = new String[lengthSrc + 1];
- System.arraycopy(storedValues, 0, valuesArray, 0, lengthSrc);
- valuesArray[lengthSrc] = value;
- parametersMap.put(name, valuesArray);
- }
- }
- }
最后在web.xml配置过滤器,sun的jsf实现就可以处理 multipart/form-data表单了。
web.xml:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <context-param>
- <param-name>javax.faces.CONFIG_FILES</param-name>
- <param-value>/WEB-INF/faces-config.xml</param-value>
- </context-param>
- <servlet>
- <servlet-name>Faces Servlet</servlet-name>
- <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
- <load-on-startup>0</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>Faces Servlet</servlet-name>
- <url-pattern>*.faces</url-pattern>
- </servlet-mapping>
- <description>=====配置过滤器=====</description>
- <filter>
- <filter-name>MultipartFilter</filter-name>
- <filter-class>com.jsfx.filter.MultipartFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>MultipartFilter</filter-name>
- <servlet-name>Faces Servlet</servlet-name>
- </filter-mapping>
- <description>==================</description>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
2、UploadedFile.java:作为标签的value存储上传文件相关属性的类。
- package com.jsfx.fileupload;
- import java.io.ByteArrayInputStream;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import org.apache.commons.fileupload.FileItem;
- public class UploadedFile {
- private String name;
- private String contentType;
- private FileItem fileItem;
- public UploadedFile(FileItem fileItem) throws IOException {
- this.name = fileItem.getName();
- this.contentType = fileItem.getContentType();
- this.fileItem = fileItem;
- }
- public void save(String file) {// 保存文件
- try {
- fileItem.write(new File(file));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public byte[] getBytes() throws IOException {
- byte[] bytes = new byte[(int) getSize()];
- if (fileItem != null)
- fileItem.getInputStream().read(bytes);
- return bytes;
- }
- public InputStream getInputStream() throws IOException {
- return fileItem != null ? fileItem.getInputStream()
- : new ByteArrayInputStream(new byte[0]);
- }
- public String getContentType() {
- return contentType;
- }
- public String getName() {
- return name;
- }
- public long getSize() {
- return fileItem != null ? fileItem.getSize() : 0;
- }
- }
UploadedFileConverter.java用来转化UploadedFile的类型
- package com.jsfx.fileupload;
- import javax.faces.component.UIComponent;
- import javax.faces.context.FacesContext;
- import javax.faces.convert.Converter;
- import javax.faces.convert.ConverterException;
- public class UploadedFileConverter implements Converter {
- public Object getAsObject(FacesContext facescontext,
- UIComponent uicomponent, String s) throws ConverterException {
- return null;
- }
- public String getAsString(FacesContext facescontext,
- UIComponent uicomponent, Object obj) throws ConverterException {
- if (obj instanceof UploadedFile) {
- return ((UploadedFile) obj).getName();
- } else {
- return null;
- }
- }
- }
3、实现标签描述库,这里使用的UploadTag类,下面将会提到
jsfx.tld(注意看它在上面项目中的位置)
- <?xml version="1.0" encoding="UTF-8"?>
- <taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee web-jsptaglibrary_2_1.xsd">
- <tlib-version>1.0</tlib-version>
- <short-name>x</short-name>
- <uri>http://jsfx.com/</uri>
- <tag>
- <name>upload</name>
- <tag-class>com.jsfx.fileupload.UploadTag</tag-class>
- <body-content>JSP</body-content>
- <description>
- 为了简化开发只定义了几个必要和常用的属性如id,value,required,style,onchange等等
- </description>
- <attribute>
- <name>id</name>
- <rtexprvalue>true</rtexprvalue>
- </attribute>
- <attribute>
- <name>value</name>
- <rtexprvalue>false</rtexprvalue>
- <deferred-value>
- <type>com.jsfx.fileupload.UploadedFile</type>
- </deferred-value>
- </attribute>
- <attribute>
- <name>converter</name>
- <rtexprvalue>false</rtexprvalue>
- <deferred-value>
- <type>com.jsfx.fileupload.UploadedFileConvert</type>
- </deferred-value>
- </attribute>
- <attribute>
- <name>required</name>
- <rtexprvalue>false</rtexprvalue>
- <deferred-value>
- <type>boolean</type>
- </deferred-value>
- </attribute>
- <attribute>
- <name>disabled</name>
- <rtexprvalue>false</rtexprvalue>
- <deferred-value>
- <type>boolean</type>
- </deferred-value>
- </attribute>
- <attribute>
- <name>readonly</name>
- <rtexprvalue>false</rtexprvalue>
- <deferred-value>
- <type>boolean</type>
- </deferred-value>
- </attribute>
- <attribute>
- <name>style</name>
- <rtexprvalue>false</rtexprvalue>
- <deferred-value>
- <type>java.lang.String</type>
- </deferred-value>
- </attribute>
- <attribute>
- <name>styleClass</name>
- <rtexprvalue>false</rtexprvalue>
- <deferred-value>
- <type>java.lang.String</type>
- </deferred-value>
- </attribute>
- <attribute>
- <name>onchange</name>
- <required>false</required>
- <deferred-value>
- <type>java.lang.String</type>
- </deferred-value>
- </attribute>
- </tag>
- </taglib>
一个jsf自定义组件通常由
(1)标签属性处理类:主要作用是从页面标签接收值。继承至UIComponentELTag,这里与jsf1.1不同,由于使用了统一EL表 达式。
(2)Component类:主要作用为在Server端保存及恢复组件状态。
(3)Renderer类: 主要功能是 在响应阶段将Java组件的属性转换为HTML代码,在接受请求阶段将HTML Request中传来的资料转换为Java组件的属性。
4、标签属性处理类:
UploadTag.java
- package com.jsfx.fileupload;
- import javax.faces.component.UIComponent;
- import javax.faces.context.FacesContext;
- import javax.faces.convert.Converter;
- import javax.faces.webapp.UIComponentELTag;
- import javax.servlet.jsp.JspException;
- public class UploadTag extends UIComponentELTag {
- private javax.el.ValueExpression value;
- private javax.el.ValueExpression converter;
- private javax.el.ValueExpression styleClass;
- private javax.el.ValueExpression disabled;
- private javax.el.ValueExpression required;
- private javax.el.ValueExpression style;
- private javax.el.ValueExpression onchange;
- @Override
- public String getComponentType() {
- return "HtmlUpload";//返回Component的类型,在faces-config.xml中找到相应的类
- }
- @Override
- public String getRendererType() {
- return "UploadRenderer";//返回Renderer的类型,在faces-config.xml中找到相应的类
- }
- public void setValue(javax.el.ValueExpression value) {
- this.value = value;
- }
- public void setConverter(javax.el.ValueExpression converter) {
- this.converter = converter;
- }
- public void setRequired(javax.el.ValueExpression required) {
- this.required = required;
- }
- public void setDisabled(javax.el.ValueExpression disabled) {
- this.disabled = disabled;
- }
- public void setStyle(javax.el.ValueExpression style) {
- this.style = style;
- }
- public void setStyleClass(javax.el.ValueExpression styleClass) {
- this.styleClass = styleClass;
- }
- public void setOnchange(javax.el.ValueExpression onchange) {
- this.onchange = onchange;
- }
- @Override
- protected void setProperties(UIComponent component) {
- super.setProperties(component);
- javax.faces.component.UIInput input = null;
- try {
- input = (javax.faces.component.UIInput) component;
- } catch (ClassCastException cce) {
- throw new IllegalStateException(
- "Component "
- + component.toString()
- + " not expected type. Expected: javax.faces.component.UIInput. Perhaps you're missing a tag?");
- }
- if (converter != null) {
- if (!converter.isLiteralText()) {
- input.setValueExpression("converter", converter);
- } else {
- Converter conv = FacesContext.getCurrentInstance()
- .getApplication().createConverter(
- converter.getExpressionString());
- input.setConverter(conv);
- }
- }
- if (value != null) {
- input.setValueExpression("value", value);
- }
- if (required != null) {
- input.setValueExpression("required", required);
- }
- if (disabled != null) {
- input.setValueExpression("disabled", disabled);
- }
- if (style != null) {
- input.setValueExpression("style", style);
- }
- if (styleClass != null) {
- input.setValueExpression("styleClass", styleClass);
- }
- if (onchange != null) {
- input.setValueExpression("onchange", onchange);
- }
- }
- @Override
- public int doStartTag() throws JspException {
- try {
- return super.doStartTag();
- } catch (Exception e) {
- Throwable root = e;
- while (root.getCause() != null) {
- root = root.getCause();
- }
- throw new JspException(root);
- }
- }
- @Override
- public int doEndTag() throws JspException {
- try {
- return super.doEndTag();
- } catch (Exception e) {
- Throwable root = e;
- while (root.getCause() != null) {
- root = root.getCause();
- }
- throw new JspException(root);
- }
- }
- @Override
- public void release() {
- super.release();
- this.value = null;
- this.converter = null;
- this.disabled = null;
- this.style = null;
- this.styleClass = null;
- this.required = null;
- this.onchange = null;
- }
- }
5、Component类
HtmlUpload.java
- package com.jsfx.fileupload;
- import java.util.ArrayList;
- import java.util.List;
- import javax.el.ValueExpression;
- import javax.faces.component.UIInput;
- public class HtmlUpload extends UIInput {
- private java.lang.Boolean disabled;
- private java.lang.String style;
- private java.lang.String styleClass;
- private java.lang.String onchange;
- public java.lang.String getOnchange() {
- if (null != this.onchange) {
- return this.onchange;
- }
- ValueExpression _ve = getValueExpression("onchange");
- if (_ve != null) {
- return (java.lang.String) _ve.getValue(getFacesContext()
- .getELContext());
- } else {
- return null;
- }
- }
- public void setOnchange(java.lang.String onchange) {
- this.onchange = onchange;
- handleAttribute("onchange", onchange);
- }
- public boolean isDisabled() {
- if (null != this.disabled) {
- return this.disabled;
- }
- ValueExpression _ve = getValueExpression("disabled");
- if (_ve != null) {
- return (java.lang.Boolean) _ve.getValue(getFacesContext()
- .getELContext());
- } else {
- return false;
- }
- }
- public void setDisabled(boolean disabled) {
- this.disabled = disabled;
- }
- public java.lang.String getStyle() {
- if (null != this.style) {
- return this.style;
- }
- ValueExpression _ve = getValueExpression("style");
- if (_ve != null) {
- return (java.lang.String) _ve.getValue(getFacesContext()
- .getELContext());
- } else {
- return null;
- }
- }
- public void setStyle(java.lang.String style) {
- this.style = style;
- handleAttribute("style", style);
- }
- public java.lang.String getStyleClass() {
- if (null != this.styleClass) {
- return this.styleClass;
- }
- ValueExpression _ve = getValueExpression("styleClass");
- if (_ve != null) {
- return (java.lang.String) _ve.getValue(getFacesContext()
- .getELContext());
- } else {
- return null;
- }
- }
- public void setStyleClass(java.lang.String styleClass) {
- this.styleClass = styleClass;
- }
- public HtmlUpload() {
- super();
- setRendererType("TestRenderer");
- }
- @SuppressWarnings("unchecked")
- private void handleAttribute(String name, Object value) {
- List<String> setAttributes = null;
- setAttributes = (List<String>) this.getAttributes().get(
- "javax.faces.component.UIComponentBase.attributesThatAreSet");
- if (setAttributes == null) {
- setAttributes = new ArrayList<String>(6);
- this
- .getAttributes()
- .put(
- "javax.faces.component.UIComponentBase.attributesThatAreSet",
- setAttributes);
- }
- if (value == null) {
- setAttributes.remove(name);
- } else if (!setAttributes.contains(name)) {
- setAttributes.add(name);
- }
- }
- }
6、Renderer类
UploadRenderer.java
- package com.jsfx.fileupload;
- import java.io.IOException;
- import java.util.Map;
- import javax.faces.component.UIComponent;
- import javax.faces.context.ExternalContext;
- import javax.faces.context.FacesContext;
- import javax.faces.context.ResponseWriter;
- import javax.faces.convert.ConverterException;
- import javax.servlet.ServletRequest;
- import javax.servlet.http.HttpServletRequestWrapper;
- import org.apache.commons.fileupload.FileItem;
- import com.jsfx.filter.MultipartRequestWrapper;
- import com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer;
- public class UploadRenderer extends HtmlBasicInputRenderer {
- @Override
- /**
- * 生成<input: type=file/>的html标签
- * */
- protected void getEndTextToRender(FacesContext context,
- UIComponent component, String currentValue) throws IOException {
- String style = (String) component.getAttributes().get("style");
- String styleClass = (String) component.getAttributes()
- .get("styleClass");
- Boolean disabled = (Boolean) component.getAttributes().get("disabled");
- String onchange = (String) component.getAttributes().get("onchange");
- ResponseWriter writer = context.getResponseWriter();
- assert (writer != null);
- writer.startElement("input", component);
- writeIdAttributeIfNecessary(context, writer, component);
- writer.writeAttribute("type", "file", null);
- writer.writeAttribute("name", (component.getClientId(context)),
- "clientId");
- if (currentValue != null) {
- writer.writeAttribute("value", currentValue, "value");
- }
- if (null != styleClass) {
- writer.writeAttribute("class", styleClass, "styleClass");
- }
- if (null != style) {
- writer.writeAttribute("style", style, "style");
- }
- if (null != disabled) {
- writer.writeAttribute("disabled", disabled, "disabled");
- }
- if (null != onchange) {
- writer.writeAttribute("onchange", onchange, "onchange");
- }
- writer.endElement("input");
- }
- @Override
- @SuppressWarnings("unchecked")
- /**
- * 这个方法将取出Request中的文件数据,并将提交的“value” uploadedFile实例化
- * */
- public void decode(FacesContext facesContext, UIComponent uiComponent) {
- super.decode(facesContext, uiComponent);
- Object request = facesContext.getExternalContext().getRequest();
- if (!(request instanceof ServletRequest)) {
- ExternalContext externalContext = facesContext.getExternalContext();
- Map fileItems = (Map) externalContext.getRequestMap().get(
- MultipartRequestWrapper.UPLOADED_FILES_ATTRIBUTE);
- FileItem fileItem = null;
- if (fileItems != null) {
- String paramName = uiComponent.getClientId(facesContext);
- fileItem = (FileItem) fileItems.get(paramName);
- }
- if (fileItem != null) {
- try {
- UploadedFile upFile;
- upFile = new UploadedFile(fileItem);//实例化提交的value
- ((HtmlUpload) uiComponent).setSubmittedValue(upFile);
- ((HtmlUpload) uiComponent).setValid(true);
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- return;
- }
- if (facesContext.getExternalContext().getRequest() instanceof ServletRequest) {
- ServletRequest multipartRequest = (ServletRequest) facesContext
- .getExternalContext().getRequest();
- while (multipartRequest != null
- && !(multipartRequest instanceof MultipartRequestWrapper)) {
- if (multipartRequest instanceof HttpServletRequestWrapper) {
- multipartRequest = ((HttpServletRequestWrapper) multipartRequest)
- .getRequest();
- } else {
- multipartRequest = null;
- }
- }
- if (multipartRequest != null) {
- MultipartRequestWrapper mpReq = (MultipartRequestWrapper) multipartRequest;
- String paramName = uiComponent.getClientId(facesContext);
- FileItem fileItem = mpReq.getFileItem(paramName);
- if (fileItem != null) {
- try {
- UploadedFile upFile;
- upFile = new UploadedFile(fileItem);//实例化提交的value
- ((HtmlUpload) uiComponent).setSubmittedValue(upFile);
- ((HtmlUpload) uiComponent).setValid(true);
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- }
- }
- }
- @Override
- public Object getConvertedValue(FacesContext context,
- UIComponent component, Object submittedValue)
- throws ConverterException {
- if (submittedValue instanceof UploadedFile) {
- UploadedFile file = (UploadedFile) submittedValue;
- if (file.getName() != null && file.getName().length() > 0) {
- return file;
- }
- }
- return null;
- }
- }
7、整合
上面几个部分需要配置才能互相配合工作,这就需要UploadTag.java中的 getComponentType()、getRendererType()两个方法及配置文件。为了保证组件的独立性,我把faces-config.xml打包进了类的META-INF文件夹(见最上面项目的结构)。
faces-config.xml:
- <?xml version="1.0" encoding="UTF-8"?>
- <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xi="http://www.w3.org/2001/XInclude"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
- <component>
- <component-type>HtmlUpload</component-type>
- <component-class>
- com.jsfx.fileupload.HtmlUpload
- </component-class>
- </component>
- <render-kit>
- <renderer>
- <component-family>javax.faces.Input</component-family>
- <renderer-type>UploadRenderer</renderer-type>
- <renderer-class>
- com.jsfx.fileupload.UploadRenderer
- </renderer-class>
- </renderer>
- </render-kit>
- </faces-config>
8、打包
只要按照上面的目录结构打包就可以保证组件的独立性了,只需要配置web.xml的过滤 器
然后在需要的页面引入标签:<%@ taglib uri="http://jsfx.com/" prefix="x"%>
就可以像这样<x:upload id="upload" value="#{user.picture}" οnchange="fileTypeCheck()"></x:upload>就可以使用标签了
注意:最好用jdk5编译,用高版本的话可能会与jsf1.2有冲突。
本来有个使用样例的,在这里就不贴出来了,到这里可以下载,包括上面所有源代码。
http://download.csdn.net/source/637158