一、什么是restFul设计?
二、restFul有什么用?
restFul编程:通过相同的请求路径,但是给方法设置不同的请求方式,来调用不同的方法
三、代码部分
项目目录
1、UserInfo.java
package com.qingruan.bean; public class UserInfo { private String name; private String phone; private int age; public UserInfo() { } @Override public String toString() { return "UserInfo{" + "name='" + name + '\'' + ", phone='" + phone + '\'' + ", age=" + age + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
2、RestFulController.java
package com.qingruan.servlet; import com.qingruan.bean.UserInfo; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @Controller @RequestMapping("/restful") public class RestFulController { @PostMapping public void post(@RequestBody UserInfo userInfo){ System.out.println(userInfo); System.out.println("保存成功"); } //可以将URL路径占位符参数{}取出,给变量赋值 @PutMapping("/{id}") public void patch(@PathVariable("id") Integer id,@RequestBody UserInfo userInfo){ System.out.println(id); System.out.println(userInfo); System.out.println("修改成功"); } @GetMapping("/{id}") @ResponseBody public UserInfo get(@PathVariable("id") Integer id){ System.out.println("根据id查询:"+id); UserInfo userInfo=new UserInfo(); userInfo.setName("jack"); userInfo.setAge(22); userInfo.setPhone("138989898"); return userInfo; } @DeleteMapping("/{id}") public void delete(@PathVariable("id") Integer id){ System.out.println("删除成功:" + id); } @GetMapping @ResponseBody public List<UserInfo> getAll(){ List<UserInfo> users=new ArrayList<UserInfo>(); System.out.println("查询用户列表:"); UserInfo u1=new UserInfo(); u1.setName("jack"); u1.setAge(22); u1.setPhone("138989898"); UserInfo u2=new UserInfo(); u2.setName("tom"); u2.setAge(19); u2.setPhone("138989898"); users.add(u1); users.add(u2); return users; } }
3、TestController.java
package com.qingruan.servlet; import com.qingruan.bean.UserInfo; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; //RestController是类级别的注解,应用之后相当于使用了@Controller、@ResponseBody //相当于减少了注解使用次数 @RestController public class TestController { //请求urll中的参数名和实体类中的属性名一致 //127.0.0.1:8080/springmvc_day01/userParam?name=zhangsan&age=21&phone=137272727 //@RequestBody表明把请求体中的JSON数据直接转换成对象 @RequestMapping("/getUser") public UserInfo getUser(@RequestBody UserInfo userInfo){ System.out.println(userInfo); return userInfo; } }
4、spring-mvc.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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--配置spring,创建容器时,扫扫描的包--> <context:component-scan base-package="com.qingruan"></context:component-scan> <!--配置内部视图解析器--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--前缀和后缀都是与业务逻辑方法值进行组合,组合成jsp文件所在的路径,/hello.jsp--> <property name="prefix" value="/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--配置响应结果的转换器--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <!--将响应结果转换成json格式数据--> <list> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean> </list> </property> </bean> <!--开启sringmvc框架注解的支持--> <mvc:annotation-driven></mvc:annotation-driven> <!--出现静态资源访问不到的情况,是因为前端控制器会拦截所有的请求,进行处理器的匹配 方式一:开启默认servlet,所有请求都会经过默认servlet请求,如果是静态资源则直接进行响应 <mvc:default-servlet-handler/> --> <!--方式二:设置指定的静态资源访问映射--> <!--<mvc:resources mapping="/img/**" location="/img/"></mvc:resources> <mvc:resources mapping="/js/**" location="/js/"></mvc:resources> <mvc:resources mapping="/html/**" location="/html/"></mvc:resources> <mvc:resources mapping="/css/**" location="/css/"></mvc:resources> --> </beans>
5、web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--配置核心控制器 前端控制器springmvc的集中访问点,负责指定分派 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--设置初始化参数,让程序启动后帮我们加载spring主配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> </servlet> <!--设置servlet拦截的请求路径--> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
6、index.jsp
<%-- Created by IntelliJ IDEA. User: 45579 Date: 2022/11/15 Time: 20:04 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored="false" %> <html> <head> <title>Title</title> <% pageContext.setAttribute("page",request.getContextPath());%> <!--绝对url指向指定栈点--> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <script> $(function (){ $("#btn").click(function () { var user={age:21,name:"zhangsan",phone:"111222333"}; $.ajax({ type:"POST", data:JSON.stringify(user), url:"${page}/getUser", contentType:"application/json;charset=utf-8", success:function (data) { console.log(data.age); } }) }) }) </script> </head> <body> <input type="button" id="btn" value="submitUser"/> <%--<img src="${page}/img/1.jpg">--%> </body> </html>
7、restful.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored="false" %> <html> <head> <title>Title</title> <% pageContext.setAttribute("page",request.getContextPath());%> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <script> var param = {id:1001,name:"zhangsan",age:21,phone:"1378888"}; var postMethod = function(){ $.ajax({ type:"POST", url:"${page}/restful", data:JSON.stringify(param), contentType:"application/json"}).then(function (value) { console.log(value) }) } var putMethod=function () { $.ajax({ type:"put", url:"${page}/restful/"+param.id, data:JSON.stringify(param), contentType:"application/json"}).then(function (value) { console.log(value) }) } var getMethod=function () { $.ajax({ type:"get", url:"${page}/restful/"+param.id, contentType:"application/json"}).then(function (value) { console.log(value) }) } var deleteMethod=function () { $.ajax({ type:"delete", url:"${page}/restful/"+param.id, contentType:"application/json"}).then(function (value) { console.log(value) }) } var getAllMethod=function () { $.ajax({ type:"get", url:"${page}/restful/", contentType:"application/json"}).then(function (value) { console.log(value) }) } </script> </head> <body> <input type="button" value="post" onclick="postMethod()"/> <input type="button" value="put" onclick="putMethod()"/> <input type="button" value="getById" onclick="getMethod()"/> <input type="button" value="delete" onclick="deleteMethod()"/> <input type="button" value="getAll" onclick="getAllMethod()"/> </body> </html>
四、运行效果
连接tomcat
控制台