ajax请求springmvc与mvc:annotation-driven

本文介绍了解决前端Ajax请求与后端SpringMVC交互时遇到的问题,包括返回数据无法正确解析为JSON及中文乱码现象。通过使用@ResponseBody注解及自定义StringHttpMessageConverter来解决这些问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  昨天遇到两个问题有必要在此做个记录。逻辑是在页面发送ajax请求到spring mvc controller里,该ajax如下:
function buyHouse(houseId) {
    houseId = houseId.attr("value");
    $.ajax({

         type : 'post',

         url : "buyHouse.do",

         dataType : 'JSON',

         data : {
             houseId : houseId
         },

         success : function(data) {
            if(data.isSuccess) {
                alert('购买成功');
                window.location.reload();
            } else {
                alert(data.errorMsg);
            }
        } ,
         error : function() {  
             var rt = window.confirm("返回数据异常");
                if(rt) {
                    window.location.reload();
                } 
            } 

    });
}

对应的controller如下:

@RequestMapping("buyHouse.do")
    public String buyHouse(@RequestParam("houseId") Long houseId, HttpSession sesson) {
        User user = (User) sesson.getAttribute("currentUser");
        Result result = new Result();
        if(user == null) {
            // this code block is not execute generally..
            /*sesson.setAttribute("errorMsg", "当前用户失效");
            return "error";*/
            result.setSuccess(false);
            result.setErrorMsg("current user passed.please login agian");
        } else {
            result = houseManager.buyHouseById(houseId, user.getUserId());
        }
        return parseResultToJson(result);
    }

但是返回的js里总是只执行error而不执行success。后来我检查发现是返回的数据无法解析为json。jq版本更新后对于json的格式要求十分严格,我debug确认返回的数据的格式满足严格的json格式,后来同事提醒我用@ResponseBody注解,这个注解就是返回方法的数据而直接跳过视图解析。,我猜测是spring自动封装成一个对象,默认的视图是该方法名,加入这个注解后返回数据正常了,是个json。

第二个问题是json如果是中文,则会显示????乱码,这肯定是编码问题,上次存入数据库是乱码的原因是数据库编码或则是传输url编码问题,这次从后端返回的数据乱码是从controller到js时候出了问题。这应该是框架的问题,所以我一直在想我的过滤器是否正常工作,然后知道了注解mvc:annotation-driven,该注解会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean。
AnnotationMethodHandlerAdapter会默认使用如下:
ByteArrayHttpMessageConverter

StringHttpMessageConverter

ResourceHttpMessageConverter

SourceHttpMessageConverter

XmlAwareFormHttpMessageConverter

Jaxb2RootElementHttpMessageConverter

MappingJacksonHttpMessageConverter

然后我再自己定义了StringHttpMessageConverter,应该就是会过滤所有String类型:

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">  
        <property name="messageConverters">
            <list>  
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">  
                    <property name="supportedMediaTypes">  
                        <list>  
                            <value>text/html;charset=UTF-8</value> 
                        </list>  
                    </property>  
                </bean>  
            </list>  
        </property>  
    </bean> 

加入该配置之后,controller返回到js里的中文数据正常显示了。

实验十二 SpringMVC 一、实验目的 1、掌握SpringMVC项目构建 2、掌握SpringMVC数据接收传递的原理 二、实验过程 1、配置SpringMVC开发环境 a)创建新的项目,TestSpringMvc b)为项目添加Web框架SpringMVC框架 c)添加classes目录 d)添加javaee依赖 e)添加lib输出配置 将依赖文件添加至lib中 f)修改web.xml配置 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.form</url-pattern> </servlet-mapping> <filter> <filter-name>charactorEncoding</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>charactorEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> g)修改applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <context:annotation-config></context:annotation-config> <context:component-scan base-package="cs18.controller"/> </beans> h)添加controller,TestController.java @Controller public class TestController { @RequestMapping(value = "/showName") public String showName(HttpServletRequest request, HttpServletResponse response) { //访问传递的参数 ; return "index.jsp"; } } i)配置tomcat,添加项目部署 j)启动tomcat,在浏览器中输入以下地址 http://localhost:8080/TestSpringMvc/showName?name=fredy 2、测试以下不同类型数据绑定方法 a)HttpServletRequet,HttpSession,Model/ModelMap b)简单数据类型绑定(int,String等) c)POJO数据绑定 d)包装POJO数据绑定 e)自定义数据类型绑定 f)数组或集合绑定 g)使用Json风格类型的数据绑定
06-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值