0

struts 1.3 で作成された古い Web アプリケーションがあり、内部で多言語が機能する方法を変更する必要があります。現在、言語の変更を次のように処理するアクションがあります。

this.setLocale(request, new Locale("es", "", ""));
this.setLocale(request, new Locale("en", "", ""));
this.setLocale(request, new Locale("fr", "", ""));
this.setLocale(request, new Locale("pt", "", ""));
// this is and instance of org.apache.struts.action.Action

すべて正常に動作しますが、URL から言語を変更するhttp://www.example.com/en/index.do必要があります。つまり、ページを英語で表示しhttp://www.example.com/es/index.doスペイン語で表示する必要があります。

これをどのように実装できるか知っていますか?

URLを解析し、必要に応じて言語を変更してから続行するorg.apache.struts.action.ActionServlet(ActionServletを拡張することにより)の前にサーブレットを設定することを考えていましたsuper.doGet(request, response);が、残りのWebサイトのリンクにはURL の言語。http://www.example.com/index.do

----- 編集:別の回答 でこれに対する部分的な解決策を見つけました:

フィルタを作成して web.xml ファイルに追加しました

<filter>
    <filter-name>LangFilter</filter-name>
    <filter-class>com.company.struts.LanguageFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>LangFilter</filter-name>
    <servlet-name>action</servlet-name>
</filter-mapping>

javax.servlet.Filterクラス

public class LanguageFilter implements Filter {
[...]

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    String requestURI = request.getRequestURI();
    if (requestURI.indexOf("/context/en/") != -1) {
        String newURI = requestURI.replace("/context/en/", "/");
        req.getRequestDispatcher(newURI).forward(req, res);
    }
    else {
        chain.doFilter(req, res);
    }
}
}

しかし今、私はすべての html:form と html:link タグを変更する必要があります

<html:link action="/test2">Old link</html:link>

<a href="${pageContext.request.contextPath}/${sessionScope["org.apache.struts.action.LOCALE"]}/test2.do">New link</a>

これらの *.do URI を変更して言語パラメーターを追加できるように、生成された応答を傍受する方法はありますか??

ありがとう。

4

1 に答える 1

0

応答を送信する前にリンクを変更する解決策をついに思いつきました。これらは、他の誰かを助ける場合に備えて、私のクラスです。

これは私のフィルターです:

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts.Globals;

public class LanguageFilter implements Filter
{
    // ************************************************************************
    private Logger log = LogManager.getLogger(this.getClass());

    private FilterConfig filterConfig = null;

    // ************************************************************************
    public void init(FilterConfig filterConfig) throws ServletException
    {
        this.filterConfig = filterConfig;
    }

    // ************************************************************************
    public void destroy()
    {
    }

    // ************************************************************************
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
    {
        PrintWriter out = response.getWriter();
        GenericResponseWrapper wrapper = new GenericResponseWrapper((HttpServletResponse) response);
        HttpServletRequest hrequest = (HttpServletRequest) request;
        String servletPath = hrequest.getServletPath();

        String servletPathLowCase = servletPath.toLowerCase();

        String lang = "";
        String newURI = "/";
        if (servletPathLowCase.startsWith("/es/"))
        {
            lang = "es";
            newURI += servletPath.substring(4, servletPath.length());
        }
        else if (servletPathLowCase.startsWith("/en/"))
        {
            lang = "en";
            newURI += servletPath.substring(4, servletPath.length());
        }
        else if (servletPathLowCase.startsWith("/fr/"))
        {
            lang = "fr";
            newURI += servletPath.substring(4, servletPath.length());
        }
        else if (servletPathLowCase.startsWith("/pt/"))
        {
            lang = "pt";
            newURI += servletPath.substring(4, servletPath.length());
        }

        log.debug("language: '" + lang + "'; newURI: '" + newURI + "'");

        if (!"".equals(lang))
        {
            hrequest.getSession().setAttribute(Globals.LOCALE_KEY, new Locale(lang));
            request.getRequestDispatcher(newURI).forward(request, wrapper);
        }
        else
        {
            chain.doFilter(request, wrapper);
        }

        if (wrapper.getContentType().equals("text/html"))
        {
            String langStruts = hrequest.getSession().getAttribute(Globals.LOCALE_KEY).toString();
            // if ("".equals(langStruts))
            // langStruts = "es";
            String htmlResponseStruts = wrapper.toString();
            if ("".equals(lang))
            {
                // This URI is the requested URI for the section on the website where I have links to change language
                String uriForLanguages = servletPath + ("".equals(hrequest.getQueryString()) ? "" : "?" + hrequest.getQueryString());
                htmlResponseStruts = modifyStrutsLinks(htmlResponseStruts, langStruts, uriForLanguages);
            }

            // log.debug("htmlResponseStruts: " + htmlResponseStruts.toString());
            out.write(htmlResponseStruts);
        }
        else
            out.write(wrapper.toString());
        out.close();
    }

