struts 2とfckeditorの統合

9876 ワード

struts 2では、デフォルトのactionはserverltと同様に接尾辞(.action)がないため、このときはアドレスにアクセスし、serletである可能性が高く、actionである可能性が高い.本稿で使用するfckeditorは、画像をアップロードする際にservletの機能を利用しているが、この場合もstruts 2がプロジェクトで使用されている場合、struts 2はデフォルトでこのアドレスをブロックしsturts 2処理に渡す.そのため、画像を正常にアップロードしたり閲覧したりする機能がありません.
具体的な統合プロセスは簡単ですが、ここではstruts 2のactionを修正し、アップロードされた画像のアドレスをfckeditorに渡して処理します.
Webを見るxmlファイル
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <servlet>
    <servlet-name>ConnectorServlet</servlet-name>
    <servlet-class>net.b2c.u.servlet.ConnectorServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>ConnectorServlet</servlet-name>
    <url-pattern>/fckeditor/editor/filemanager/connectors/*</url-pattern>
  </servlet-mapping>
  

    <filter-name>struts2</filter-name>
    <filter-class>net.b2c.u.interceptor.StrutsAndFckFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <error-page>
    <error-code>403</error-code>
    <location>/404.htm</location>
  </error-page>
  <error-page>
    <error-code>404</error-code>
    <location>/404.htm</location>
  </error-page>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

その中で、上の段は1段のコードをパッケージして、主に中国語の文字化けしの問題を解決します.
package net.b2c.u.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.fckeditor.requestcycle.ThreadLocalData;
import net.fckeditor.response.GetResponse;
import net.fckeditor.response.UploadResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Connector servlet of the File Browser. It accepts requests begins the request
 * cycle, forwards requests to the {@link Dispatcher dispatcher} and ends the
 * request cycle with an appropriate {@link net.fckeditor.response response}.
 * 
 * @version $Id: ConnectorServlet.java,v 1.1 2012/04/18 13:16:04 user4 Exp $
 */
public class ConnectorServlet extends HttpServlet {
	private static final long serialVersionUID = -5742008970929377161L;
	private final Logger logger = LoggerFactory.getLogger(ConnectorServlet.class);
	private transient Dispatcher dispatcher;

	/**
	 * Initializes this servlet. It initializes the dispatcher internally.
	 * 
	 * @throws ServletException
	 *             if an exception occurs that interrupts the servlet's normal
	 *             operation
	 */
	@Override
	public void init() throws ServletException {
		try {
			dispatcher = new Dispatcher(getServletContext());
		} catch (Exception e) {
			logger.error("Dispatcher could not be initialized", e);
			throw new ServletException(e);
		}
	}

	/**
	 * Passes a GET request to the dispatcher.
	 * 
	 * @throws IOException
	 *             if an input or output error is detected when the servlet
	 *             handles the GET request
	 * @throws ServletException
	 *             if the request for the GET could not be handled
	 */
	@Override
	protected void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/xml");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		GetResponse getResponse = null;

		try {
			ThreadLocalData.beginRequest(request);
			getResponse = dispatcher.doGet(request);
		} catch (Exception e) {
			throw new ServletException(e);
		} finally {
			/*
			 * call this method to prevent detached requests or else the request
			 * will probably never be garbage collected and will fill your
			 * memory
			 */
			ThreadLocalData.endRequest();
		}

		out.print(getResponse);
		out.flush();
		out.close();
	}

	/**
	 * Passes a POST request to the dispatcher.
	 * 
	 * @throws IOException
	 *             if an input or output error is detected when the servlet
	 *             handles the request
	 * @throws ServletException
	 *             if the request for the POST could not be handled
	 */
	@Override
	protected void doPost(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		System.out.println("ttttttttttttttttttttttttttttttttttttttttttttttttttttttt");
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		UploadResponse uploadResponse = null;

		try {
			ThreadLocalData.beginRequest(request);
			uploadResponse = dispatcher.doPost(request);
		} catch (Exception e) {
			throw new ServletException(e);
		} finally {
			/*
			 * call this method to prevent detached requests or else the request
			 * will probably never be garbage collected and will fill your
			 * memory
			 */
			ThreadLocalData.endRequest();
		}

		out.print(uploadResponse);
		out.flush();
		out.close();
	}

}

 
package net.b2c.u.interceptor;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;

public class StrutsAndFckFilter extends StrutsPrepareAndExecuteFilter {
	private String fckUrl="/fckeditor/editor/filemanager/connectors";
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest httpRequest=(HttpServletRequest)request;

		if(fckUrl.equals(httpRequest.getServletPath())){
			chain.doFilter(request, response);
		}else{
			 super.doFilter(request, response, chain);
		}

	}
}

fckeditor.properties
# default allowed extensions settings
connector.resourceType.file.extensions.allowed = 7z|aiff|asf|avi|bmp|csv|doc|fla|flv|gif|gz|gzip|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|ods|odt|pdf|png|ppt|pxd|qt|ram|rar|rm|rmi|rmvb|rtf|sdc|sitd|swf|sxc|sxw|tar|tgz|tif|tiff|txt|vsd|wav|wma|wmv|xls|xml|zip
connector.resourceType.image.extensions.allowed = bmp|gif|jpeg|jpg|png
connector.resourceType.flash.extensions.allowed = swf|fla
connector.resourceType.media.extensions.allowed = aiff|asf|avi|bmp|fla|flv|gif|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|png|qt|ram|rm|rmi|rmvb|swf|tif|tiff|wav|wma|wmv


# base URL path for the userfiles
connector.userFilesPath = /fckeditor_upfiles

# base system path on the backend for the userfiles
connector.userFilesAbsolutePath = /fckeditor_upfiles

# default resource type paths
connector.resourceType.file.path = /file
connector.resourceType.image.path = /image
connector.resourceType.flash.path = /flash
connector.resourceType.media.path = /media

# Due to security issues with Apache modules, it is recommended to leave this 
# setting enabled.
connector.forceSingleExtension = true

# Instructs the Connector to check, if the uploaded image is really one
connector.secureImageUploads = true

# directory of the editor relative to the context root
fckeditor.basePath = /fckeditor

# default height of the editor
fckeditor.height = 200

# default toolbar set of the editor
fckeditor.toolbarSet = Default

# default width of the editor
fckeditor.width = 100%

# default implementations
connector.impl = net.fckeditor.connector.impl.ContextConnector
connector.userActionImpl = net.fckeditor.requestcycle.impl.EnabledUserAction
connector.userPathBuilderImpl = net.fckeditor.requestcycle.impl.ContextPathBuilder
localization.localeResolverImpl = net.fckeditor.localization.impl.AcceptLanguageHeaderResolver