(Spring + JSP + jQuery-AJAX + JSON ) setting environment for UTF-8 issue?

前端 未结 3 1857
盖世英雄少女心
盖世英雄少女心 2021-02-20 14:21

I am doing a chat project in java with Spring 3.x which needs Multi-language support.

Here is what I have done.

3条回答
  •  忘了有多久
    2021-02-20 14:38

    I have tried your javascript with this test controller:

    @Controller
    public class TestController {
        @RequestMapping(value = "/test", method = POST, produces = "application/json; charset=utf-8")
        public @ResponseBody
        ResponseEntity sendMessage(HttpSession session, @RequestParam String intxnId, @RequestParam String message, HttpServletRequest request, HttpServletResponse response) {
    
            System.out.println("Send Message UTF-8 ----------------- " + message);
    
            String json = null;
            HashMap result = new HashMap();
            result.put("name", "test");
            result.put("message", message);
            result.put("time", "time");
            ObjectMapper map = new ObjectMapper();
            if (!result.isEmpty()) {
                try {
                    json = map.writeValueAsString(result);
                    System.out.println("Send Message  :::::::: : " + json);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            HttpHeaders responseHeaders = new HttpHeaders(); 
            responseHeaders.add("Content-Type", "application/json; charset=utf-8"); 
            return new ResponseEntity(json, responseHeaders, HttpStatus.CREATED);
        }
    }
    

    It works like a charm, and I see UTF-8 characters from the response in the alert popup, using chrome browser.

    My test.jsp:

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%request.setCharacterEncoding("UTF-8");%>
    
    
    
    
        
            
        
        
            

    Test

提交回复
热议问题