Spring 之 注解实现返回json

下面的部分位于Spring-mvc.xml或者dispatcherServlet-servlet.xml中 (Spring 3.0中ServletName-servlet.xml替代了Spring-mvc.xml)

<!-- 用于将对象转换为 JSON  -->  
    <bean id="stringConverter"  
        class="org.springframework.http.converter.StringHttpMessageConverter">  
        <property name="supportedMediaTypes">  
            <list>  
                <value>text/plain;charset=UTF-8</value>  
            </list>
        </property>
    </bean>  
    <bean id="jsonConverter"  
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>  
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">  
        <property name="messageConverters">  
            <list>  
                <ref bean="stringConverter" />
                <ref bean="jsonConverter" />  
            </list>  
        </property>  
    </bean>  

在对应的Controller中

@RequestMapping(value="/login",method=RequestMethod.POST)
    public @ResponseBody User login(String username,String password){
        User user = userService.login(username, password);
        return user;
    }

这里我使用的jackson包:

      (1)jackson-core 2.5.0

      (2)jackson-databind 2.5.0

      (3)jackson-annotations 2.5.0

导入后build path;

       警告:若用hibernate等orm工具生成的pojo类,一对一,对多等关系可能会输出无限循环的json:

需要使用在pojo类中导入com.fasterxml.jackson.annotation.JsonIgnore,并为需要屏蔽的类添加@JsonIgnore注解,这样被注解的属性就不会出现在json中了。

 

第二种示例

@ResponseBody  
    @RequestMapping(value = "/login")  
    public ModelAndView ajaxLogin(Model model,User user,HttpServletRequest request, HttpSession session){  
        String errorMessage=loginCommon(model, user, request, session);  
        Map map=new HashMap();  
        if(ValueWidget.isNullOrEmpty(errorMessage)){  
            map.put(Constant2.AJAX_LOGIN_RESULT, "success");  
        }else{  
            map.put(Constant2.AJAX_LOGIN_RESULT, "failed");  
        }  
        map.put("error", errorMessage);  
        model.addAttribute("user", null);  
        return new ModelAndView(new MappingJacksonJsonView(),map);  
    }  

或者 

            model.addAttribute("user", user1);  

运行结果:

posted @ 2016-09-13 15:41  JokerJason  阅读(5870)  评论(0编辑  收藏  举报

It's not who you are underneath, it's what you do that defines you

Brick walls are there for a reason :they let us prove how badly we want things