javascript
【Spring】SpringMVC之REST编程风格
REST架構是一個抽象的概念,目前主要是基于HTTP協議實現,其目的是為了提高系統的可伸縮性、降低應用之間的耦合度、便于架構分布式處理程序。當使用多種語言進行開發的時候,每一種語言對URL的處理不同,這時候就需要統一處理,那么使用REST編程風格就很有必要了。REST只是一種設計模式,如果需要對安全性有要求,就是額外的功能代碼了。
使用方式
在URL中設置使用如下方式: /{變量名1}/{變量名2}
在代碼中向Controller方法注入參數: ?(@PathVariable("變量名1") String str1,@PathVariable("變量名2") String str2)?
例如:
?
Demo
bean類:
package cn.xdl.bean;public class Book {private int bid;private String bname;public int getBid() {return bid;}public void setBid(int bid) {this.bid = bid;}public String getBname() {return bname;}public void setBname(String bname) {this.bname = bname;}public Book(int bid, String bname) {super();this.bid = bid;this.bname = bname;}public Book() {super();// TODO Auto-generated constructor stub }@Overridepublic String toString() {return "Book [bid=" + bid + ", bname=" + bname + "]";}} Book.javaController類:
package cn.xdl.c;import java.util.HashMap; import java.util.Map;import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody;import cn.xdl.bean.Book;@Controller public class BookController {/*** VALUE :請求的地址模版 (模版中使用大括號括住的部分, 屬于變量)* method: 請求的方式* @return*/@RequestMapping(value="/book/{bookid}",method=RequestMethod.GET)@ResponseBodypublic Object insertBook(@PathVariable("bookid") String bookId) {System.out.println("正在查詢圖書 , 請求的圖書的編號為:"+bookId);return new Book(Integer.parseInt(bookId), "歡樂頌");}@RequestMapping(value="book/{bookid}",method=RequestMethod.DELETE)@ResponseBodypublic Object deleteBook(@PathVariable("bookid")String bookid) {System.out.println("正在刪除圖書:id:"+bookid);Map<String,String> map = new HashMap<String,String>();map.put("errorCode0", "0");map.put("msg", "刪除成功");return map;}@RequestMapping(value="book/{bookid}/{bookname}",method=RequestMethod.PUT)@ResponseBodypublic Object updateBook(@PathVariable("bookid") String bookId,@PathVariable("bookname") String bookName) {System.out.println("正在修改圖書:id:"+bookId+", 要修改的新書名:"+bookName);Map<String,String> map = new HashMap<String,String>();map.put("errorCode0", "0");map.put("msg", "修改成功");return map;}@RequestMapping(value="book/{bookid}/{bookname}",method=RequestMethod.POST)@ResponseBodypublic Object insertBook(@PathVariable("bookid") String bookId,@PathVariable("bookname") String bookName) {System.out.println("正在添加圖書:id:"+bookId+", 要添加的新書名:"+bookName);Map<String,String> map = new HashMap<String,String>();map.put("errorCode0", "0");map.put("msg", "添加成功");return map;}} BookController.java這里的通信方式返回的結果是Object對象。在這個筆者使用了注解?@ResponseBody ,需要導入包?jackson-annotations.jar 、?jackson-core.jar 和?jackson-databind.jar包。
bean.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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:util="http://www.springframework.org/schema/util"xmlns:jpa="http://www.springframework.org/schema/data/jpa"xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsdhttp://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsdhttp://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd"><!-- 開啟注解掃描--><context:component-scan base-package="cn"></context:component-scan><!-- 開啟mvc注解掃描--><mvc:annotation-driven/><mvc:default-servlet-handler/></beans> bean.xml在配置文件中一定需要指出:
<mvc:default-servlet-handler/>否則會出現靜態資源(如js、css等資源)攔截404的錯誤。
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_3_0.xsd" version="3.0"><servlet><servlet-name>webmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:bean.xml</param-value></init-param></servlet><servlet-mapping><servlet-name>webmvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping></web-app> web.xmlweb.xml文件過濾的url必須寫成?<url-pattern>/</url-pattern> ,因為采用REST編程風格,在url地址中只會出現/分割符號,所以只能寫成這樣?<url-pattern>/</url-pattern> ,以匹配所有的路徑。
restTest.jsp文件
<%@ 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>Insert title here</title> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript">function insertClick(){$.ajax({url:"book/10003/hahaha",dataType:"JSON",type:"POST",success:function(data){alert( JSON.stringify(data));},error:function(){}});}function deleteClick(){$.ajax({url:"book/10003",dataType:"JSON",type:"DELETE",success:function(data){alert( JSON.stringify(data));},error:function(){}});}function updateClick(){$.ajax({url:"book/10003/hahaha",dataType:"JSON",type:"PUT",success:function(data){alert( JSON.stringify(data));},error:function(){}});}function findClick(){$.ajax({url:"book/10003",dataType:"JSON",type:"GET",success:function(data){alert( JSON.stringify(data));},error:function(){}});}</script> </head> <body><input οnclick="insertClick()" type="button" value="增加"/><br><br><input οnclick="deleteClick()" type="button" value="刪除"/><br><br><input οnclick="updateClick()" type="button" value="修改"/><br><br><input οnclick="findClick()" type="button" value="查詢"/><br><br> </body> </html> restTest.jsp這里通信方式是采用Ajax請求。
?
Rest請求地址中帶有中文的處理
如果在Rest風格的請求中,請求的參數帶有中文,就會出現映射錯誤。這時候需要進行如下的配置:
在SpringMVC的配置文件中將?<mvc:annotation-driven/> 改為:
<!--開始注解--><mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>除此之外還需要在tomcat 的 server.xml中,加入URIEncoding="UTF-8":
<Connector connectionTimeout="20000" port="8081" URIEncoding="UTF-8" protocol="HTTP/1.1" redirectPort="8443"/>這樣就可以解決Rest請求中中文亂碼的問題了。
轉載于:https://www.cnblogs.com/HDK2016/p/7197696.html
總結
以上是生活随笔為你收集整理的【Spring】SpringMVC之REST编程风格的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sql数据库的基本操作
- 下一篇: javascript的程序控制结构及语句