我有一个用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
一切正常,但现在我需要更改网址中的语言,即http://www.example.com/en/index.do
应该以英文显示页面,http://www.example.com/es/index.do
会这样做所以在西班牙语。
你知道我该怎么做呢?
我一直在考虑在org.apache.struts.action.ActionServlet(通过扩展ActionServlet)之前设置一个servlet来解析URL,必要时更改语言,然后继续super.doGet(request, response);
但其余的该网站的链接将不包含URL中的语言。 http://www.example.com/index.do
-----编辑: 我在another answer中找到了部分解决方案:
我已经创建了一个过滤器并将其添加到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并添加语言参数??
感谢。
答案 0 :(得分: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;
}
}