开发者

Set a locale for a war different from JVM's?

My tomcat6 is running in a JVM with locale en_US. I need to deploy several webapps & I want each webapp (packaged in war files) to have a different default locale. Is this pos开发者_运维问答sible ?


No. You can, however, set the Locale explicitly on each JSP-page. Store the locale in a session object or in a resource.

If you use sesison objects your users may have their own, individual locale which might be nice in an international setting.


(Caveat: I haven't done a lot of locale stuff in Java yet.)

You want to avoid doing this in the actual code of the JSPs or servlets if you possibly can. If there's no straight config way to do it (which seems surprising), I bet there's a nearly straight config way: You could do it with a filter.

Create your subclass of javax.servlet.Filter, install it in the web.xml of the relevant applications, and call setLocale on the ServletResponse in your doFilter implementation. Or something along those lines. Note that this doesn't prevent your doing specific things for specific users so they can have their own locales, if that's useful.

If you haven't done a filter before, they're dead easy (and very powerful). You just implement a three-method interface, two of which are usually just empty stubs unless you have resources you have to acquire and release, and the third (doFilter) which looks like this:

public void doFilter(
    ServletRequest request,
    ServletResponse response,
    FilterChain chain
    )
throws IOException, ServletException
{
    // Do your stuff here; so for instance:
    response.setLocale(...);

    // Chain to the next filter
    chain.doFilter(request, response);
}

And then the web.xml part just looks like this:

<filter>
    <filter-name>My Servlet Filter</filter-name>
    <filter-class>com.example.MyServletFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>My Servlet Filter</filter-name>
    <url-pattern>*.jsp</url-pattern>
</filter-mapping>

One of the cool things about filters is that you can insert a façade over the request or response if you need to (I don't think you do in this case, but who knows) via the ServletRequestWrapper and ServletResponseWrapper utility classes. These are base classes that just wrap a request or response instance and do pass-through to them. This means you can replace the request or response instance that gets passed to the next filter in the chain, with an instance of your own wrapper subclass that lets you override whatever request or response method you need to get involved in.

I've used filters (and wrappers) to do various things, they work a treat and are wonderful for app-specific, config-driven stuff.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