Не работает кодировка при передаче с View на Controler

Рейтинг: -1Ответов: 1Опубликовано: 25.08.2023

Есть вот такая форма

<form id="imageForm" method="post" th:action="@{/people}" th:object="${person}" accept-charset="UTF-8" >

        <label for ="name">Name</label>
        <input type="text" name="name" th:field="*{name}" id="name">

        <label for ="firstName">first Name</label>
        <input type="text" name="firstname" th:field="*{firstName}" id="firstName">

        <label for="age">Age</label>
        <input type="number" name = "age" th:field="*{age}" id="age">
        <br>
        <input type="hidden" name="imageBase64" th:field="*{imageBase64}" id="imageBase64">


        <button type="submit" id ="converterBut">Create</button>
    </form>

Если написать что нибуть на английском то всё хорошо если написать на русском то выходит кракозябра.Вот контролер который принемает данное дело

@PostMapping(produces = {"text/html; charset=utf-8"})
    public String createNewPerson(@ModelAttribute("person") Person person){
        this.personDAO.add(person);


        return "redirect:/people";
    }

И класс с конфигурацией

@Configuration
@ComponentScan("src")
@EnableWebMvc
@PropertySource(value = "classpath:config.properties")
public class SpringConfig implements WebMvcConfigurer {
    private final ApplicationContext ApplicationContext;
    @Autowired
    public SpringConfig(ApplicationContext applicationContext) {
        this.ApplicationContext = applicationContext;
    }
//    @Bean
//    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
//        PropertySourcesPlaceholderConfigurer configurator = new PropertySourcesPlaceholderConfigurer();
//        configurator.setLocation(new ClassPathResource("/config.properties", DbPersonDAO.class));
//        return configurator;
//    }

    @Bean
    public SpringResourceTemplateResolver templateResolver(){
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(this.ApplicationContext);
        templateResolver.setPrefix("/WEB-INF/views/");
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine(){
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setEnableSpringELCompiler(true);
        templateEngine.setTemplateResolver(templateResolver());
        return templateEngine;
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry){
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());

        resolver.setCharacterEncoding("UTF-8");
        registry.viewResolver(resolver);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/web-interface-res/**")
                .addResourceLocations("classpath:/web-interface-res/");

    }

}

Я так подозреваю я просто в класс конфигуратор не добавил что то. Смотрел в инете нечего не срабатывало:)

Ответы

▲ 0Принят

Спасибо за ответы :) пожалуй я отвечу сам. В любом html документе нужно добавить

<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>

А так же данный конфигурационный класс который реализует интерфейс:

@Configuration
public class MyWebFilterApplicationInitializer implements org.springframework.web.WebApplicationInitializer{

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);

        // Регистрируем фильтр
        FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("characterEncodingFilter", characterEncodingFilter);

        // Настраиваем URL-паттерн для фильтра
        filterRegistration.addMappingForUrlPatterns(null, true, "/*");
    }
}

После данных настроек появятся русские буквы.