SpringMVC中文乱码问题解决

一、数据库连接

 

    public static Connection getConnect() throws ClassNotFoundException, SQLException{
        Class.forName("net.sf.log4jdbc.DriverSpy");
        Connection conn = DriverManager.getConnection("jdbc:log4jdbc:mysql://127.0.0.1:3306/mydata?characterEncoding=utf8", "root", "950909");
        return conn;
    }

 

二、controller返回json数据

    @RequestMapping(value="/listHeroJson", produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String listHeroJson() throws ClassNotFoundException, SQLException, JsonGenerationException, JsonMappingException, IOException{
        PreparedStatement ps = DbUtil.getConnect().prepareStatement("select id, name, damage, hp, imgsrc from hero");
        ResultSet rs = ps.executeQuery();
        List<Hero> heroList = new ArrayList<Hero>();
        while(rs.next()){
            Hero hero = new Hero();
            hero.setId(rs.getInt(1));
            hero.setname(rs.getString(2));
            hero.setDamage(rs.getInt(3));
            hero.setHp(rs.getInt(4));
            hero.setImgsrc(rs.getString(5));
            heroList.add(hero);
            System.out.println("heroname:" + rs.getString(2));
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data", heroList);
        ObjectMapper om = new ObjectMapper();
        String jsonString = om.writeValueAsString(map);
        return jsonString;
    }

二、页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isELIgnored="false"%>

 

posted @ 2017-10-10 11:57  Junsept  阅读(720)  评论(0编辑  收藏  举报