Java框架之SpringMVC返回json串

使用注解@ResponseBody
需要导入Jackson2相关jar包:

Java框架之SpringMVC返回json串_第1张图片

接下来要在springmvc.xml配置相关转化解析类:



    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8value>
            list>
        property>
    bean>
    
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                
                <ref bean="mappingJacksonHttpMessageConverter" />
            list>
        property>
    bean>

写个例子index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首页title>
head>
<body>
    <li><a class="btn">点击a>li>

body>
<script type="text/javascript" src="js/jquery.min.js">script>
<script type="text/javascript">
$(".btn").click(function(){
    $.ajax({
        type:"post",
        dataType:"json",
        url:"book/check.do",
        success:function(data){
        alert(data.author);//弹出"张华"
        }
    });
    })
script>

html>

然后在控制器BookController.java中

@Controller
@RequestMapping("book")
public class BookController {
    @Autowired
    private  BookService book;//此处不能写成static,否则下面第21行会出现空指针异常
    @RequestMapping("check.do")
    @ResponseBody
    public BookInfo check(){
    ApplicationContext sc=new ClassPathXmlApplicationContext("application.xml");
BookInfo bookInfo = (BookInfo)sc.getBean("book");
bookinfo.setAuthor("张华");
return bookinfo;
    }

}

你可能感兴趣的:(JAVA)