为Servlet添加UTF8过滤器

时间:2015-08-25 17:43:26

标签: java spring servlets servlet-filters spring-java-config

您好我使用了Initializer,效果很好。

public class Initializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext)
            throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebAppConfig.class);
        servletContext.addListener(new ContextLoaderListener(ctx));

        ctx.setServletContext(servletContext);


        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);

        FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("encodingFilter",
                new CharacterEncodingFilter());
        filterRegistration.setInitParameter("encoding", "UTF-8");
        filterRegistration.setInitParameter("forceEncoding", "true");
        filterRegistration.addMappingForUrlPatterns(null,true,"/*");
    }

然后我把它改成了另一个:

public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {


    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{WebAppConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{WebAppConfig.class};
    }
}

但是我无法添加这种方法:

public void onStartup(ServletContext servletContext) {
        FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("encodingFilter",
                new CharacterEncodingFilter());
        filterRegistration.setInitParameter("encoding", "UTF-8");
        filterRegistration.setInitParameter("forceEncoding", "true");
        filterRegistration.addMappingForUrlPatterns(null, true, "/*");
    }

因为申请失败了。 我究竟做错了什么?如何将此过滤器添加到新的初始化程序以强制它工作? 谢谢。

1 个答案:

答案 0 :(得分:0)

<% @question.sub_questions.each_with_index do |q, index| %>
   <%= f.fields_for @answer.sub_answers.build  do |s| %>
     <p><strong>Q <%= @question.question_index %>.<%= index+1 %></strong></p>
     <p><strong><%= q[1]['question'] %></strong></p>
     <% if q[1]['form_fields']['boolean_field'] %>
       <div class="field">
         <div style="display:flex;">
           <%= s.label 'Yes or No' %>
           <%= s.check_box :answer_boolean, {}, true, false %> <br />
         </div>
       </div>
     <% end %>
     <% if q[1]['form_fields']['text_field'] %>
       <div class="field">
         <%= s.text_area :answer_text %> <br />
       </div>
     <% end %>
   <% end %>
  <% end %>