Java Web(11) Spring MVC 返回Json

1. 首先是对Spring mvc 进行xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:annotation-config/>

    <mvc:annotation-driven />
</beans>

    其中annotation-driven是启动注解

2. 在maven 添加类

<properties>
    <jackson.version>2.7.3</jackson.version>
</properties>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>${jackson.version}</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>${jackson.version}</version>
</dependency>

3. 创建Controller 处理json请求

package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
@Controller
public class JsonUserExistsController {

    private Boolean flag ;
    private String message;
    @RequestMapping(value="json/test",
            produces = MediaType.APPLICATION_JSON_VALUE)
    public
    @ResponseBody Map<String,String>
    userchecking(@RequestParam Map<String,String> params,HttpSession session){
        Map<String,String> json = new HashMap<String,String>();
        String imageWord = params.get("imgcode");
        String session_word = (String) session.getAttribute("image_word");
        if(!session_word.equals(imageWord)){
            flag = false;
            message = "验证码错误";
            json.put("flag",flag.toString());
            json.put("message",message);
            return json;
        }
    }    
}

4. 结果

{"flag":"false","message":"验证码错误"}


 

你可能感兴趣的:(Java Web(11) Spring MVC 返回Json)