0

I want to make a small website in Hindi language using Spring 4 MVC and MySql DB. When I tried to store hindi text into the Database,it saved like 'राà¤à¥à¤¶ मà¥à¤à¥à¤¶ सà¥à¤°à¥à¤¶' instead of 'राकेश मुकेश महेश'. How can I do this?

My project configuration and coding given below

public class AppConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setContentType("text/html;charset=UTF-8");
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        return messageSource;
    }

    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver resolver=new CommonsMultipartResolver();
        resolver.setDefaultEncoding("utf-8");
        return resolver;
    }

    @Bean
    public StringHttpMessageConverter stringHttpMessageConverter() {
        return new StringHttpMessageConverter(Charset.forName("UTF-8"));
    }

    public void addResourceHandlers(ResourceHandlerRegistry registry) {

          registry.addResourceHandler("/css/**")
            .addResourceLocations("/css/");
          registry.addResourceHandler("/images/**")
            .addResourceLocations("/images/");
          registry.addResourceHandler("/js/**")
            .addResourceLocations("/js/");
          registry.addResourceHandler("/uploadedContents/**")
            .addResourceLocations("/uploadedContents/");
          registry.addResourceHandler("/fonts/**")
            .addResourceLocations("/fonts/");
    }
}

public class SpringMVCWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

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

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

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

     @Override
        protected void registerDispatcherServlet(ServletContext servletContext) {
            String servletName = getServletName();
            Assert.hasLength(servletName, "getServletName() may not return empty or null");

            WebApplicationContext servletAppContext = createServletApplicationContext();
            Assert.notNull(servletAppContext,
                "createServletApplicationContext() did not return an application " +
                        "context for servlet [" + servletName + "]");

            DispatcherServlet dispatcherServlet = new DispatcherServlet(servletAppContext);

            // throw NoHandlerFoundException to Controller
            dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);

            ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);
            Assert.notNull(registration,
                "Failed to register servlet with name '" + servletName + "'." +
                        "Check if there is another servlet registered under the same name.");

            registration.setLoadOnStartup(1);
            registration.addMapping(getServletMappings());
            registration.setAsyncSupported(isAsyncSupported());

            Filter[] filters = getServletFilters();
            if (!ObjectUtils.isEmpty(filters)) {
                for (Filter filter : filters) {
                    registerServletFilter(servletContext, filter);
                }
            }

            customizeRegistration(registration);
        }

}

public class CardOperationController {

    @Autowired
    private CardService cardService;

    @RequestMapping(value = "addCard.html", method = RequestMethod.GET)
    public String getAddNewCardPage(Model model){
        model.addAttribute("card", new MarriageCard());
        return "AddNewCard";
    }

    @RequestMapping(value="addCard",method=RequestMethod.POST,produces = "text/plain;charset=UTF-8")
    public String addNewCard(@ModelAttribute("card")MarriageCard card,Model model,HttpServletRequest request){

        // method to persist card details..
        cardService.addNewCard(card);
        return "AddNewCard";
    }

}

AddCard.jsp

<head>
<title>Marriage-Card | Add new marriage card</title>
<!-- for-mobile-apps -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="#" />
<head>... </head>
<body>
    <section id="main_container" style="min-height: 1024px;">
        <div id="job_post_panel" class="panel panel-primary">
            <div class="panel-heading">नया निमंत्रण कार्ड बनायें ...</div>
            <form:form action="addCard" method="post" commandName="card" id="job_post"
                name="job_post">
                <table class="input-container">
                    <tbody>
                        <tr>
                            <td class="column-name"><form:label path="marriageVanue"> स्‍थान</form:label>
                            <td class="input-text"><form:input path="marriageVanue"
                                    class="text" placeholder="स्‍थान भरें ..." />
                        </tr>
                        <tr>
                            <td class="column-name"><form:label path="darshanAbhilashi"> दर्शनाभिलाषी</form:label>
                            <td class="input-text"><form:input type="text" class="text"
                                    path="darshanAbhilashi" placeholder="दर्शनाभिलाषी  भरें ..." />
                        </tr>
                        <tr>
                            <td class="column-name"><form:label path="swagatUtsuk">स्‍वागतोत्‍सुक</form:label>
                            <td class="input-text"><form:input type="text" class="text"
                                path="swagatUtsuk" placeholder="स्‍वागतोत्‍सुक के नाम भरें ..." />
                        </tr>
                        <tr>
                            <td class="column-name"><form:label path="vinit">विनीत</form:label>
                            <td class="input-text"><form:input type="text" class="text"
                                path="vinit" placeholder="विनीत  के नाम भरें ..." />
                        </tr>

                        <tr>
                            <td class="btn-row" colspan="2"><input class="btn-submit"
                                type="submit" value="Submit" /></td>
                        </tr>
                    </tbody>

                </table>
            </form:form>

        </div>

        </section>
</body>
<html>

Input Data :

enter image description here

Data Stored in Database

enter image description here

Draken
  • 3,134
  • 13
  • 34
  • 54
  • How are you viewing the data stored in the database? What program? Does it have an encoding option? – Josh Lee May 15 '17 at 19:05
  • In other words: Based on this question it appears that you are correctly storing UTF-8 data in the database, so there is no problem. But you need to fix your database client to see it properly. – Josh Lee May 15 '17 at 19:10
  • I am using MySQL Workbench 5.2 to view stored data and i have selected "utf8_general_ci" encoding option for database. – Santosh Kumar May 16 '17 at 05:04
  • Hey if i am using RequestMethod.GET then it works fine but with POST method doesn't works, how can I solve this? – Santosh Kumar May 16 '17 at 06:27
  • Finally i got the solution, the problem was regarding tomcat server configuration. I have edited Server>tomcat v8.x> web.xml using this link http://stackoverflow.com/questions/7566857/setting-java-environment-apache-tomcat-to-encode-utf-8 – Santosh Kumar May 16 '17 at 07:41

1 Answers1

0

Add a Servlet filter to specify a character encoding for requests. This might be your problem?

e.g.

    <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <async-supported>true</async-supported>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>   

In your AnnotationDispatcher class you can register filters (instead of using web.xml)

@Override
protected Filter[] getServletFilters() {
    CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
    ... set prepare filter, e.g. setting encoding

    return new Filter[]{encodingFilter};
 }
  • Yes it's working Thanks @Tim Mickelson but is there any alternatives solution without xml coding? – Santosh Kumar May 18 '17 at 04:52
  • I updated my answer with an example how you could register the filter in your Java @Configuration. I have not tested it, but you should follow that direction. – Tim Mickelson May 18 '17 at 06:53