1. 程式人生 > >SpringMVC如何實現restful介面

SpringMVC如何實現restful介面

 今天看一個SpringMVC的專案,然後編寫介面,並通過前臺的ajax呼叫來訪問介面,當然這所有的一切好像都沒有什麼問題,你看下面是我們的ajax,

    function sendMessage() {
        var curPath=window.document.location.href;  
        var pathName=window.document.location.pathname;  
        var pos=curPath.indexOf(pathName);  
        var localhostPaht=curPath.substring(0,pos);  
        var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1); 
        var params={
        		"name":"wangdneggao"
        }
        var json = JSON.stringify(params);
    	$.ajax({
    		url : localhostPaht + projectName+"/demo/index",
     		data:json,
    		type : 'post',
    		contentType : 'application/json;charset=utf-8',
    		success : function(data) {
    			console.log(data);
    		},
    		error : function(error) {
    			console.log('介面不通' + error);
    		}
    	});
    }
    sendMessage();

呼叫後臺的demo/index這個介面,但是訪問了半天可以總是提示404

如下:

出現這樣的結果當然是讓人和頭疼的因為這個問題,我除錯一天,工程重新搭建,重新搭建,就這樣

但是到最後的時刻,問題還是解決了,讓人還是能看到一些生活的希望

聽說SpringMVC的配置很重要,那麼我們首先從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.wdg.SqzpAdmin</groupId>
	<artifactId>SqzpAdmin</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<build>
		<finalName>SqzpAdmin</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<version>2.1</version>
				<configuration>
					<path>/SqzpAdmin</path>
					<port>8080</port>
					<uriEncoding>UTF-8</uriEncoding>
					<server>tomcat7</server>
				</configuration>

			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.0</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<properties>
		<spring.version>4.0.5.RELEASE</spring.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>


		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</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>
		<!-- https://mvnrepository.com/artifact/log4j/log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.47</version>
		</dependency>
	</dependencies>
</project>

上面是一個非常簡單的SpringMVC,裡面用到的使用到的依賴都是最為基礎的依賴,那麼下下面是web.xml

當然僅僅配置一個轉發器就行了:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<display-name>SqzpAdmin</display-name>
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>index.html</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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
  http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
  http://www.springframework.org/schema/util
  http://www.springframework.org/schema/util/spring-util-4.2.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-4.2.xsd
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

	<!-- 解決中文亂碼 -->
	<mvc:annotation-driven>
		<mvc:message-converters register-defaults="true">
			<bean class="org.springframework.http.converter.StringHttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>text/plain;charset=UTF-8</value>
						<value>text/html;charset=UTF-8</value>
						<value>application/json;charset=UTF-8</value>
					</list>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>
	
	
	<bean id="utf8Charset" class="java.nio.charset.Charset"
		factory-method="forName">
		<constructor-arg value="UTF-8" />
	</bean>

	<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter" />
	<bean
		class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/" />
	</bean>
	<!-- 靜態資源處理 -->
	<mvc:default-servlet-handler />
	<mvc:annotation-driven />
	<context:component-scan base-package="com.wdg.controller"></context:component-scan>
</beans>

還有一個是controller:

package com.wdg.controller;

import java.io.IOException;

import org.apache.log4j.Logger;
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.ResponseBody;

import com.wdg.util.BuildJsonOfObject;

@Controller
@RequestMapping("/demo")
public class DemoController {

	private Logger log;

	public DemoController() {
		this.log = Logger.getLogger(this.getClass());
	}

	@RequestMapping("/index")
	public  String index(@RequestBody String params) {
		log.info("-----------------開始addcomment------------------------------------");

		log.info("-----------------結束addcomment------------------------------------");
		return BuildJsonOfObject.buildJsonOfString("demo");
	}

	@RequestMapping(value = "/addcomment", produces = "application/json; charset=utf-8")
	public @ResponseBody String addComment(@RequestBody String params) throws IOException {
		log.info("-----------------開始addcomment------------------------------------");

		log.info("-----------------結束addcomment------------------------------------");
		return params;

	}
}

上面就是簡單的工程了,但是訪問一直出現404,原因是因為我們需要在介面的前面加上:@ResponseBody 這個註釋,問題就解決了,希望對你有所幫助