先說一下什么是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/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttps://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>
java restful api 框架,
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态