本篇文章写给刚接触SpingMVC的同道中人,虽然笔者本身水平也不高,但聊胜于无吧,希望可以给某些人带来帮助
笔者同时再次说明,运行本例时,需注意一些配置文件和网页脚本的路径,因为笔者的文件路径与读者的未必相同
首先准备以下 jar包:
commons-logging-1.1.3.jar
jackson-core-asl-1.9.2.jar
jackson-mapper-asl-1.9.2.jar
spring-aop-4.0.6.RELEASE.jar
spring-beans-4.0.6.RELEASE.jar
spring-context-4.0.6.RELEASE.jar
spring-core-4.0.6.RELEASE.jar
spring-expression-4.0.6.RELEASE.jar
spring-web-4.0.6.RELEASE.jar
spring-webmvc-4.0.6.RELEASE.jar
其中commons-logging-1.1.3.jar,jackson-core-asl-1.9.2.jar,jackson-mapper-asl-1.9.2.jar均可在struts2的工具包中取得
导入以上包后,去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>web</display-name> <!-- 配置springMVC请求分配Servlet --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- <!-- 声明配置文件存放位置和配置文件的名称,加入不配置此标签,springMVC的配置文件名称默认为<servlet-name>的值加上"-servlet.xml",例如本例便是springMVC-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/*-servlet.xml</param-value> </init-param> --> <!-- 值小于1时,表示容器启动时并不加载此servlet,此时只有当第一次使用servlet时才会加载,但当值大于等于1时,表示容器启动时会立即加载此servlet,此时值越大表示加载的优先级越小 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <!-- 请求链接以do结尾,具体怎么回事请耐心继续往下看 --> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
接下来我们再看springMVC-servlet.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"> <!-- 扫描指定包下的所有类,倘若发现@Component,@Controller,@Service,@Repsitory等注解,则将相应的类实例化 --> <context:component-scan base-package="org.xt.controller"/> <!-- 配置视图资源 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 此乃视图资源的前缀 --> <property name="prefix" value="/WEB-INF/page"/> <!-- 此乃视图资源的后缀 --> <property name="suffix" value=".jsp"/> </bean> <!-- 此处乃进行json数据传输的关键,当配置 --> <bean id="jsonMapping" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jsonMapping"/> </list> </property> </bean> </beans>
接下来我们再看vo对象即值对象User.java,如下:
package org.xt.pojo; import java.io.Serializable; @SuppressWarnings("serial") public class User implements Serializable { private long userId; private String userName; private String userPassword; public long getUserId() { return this.userId; } public void setUserId(long userId) { this.userId = userId; } public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return this.userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } }
好接下来便轮到了Controller的类TestJSONController.java,如下:
package org.xt.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.xt.pojo.User; @Controller @RequestMapping("/test") public class TestJSONController { /* *看value属性,是以do结尾的,这正是web.xml配置url-pattern的值为*.do的原因, *这样所有的请求链接都必须以.do结尾,这样做的好处在于可以将请求链接同其他链接区分开来. *笔者建议如此做(当然了,你也可以将.do换成.html,.htm或者其他) */ @RequestMapping(value = "/testJSON.do",method={RequestMethod.POST}) @ResponseBody public User testJSON(@RequestBody User user) { System.out.println(user.getUserName() + " " + user.getUserPassword()); return user; } }
在以上类中出现的@ResponseBody和@RequestBody是关键,前者用于将JSON数据返回客户端,后者用于接受客户端的JSON数据
接下来我们来看看客户端的代码,客户端的代码由jquery完成
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>TestJSONForSpringMVC</title> </head> <body> 用户名: <input id="userName" type="text" style="width:150px" /> <br /> <br /> 密 码: <input id="userPassword" type="password" style="width:150px" /> <br /> <br /> <input id="login" type="button" value="登录" /> <!-- 注意了,此处jquery的路径记得替换成你自己jquery所在的路径 --> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $("#login").click(function() { $.ajax({ url : "test/testJSON.do", type : "POST", dataType : "json", contentType : "application/json;charset=UTF-8", data : JSON.stringify({ userId : "1", userName : $("#userName").val(), userPassword : $("#userPassword").val() }), success : function(result) { alert(JSON.stringify(result)); }, error:function(result){ alert("Sorry,you are make a error!"); } }); }); </script> </body> </html>
以上jsp文件中出现了一个JSON.stringify()函数,此函数由jquery提供,作用在于将JSON数据转换为字符串,之所以要这么做,原因在于服务端的@RequestBody只能识别字符串,而不能识别JSON对象
--写于2014-09-10 夜