SpringMvc与json交互以及restful风格

SpringMvc与json交互以及restful风格

1.导入jar包
2.在wen.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>chapter14</display-name>
  <welcome-file-list>
       <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <!-- 配置Spring MVC前端控制器 DispatcherServlet -->
  <servlet>
       <servlet-name>springmvc</servlet-name>
       <servlet-class>
           org.springframework.web.servlet.DispatcherServlet
       </servlet-class>
       <!-- 配置Spring MVC加载配置文件路径 -->
       <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:springmvc-config.xml</param-value>
       </init-param>
       <!-- 配置服务器启动后立即加载Spring MVC配置文件 -->
       <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
       <servlet-name>springmvc</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>
   
   
</web-app>

3.在src下创建spingmvc配置文件springmvc-config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
  http://www.springframework.org/schema/mvc 
  http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	<!-- 定义组件扫描器,指定需要扫描的包 -->
	<context:component-scan base-package="controller" />
	<!-- 配置注解驱动 -->
	<mvc:annotation-driven />
	
	<!--配置静态资源的访问映射,此配置中的文件,将不被前端控制器拦截 -->
	<mvc:resources location="/js/" mapping="/js/**" />
	<!-- <mvc:default-servlet-handler /> -->
	
	<!-- 配置视图解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>

4.创建po包,并创建User类
package po;

public class User {

	private String username;
	private String password;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + "]";
	}
	
	
}

5.创建controller包,并创建UserController类
package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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 po.Result;
import po.User;

@Controller
public class UserController {
	
	@RequestMapping("/testJson")
	@ResponseBody
	public String testJson(@RequestBody User user) {
		System.out.println(user);
		Result result = new Result(0,"获取成功",user);
		return result.toJSON();
	}
	
	
	@RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
	@ResponseBody
	public String selectUser(@PathVariable("id") String id) {
		System.out.println(id);
		User user = new User();
		if(id.equals("1234")) {
			user.setUsername("tom");
		}
		Result result = new Result(0,"查询成功",user);
		return result.toJSON();
	}

}

第二种是restfui风格

6.测试,index.jsp相关代码
$.ajax({
		url : "${pageContext.request.contextPath }/testJson",
		type : "post", 
		// data表示发送的数据
		data :JSON.stringify({username:username,password:password}),
		// 定义发送请求的数据格式为JSON字符串
		contentType : "application/json;charset=UTF-8",
		//定义回调响应的数据格式为JSON字符串,该属性可以省略
		dataType : "json",
		//成功响应的结果
		success : function(data){
			if(data != null){					
			  alert("您输入的用户名为:"+data.data.username+
                                 "密码为:"+data.data.password);
			}
			console.log(data)
		}
	});

第二种

	var id = $("#number").val();
	$.ajax({
		url : "${pageContext.request.contextPath }/user/"+id,
		type : "GET", 
		//定义回调响应的数据格式为JSON字符串,该属性可以省略
		dataType : "json",
		//成功响应的结果
		success : function(data){
			if(data.data.username != null){	
			    alert("您查询的用户是:"+data.data.username);
			}else{
			    alert("没有找到id为:"+id+"的用户!");
			}
			console.log(data)
		}
	});

你可能感兴趣的:(java,java,spring,json,ajax)