springmvc(8)ajax&json处理
1.使用HttpServletResponse处理,不需要配置解析器
@Controller public class AjaxController { @RequestMapping("ajax.do") public void ajax(String name, HttpServletResponse response) throws IOException { if (name.equals("zh")){ response.getWriter().println("true"); }else{ response.getWriter().println("false"); } } }
jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> <script type="text/javascript" src="js/jquery-3.4.1.min.js"></script> <script> $(function () { $("input[name='name']").blur(function () { $.ajax({ url:"ajax.do", data:{name:$("input[name='name']").val()}, success:function (data) { alert(data); } }) }) }) </script> </head> <body> <input type="text" name="name" value=""> </body> </html>
当打开jsp页面时,系统会请求js文件,如果说你的dispatcherServler拦截的是“/”,而你有没有对静态资源做其他配置,此时请求js文件的请求也会被拦截,那么就会找不到js文件,解决办法是要么你别拦截所有请求,要么你对静态资源的访问做其他配置。
2.springmvc处理json
a)导入jar包:
jackson-annotations-2.9.9.jar
jackson-core-2.9.9.jar
jackson-databind-2.9.9.jar
b)配置json类型转换器:
<!--用于将对象转换为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.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="stringConverter"></ref> <ref bean="jsonConverter"></ref> </list> </property> </bean>
c)controller代码:
@RequestMapping("json.do") @ResponseBody public List<User> json(String name, HttpServletResponse response) throws IOException { List<User> list = new ArrayList<>(); list.add(new User("张三","123")); list.add(new User("李四","456")); return list; }