先说一下什么是RestFul风格,以一个链接为例子,如果我们访问一个网页,想要给a和b传参数,传统的方式是?a=1&b=2,而RestFul就是改变了传统的方式,用/a/1/2的形式,达到了简洁、安全、高效(支持缓存)。
这里我们以一个简单的SpringMVC例子来进行演示,首先我们写一个Controller控制器(核心)
package com.zhiying.controller4;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ControllerTest4 {
@RequestMapping("/add/{a}/{b}")
public String test1(@PathVariable int a, @PathVariable int b, Model model) {
int result = a + b;
model.addAttribute("msg", "结果为" + result);
return "test";
}
}
然后写一个配置文件
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描指定的包,该包下面的所有注解类交给IoC容器管理-->
<context:component-scan base-package="com.zhiying"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀匹配-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 后缀匹配-->
<property name="suffix" value=".jsp"/>
</bean>
<!-- <bean id="/hello" class="com.zhiying.controller.ControllerTest"/>-->
</beans>
然后是web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 配置DispatchServlet,其本质是一个Servlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
最后是jsp文件了
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
来源:CSDN
作者:贺志营
链接:https://blog.csdn.net/HeZhiYing_/article/details/103993625