摘要:[JAVA][Spring MVC] SpringMVC + ajax request and JSON respone Example
使用到的技術
Maven
Spring framework
jQuery
Jackson ( 將 Object 與 JSON 互轉的 Lib)
Maven pom.xml 設定如下
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.myweb</groupId>
<artifactId>index_page</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>index_page</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jackson.version>2.3.0</jackson.version>
<spring.version>3.2.5.RELEASE</spring.version>
<jdk.version>1.7</jdk.version>
<tomcat.version>2.1</tomcat.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>top_page</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>${tomcat.version}</version>
<configuration>
<url>http://localhost:8080/manager/text</url>
<server>my-tomcat</server>
<path>/tomcatManager</path>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
mvc-servlet.aml 設定如下
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.index.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="personService" class="com.index.service.impl.PersonServiceImpl" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="cacheSeconds" value="0" />
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
</list>
</property>
</bean>
</beans>
Spring中@ResponeBody 預設就是用Jackson作為message Converter
在bean的部份有人用
<mvc:annotation-driven />
就可以Mapping到Jackson
但一直失敗 在Http error code 都會顯示 406
表示respone content type 無法解析
爬文了之後 直接指定 messageConverters 解決。
Domain 如下 Person.java
public class Person {
private String idNo;
private String name;
private int age;
private String email;
public String getIdNo() {
return idNo;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Controller 如下
package com.index.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.springframework.web.servlet.ModelAndView;
import com.index.dto.Person;
import com.index.service.PersonService;
@Controller
@RequestMapping(value = "/person")
public class PersonController {
@Autowired
private PersonService personService;
@RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView addPerson() {
System.out.println("addperson");
ModelAndView modelAndView = new ModelAndView("/person/add_person");
modelAndView.addObject("person", new Person());
return modelAndView;
}
@RequestMapping(value = "/add/process", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
Person addingPerson(@RequestBody Person person) {
System.out.println("addperson process");
return person;
}
}
jsp 如下
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/json2/20130526/json2.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function madeAjaxCall() {
var name = $('#name').val();
var idNo = $('#idNo').val();
var json = {
"name" : $('#name').val(),
"idNo" : $('#idNo').val(),
"age" : $('#age').val(),
"email" : $('#email').val(),
};
$.ajax({
type : "post",
url : $("#newPersonForm").attr("action"),
cache : false,
data : JSON.stringify(json),
dataType : 'json',
contentType : "application/json",
success : function(response) {
$('#personFromResponse').html("");
$('#personFromResponse').html(
"Name:- " + response.name + "</br>idNo:- "
+ response.idNo + "</br>age:- "
+ response.age + "</br>email:- "
+ response.email);
},
error : function() {
alert('Error while request..');
}
});
}
</script>
<title>Add Person</title>
</head>
<body>
<center>
<h1>Add team page</h1>
<p>Here you can add a new team.</p>
<form:form id="newPersonForm" method="POST" modelAttribute="person"
action="${pageContext.request.contextPath}/person/add/process.htm">
<table>
<tbody>
<tr>
<td>Name:</td>
<td><form:input path="name"></form:input></td>
</tr>
<tr>
<td>ID:</td>
<td><form:input path="idNo"></form:input></td>
</tr>
<tr>
<td>AGE:</td>
<td><form:input path="age"></form:input></td>
</tr>
<tr>
<td>E-MAIL:</td>
<td><form:input path="email"></form:input></td>
</tr>
<tr>
<td><input type="button" value="add"
onclick="madeAjaxCall();"></td>
<td></td>
</tr>
</tbody>
</table>
</form:form>
<div id="personFromResponse"></div>
<p>
<a href="${pageContext.request.contextPath}/index.html">Home page</a>
</p>
</center>
</body>
</html>