RESTful风格的应用创建

1 篇文章 0 订阅

准备一: web.xml

这里只需要增加一个REST的支持
在这里插入图片描述


准备二: rest-servlet.xml

启用注解扫描,以及扫描controller

<?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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
			http://www.springframework.org/schema/beans/spring-beans.xsd
  			http://www.springframework.org/schema/mvc
			http://www.springframework.org/schema/mvc/spring-mvc.xsd
       		http://www.springframework.org/schema/context
       		http://www.springframework.org/schema/context/spring-context.xsd"
	default-lazy-init="true">
	
	<!-- 通过mvc:resources设置静态资源,这样servlet就会处理这些静态资源,而不通过控制器 -->
	<!-- 设置不过滤内容,比如:css,jquery,img 等资源文件 -->
	<mvc:resources location="/*.html" mapping="/**.html" />
	<mvc:resources location="/css/*" mapping="/css/**" />
	<mvc:resources location="/js/*" mapping="/js/**" />
	<mvc:resources location="/images/*" mapping="/images/**" />
	
	<!-- 添加注解驱动 -->
	<mvc:annotation-driven />
	<!-- 默认扫描的包路径 -->
	<context:component-scan base-package="rest.controller" />
	
	<!-- mvc:view-controller可以在不需要Controller处理request的情况,转向到设置的View -->
	<!-- 像下面这样设置,如果请求为/,则不通过controller,而直接解析为/index.jsp -->
	<mvc:view-controller path="/" view-name="index" />
	<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
		<!-- 配置jsp路径前缀 -->
		<property name="prefix" value="/"></property>
		<!-- 配置URl后缀 -->
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>

准备三: controller

package rest.controller;

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 net.sf.json.JSONObject;

@Controller
@RequestMapping("/restcontroller")
public class RestController {

	@RequestMapping(value = "/usersid/{id}", method = RequestMethod.GET
			, produces = "application/json;charset=UTF-8")
	public @ResponseBody String selectById(@PathVariable("id") Integer id) {
		System.out.println("查找id为: " + id);
		UserModel userModel = new UserModel();
		userModel.setId(1);
		userModel.setName("zhangxu");
		userModel.setCipher("man");

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("data", userModel);
		System.out.println(jsonObject);
		return jsonObject.toString();
	}

	@RequestMapping(value = "/usersname/{name}", method = RequestMethod.POST
			, produces = "application/text;charset=UTF-8")
	public @ResponseBody String selectByName(@PathVariable("name") String name) {
		System.out.println("查找name为: " + name);
		return "查找" + name + ",这是返回结果String";
	}

	@RequestMapping(value = "/userspage", method = RequestMethod.POST
			, produces = "application/json;charset=UTF-8")
	public @ResponseBody String getDataFromPage(UserModel userModel) {
		JSONObject fromObject = JSONObject.fromObject(userModel);
		System.out.println("获取json数据"+fromObject.toString());
		return fromObject.toString();
	}

	
}

这里有几个地方需要注意:

  1. 界面中使用的请求方法要与controller对应
  2. 占位符表示此处为参数, 有多少个参数应该使用多少个/{}去接收, @PathVariable("")指明后面的传递参数接收的是哪个占位符对应的值.
  3. 视图传递json数据可以使用对应的实体类去接收
  4. 以上第二个是rest的一个特点

还需要增加一个实体类

package rest.controller;

public class UserModel {
	private Integer id;
	private String name;
	private String cipher;
	public Integer getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	public String getCipher() {
		return cipher;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setCipher(String cipher) {
		this.cipher = cipher;
	}
	
	
}


最后: 写个ajax请求

<%@ 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>
<script type="text/javascript" src="http://unpkg.com/jquery@3.3.1/dist/jquery.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>欢迎</title>
</head>
<body>
<h1>Hello RESTful!</h1>
<hr>
<h2>按照id查找,返回json格式: </h2>
<span id="span1" style="background-color: yellow;"></span>

<hr>
<h2>按照name查找,返回String格式: </h2>
<span id="span2" style="background-color: yellow;"></span>

<hr>
<h2>发送JSON, 返回JSON格式: </h2>
<span id="span3" style="background-color: yellow;"></span>

</body>
<script type="text/javascript">
	$.ajax({
		url:'/SpringDemo/restcontroller/usersid/1'
		, type: 'get'
		, dataType: 'json'
		, async: true
		, success: function(data){
			$("#span1").text(JSON.stringify(data))
		}
	})

	$.ajax({
		url:'/SpringDemo/restcontroller/usersname/zhangxu'
		, type: 'post'
		, dataType: 'text'
		, async: true
		, success: function(data){
			$("#span2").text(data)
		}
	})
	
	var data = {id: 2, name:'sunhongluan', cipher: 'female'}
	$.ajax({
		url:'/SpringDemo/restcontroller/userspage/'
		, type: 'post'
		, data: data
		, dataType: 'json'
		, async: true
		, success: function(data){
			$("#span3").text(JSON.stringify(data))
		}
	})
</script>

</html>


验证

刷新一下页面,可以看到,页面出现的信息
在这里插入图片描述


参考

如何给老婆解释什么是RESTful:
https://zhuanlan.zhihu.com/p/30396391?group_id=937244108725641216(推荐)
REST,以及RESTful的讲解:
https://blog.csdn.net/qq_21383435/article/details/80032375(这篇文章的参考值得一看)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值