    // ************************************************************************
    private String modifyStrutsLinks(String htmlResponseStruts, String langStruts, String uriForLanguages)
    {
        String result = htmlResponseStruts;
        // REGEX: "([a-zA-Z0-9-_/])*\.do([a-zA-Z0-9-_?&=])*"
        // Regex explained from http://www.myregextester.com/index.php
        /**<code>
        ----------------------------------------------------------------------
          "                        '"'
        ----------------------------------------------------------------------
          (                        group and capture to \1 (0 or more times
                                   (matching the most amount possible)):
        ----------------------------------------------------------------------
            [a-zA-Z0-9-_/]           any character of: 'a' to 'z', 'A' to
                                     'Z', '0' to '9', '-', '_', '/'
        ----------------------------------------------------------------------
          )*                       end of \1 (NOTE: because you are using a
                                   quantifier on this capture, only the LAST
                                   repetition of the captured pattern will be
                                   stored in \1)
        ----------------------------------------------------------------------
          \.                       '.'
        ----------------------------------------------------------------------
          do                       'do'
        ----------------------------------------------------------------------
          (                        group and capture to \2 (0 or more times
                                   (matching the most amount possible)):
        ----------------------------------------------------------------------
            [a-zA-Z0-9-_?&=]         any character of: 'a' to 'z', 'A' to
                                     'Z', '0' to '9', '-', '_', '?', '&', '='
        ----------------------------------------------------------------------
          )*                       end of \2 (NOTE: because you are using a
                                   quantifier on this capture, only the LAST
                                   repetition of the captured pattern will be
                                   stored in \2)
        ----------------------------------------------------------------------
          "                        '"'
        ----------------------------------------------------------------------
        </code>*/
        Pattern pattern = Pattern.compile("\"([a-zA-Z0-9-_/])*\\.do([a-zA-Z0-9-_?&=])*\"");
        Matcher matcher = pattern.matcher(htmlResponseStruts);

        List<String> listMatches = new ArrayList<String>();

        while (matcher.find())
        {
            listMatches.add(matcher.group(0));
        }

        for (String sUrl : listMatches)
        {
            int lastSlash = sUrl.lastIndexOf("/");
            if (lastSlash == -1)
                lastSlash = 0;
            String replacement = sUrl.substring(0, lastSlash + 1) + langStruts + "/" + sUrl.substring(lastSlash + 1);
            // log.debug("modifyStrutsLinks: " + sUrl + " ->: " + replacement);
            result = result.replace(sUrl, replacement);
        }

        // Replaces links written this way on the JSP <a href="<%=request.getContextPath() %>/fr/ServletPathForReplacement"
        result = result.replace("/ServletPathForReplacement", uriForLanguages);
        return result;
    }

    // ************************************************************************
}

これらは他のクラス GenericResponseWrapper.java です。

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class GenericResponseWrapper extends HttpServletResponseWrapper
{
    private ByteArrayOutputStream output;

    private int contentLength;

    private String contentType;

    private ServletOutputStream outputStream;

    PrintWriter printWriter;

    public GenericResponseWrapper(HttpServletResponse response)
    {
        super(response);
        output = new ByteArrayOutputStream();
        outputStream = new FilterServletOutputStream(output);
        printWriter = new PrintWriter(outputStream, true); // true means auto-flush
    }

    public byte[] getData()
    {
        return output.toByteArray();
    }

    public ServletOutputStream getOutputStream() throws IOException
    {
        return outputStream;
    }

    public PrintWriter getWriter()
    {
        return printWriter;
    }

    public void setContentLength(int length)
    {
        this.contentLength = length;
        super.setContentLength(length);
    }

    public int getContentLength()
    {
        return contentLength;
    }

    public void setContentType(String type)
    {
        this.contentType = type;
        super.setContentType(type);
    }

    public String getContentType()
    {
        return contentType;
    }

    public String toString()
    {
        String salida = "";
        try
        {
            // To modify the encoding
            salida =  output.toString("ISO-8859-1");
        }
        catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return salida;
    }
}

そして FilterServletOutputStream.java

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;

public class FilterServletOutputStream extends ServletOutputStream
{
    public ByteArrayOutputStream output = null;

    public DataOutputStream stream;

    public FilterServletOutputStream()
    {
        output = new ByteArrayOutputStream();
        stream = new DataOutputStream(output);
    }

    public FilterServletOutputStream(ByteArrayOutputStream output)
    {
        this.output = output;
        stream = new DataOutputStream(output);
    }

    public void write(int b) throws IOException
    {
        stream.write(b);
    }

    public void write(byte b[]) throws IOException
    {
        stream.write(b);
    }

    public void write(byte buf[], int offset, int len) throws IOException
    {
        stream.write(buf, offset, len);
    }

    public void flush() throws IOException
    {
        stream.flush();
    }

    public void close() throws IOException
    {
        stream.close();
    }

    public ByteArrayOutputStream getBuffer()
    {
        return output;
    }

}
于 2013-10-31T13:08:38.573 に答える