javajspstruts2servlet-filters

How to change charset in struts2 to utf-8


Hi I have testfield in which I want to put test not in English(for example into Russian) but in my action class I get instead of text only ?????????. I trying to write simple filter which described Parameters charset conversion in struts2

but it still do not work.. can somebody help me

update I have this enter image description here

<s:textfield key="index.login" name="login" />

I want to put into it test in Russian language and then send it to my action.but in my action class I get instead of text only ?????????.to fix this problem I need to change charset into utf8 instead of win1251.


Solution

  • Create a 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;
    
    public class CharacterEncodingFilter implements Filter {
    
        @Override
        public void init(FilterConfig filterConfig)
                throws ServletException {
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
                throws IOException, ServletException {
            servletRequest.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("text/html; charset=UTF-8");
            filterChain.doFilter(servletRequest, servletResponse);
        }
    
        @Override
        public void destroy() {
    
        }
    }
    

    Declare it into your web.xml:

    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>your.package.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    

    And your're good to go. Also make sure that your every JSP page contains: <%@ page contentType="text/html;charset=UTF-8" language="java" %>. If your application is running on tomcat, make sure your add URIEncoding="UTF-8" attribute to your Connector element.