Springmvc中ajax与jason应用

相关依赖包

json数据转换的jar包

jackson-annotations-2.5.4

jackson-core-2.5.4

jackson-databind-2.5.4

spring以及spring的依赖包

bean context aop context core web webmvc expression

未涉及json的ajax请求

简单的表单验证

Controller层java代码

@Controller
public class AjaxCtrl {
@RequestMapping("/toAjax.do")
public String toAjax() {
return "ajax";
}
@RequestMapping("/ajax.do")
@ResponseBody
public void ajaxJson(@RequestParam("name")String name,HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
if(name.equals("hm"))
out.print("该用户已注册");
else
out.print("该用户可使用");
}

注意点:

  • 在手动调用getWriter()方法时不可以再添加返回值,否则tomcat会报错(getWriter()方法已存在)。因为在返回值处容器会自动调用getWriter()方法来输出内容,而检测到前面getWriter()已经被调用过,产生冲突。
  • 解决:1. 像上面的代码不给出返回值;2. resp.reset(); resp.setContentType("text/html; charset=utf-8"); out.flush; out.close();
  • @ResponseBody会将返回的数据自动转换为json格式的数据

相关jsp代码:ajax.jsp

<script src="${pageContext.request.contextPath }/js/jquery-2.1.0.min.js" type="text/javascript"></script>
</head>
<body>
姓名:<input type="text" id="field" name="name" /><span id="txt"></span>
<script type="text/javascript">
$("#field").blur(function(){
$.post("ajax.do",{'name':$('#field').val()},function(result){
$("#txt").html(result);
});
});
</script>
</body>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>springmvc_ajax</display-name>
<filter>
<filter-name>characterencoding</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterencoding</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>ajax</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ajax</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

涉及json格式数据的ajax请求

Controller层java代码

@RequestMapping("/toAjaxJson.do")
public String toAjaxJson() {
return "ajaxJson";
}
@RequestMapping("/ajaxJson.do")
@ResponseBody
public List<User> ajaxJson() {
List<User> list = new ArrayList<User>();
list.add(new User(1, "xb", "123"));
list.add(new User(2, "xc", "234"));
list.add(new User(3, "xd", "345"));
list.add(new User(4, "xa", "456"));
return list;
}

相关jsp代码:ajaxJson.jsp

<input type="button" id="btn" value="获取json数据">
<table width="80%" align="center">
<tr>
<th>编号</th>
<th>姓名</th>
<th>密码</th>
</tr>
<tbody id="content"></tbody>
</table>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
$.get("ajaxJson.do",function(list){
var field = "";
for (var i = 0; i < list.length; i++) {
field +="<tr><td>"+list[i].id+"</td>"+"<td>"+list[i].name+"</td>"+"<td>"+list[i].passwd+"</td></tr>";
}
$("#content").html(field);
});
});
});
</script>

springmvc的核心配置文件: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-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- 开启mvc的注解 -->
<mvc:annotation-driven />
<!-- 扫描包 -->
<context:component-scan base-package="com.zrm.controller"></context:component-scan>
<!-- 配置视图解析器 -->
<bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<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. "></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringConverter"/>
<ref bean="jsonConverter"/>
</list>
</property>
</bean>
</beans>

相关类的介绍

StringHttpMessageConverter

官方文档:

An HttpMessageConverter implementation that can read and write Strings from the HTTP request and response. By default, this converter supports all text media types (text/*), and writes with a Content-Type of text/plain.

译文:

一种HttpMessageConverter可以从HTTP请求和响应中读取和写入字符串的实现。默认情况下,此转换器支持所有文字媒体类型(text/*),并用Content-Type中的text/plain类型。

MappingJackson2HttpMessageConverter

官方文档:

An HttpMessageConverter implementation that can read and write JSON using Jackson’s ObjectMapper. JSON mapping can be customized as needed through the use of Jackson’s provided annotations. When further control is needed, a custom ObjectMapper can be injected through the ObjectMapper property for cases where custom JSON serializers/deserializers need to be provided for specific types. By default this converter supports ( application/json).

译文:

一个HttpMessageConverter可以使用Jackson库提供的ObjectMapper类来读取和写入json格式的数据。可以根据需要通过使用Jackson库提供的注解来自定义XML映射。当需要进一步控制时,XmlMapper 可以通过ObjectMapper属性注入自定义,以用于需要为特定类型提供自定义XML序列化器/反序列化器的情况。默认情况下,此转换器支持(application/xml)。

ObjectMapper是Jackson库的主要类,他提供的一些功能用于将Java对象转换为符合jason结构的字符串。

AnnotationMethodHandlerAdapter

注入了AnnotationMethodHandlerAdapter作用是对有RequestMapping注解的控制器进行HTTP路径、HTTP方法和请求参数解析.

项目结构

项目源码已上传至 github ajaxJson

最新文章

  1. python IOError: [Errno 0] Error
  2. set[c++]
  3. 长按事件jquery mobile
  4. [转]关于event的两个常被忽略的api:isDefaultPrevented()和preventDefault()
  5. Codeforces Round #383 (Div. 2) 题解【ABCDE】
  6. 转载:关于Matlab GUI的一些经验总结
  7. 使用jQuery基本过滤选择器
  8. Windows phone(1)-ApplicationBar(应用栏)
  9. JS模板Handlebars的使用和有效组织
  10. MQTT之 Mosquitto hello world的使用
  11. 完整的yuicompressor单个压缩和批量压缩以及gzip再次压缩,拦截器的配置等
  12. 演练5-4:Contoso大学校园管理系统4
  13. 关于java中的事件类型
  14. 使用canvas进行图片裁剪简单功能
  15. IT科技企业逻辑思维面试题
  16. Python机器学习中文版
  17. MacBook PyCharm激活码(附视频)
  18. kubernetes 开发 code-generator
  19. Django系列之web应用与http协议
  20. php向数据库插入数据

热门文章

  1. IntelliJ IDEA中出现could not auto wired错误提示处理方式
  2. Unique Paths I,II
  3. Fragment嵌套
  4. c++ valarray 实现矩阵与向量相乘
  5. Python入门 五、学着机器思考
  6. 14招搞定JavaScript调试
  7. Django之ORM的增删改查操作流程
  8. POJ 1523 Tarjan求割点
  9. (转)Vue 爬坑之路(一)—— 使用 vue-cli 搭建项目
  10. ie8及其以下版本兼容性问题之圆角