Java --- springMVC实现RESTFul案例

news2025/2/24 0:34:26

一、使用springMVC实现RESTFul小案例

1.1、项目目录图:

 1.2、代码实现:

pom.xml文件:

    <packaging>war</packaging>
    <!--添加依赖-->
    <dependencies>
        <!--SpringMVC-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.1</version>
        </dependency>
        <!--日志-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!--servletAPI-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
    </dependencies>

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">
    <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>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--配置HiddenHttpMethodFilter-->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:SpringMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

SpringMVC.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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan base-package="com.cjc.mvc"></context:component-scan>
    <!--配置Thymeleaf视图解析器-->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <!--视图前缀-->
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <!--视图后缀-->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
    <!--配置视图控制器-->
    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>
    <mvc:view-controller path="/toAdd" view-name="employeeAdd"></mvc:view-controller>
    <!--开放对静态资源访问-->
    <mvc:default-servlet-handler/>
    <!--开启mvc的注解驱动-->
    <mvc:annotation-driven/>
</beans>

EmployeeController类

@Controller
public class EmployeeController {
     @Autowired
     private EmployeeDao employeeDao;
     @GetMapping("/getAllEmployee")
     public String getAllEmployee(Model model){
          Collection<Employee> employees = employeeDao.getAll();
          model.addAttribute("employees",employees);
          return "employeeList";
     }
     @DeleteMapping("/deleteEmployee/{id}")
     public String deleteEmployee(@PathVariable("id") Integer id){
          employeeDao.delete(id);
          return "redirect:/getAllEmployee";
     }
     @PostMapping("/addEmployee")
     public String addEmployee(Employee employee){
          employeeDao.save(employee);
          return "redirect:/getAllEmployee";
     }
     @GetMapping("/getEmployeeById/{id}")
     public String getEmployeeById(@PathVariable("id") Integer id,Model model){
          Employee employee = employeeDao.get(id);
          model.addAttribute("employee",employee);
          return "employeeUpdate";
     }
     @PutMapping("/updateEmployee")
     public String updateEmployee(Employee employee){
          employeeDao.save(employee);
          return "redirect:/getAllEmployee";
     }
}

EmployeeDao类:

@Repository
public class EmployeeDao {
    private static Map<Integer, Employee> employeeMap = null;
    static {
        employeeMap = new HashMap<Integer, Employee>();
        employeeMap.put(1001,new Employee(1001,"老王","123@qq.com",1));
        employeeMap.put(1002,new Employee(1002,"老李","456@qq.com",1));
        employeeMap.put(1003,new Employee(1003,"老赵","789@qq.com",0));
        employeeMap.put(1004,new Employee(1003,"老秦","987@qq.com",0));
        employeeMap.put(1005,new Employee(1003,"老头","654@qq.com",0));
        }
        private static Integer initId = 1006;
    public void save(Employee employee){
        if (employee.getId() == null){
            employee.setId(initId++);
        }
        employeeMap.put(employee.getId(),employee);
    }
    public Collection<Employee> getAll(){
        return employeeMap.values();
    }
    public Employee get(Integer id){
        return employeeMap.get(id);
    }
    public void delete(Integer id){
        employeeMap.remove(id);
    }
}

Employee类:

@AllArgsConstructor
@NoArgsConstructor
@Data
public class Employee {
    private Integer id;
    private String name;
    private String email;
    private Integer gender;
}

employeeAdd.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加</title>
</head>
<body>
<form th:action="@{/addEmployee}" method="post">
    name:<input type="text" name="name" ><br>
    email:<input type="text" name="email"><br>
    gender:<input type="radio" name="gender" value="1" >male
    <input type="radio" name="gender" value="2">female<br>
    <input type="submit" value="add">
</form>
</body>
</html>

employeeList.html:

<table id="dataTable" border="1" cellspacing="0" cellpadding="0" style="text-align: center">
    <tr>
        <th colspan="5">Employee Info</th>
    </tr>
    <tr>
        <th>id</th>
        <th>name</th>
        <th>email</th>
        <th>gender</th>
        <th>options(<a th:href="@{/toAdd}">add</a>)</th>
    </tr>
    <tr th:each="employee : ${employees}">
        <td th:text="${employee.id}"></td>
        <td th:text="${employee.name}"></td>
        <td th:text="${employee.email}"></td>
        <td th:text="${employee.gender}"></td>
        <td>
            <a @click="deleteEmployee" th:href="@{'/deleteEmployee/'+${employee.id}}">delete</a>
            <a th:href="@{'/getEmployeeById/'+${employee.id}}">update</a>
        </td>
    </tr>
</table>
<form id="deleteForm" method="post">
    <input type="hidden" name="_method" value="delete">
</form>
<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript">
    var vue = new Vue({
        el:"#dataTable",
        methods:{
            deleteEmployee:function (event){
                //根据id获取表单元素
                var elementById = document.getElementById("deleteForm");
                //将触发点击事件的超链接的href属性赋值给表单action
                elementById.action = event.target.href;
                //提交表单
                elementById.submit();
                //取消超链接默认行为
                event.preventDefault();
           }
        }
    });
</script>
</body>
</html>

employeeUpdate.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>修改</title>
</head>
<body>
<form th:action="@{/updateEmployee}" method="post">
    <input type="hidden" name="_method" value="put">
    <input type="hidden" name="id" th:value="${employee.id}">
    name:<input type="text" name="name" th:value="${employee.name}"><br>
    email:<input type="text" name="email" th:value="${employee.email}"><br>
    gender:<input type="radio" name="gender" value="1" th:field="${employee.gender}">male
    <input type="radio" name="gender" value="2" th:field="${employee.gender}">female<br>
    <input type="submit" value="update">
</form>
</body>
</html>

 index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>首页</h1>
<a th:href="@{/getAllEmployee}">查看员工信息</a>
</body>
</html>

vue.js这个文件可以自己下载拷贝过来

已上传到资源下载中:https://download.csdn.net/download/qq_46093575/86870794

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2794.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

黑马C++ 03 提高4 —— STL常用容器_string容器/vector容器/deque容器

文章目录一、string容器1. string基本概念2. string构造函数3. string赋值操作4. string字符串拼接5. string查找和替换6. string字符串比较7. string字符存取8. string字符串的插入和删除9. string子串二、vector容器(尾插尾删)1. vector基本概念2. vector构造函数3. vector赋…

【目标检测】基于yolov3的血细胞检测(无bug教程+附代码+数据集)

多的不说,少的不唠,先看检测效果图: 共检测三类:红细胞RBC、白细胞WBC、血小板Platelets Hello,大家好,我是augustqi。今天给大家带来的保姆级教程是:基于yolov3的血细胞检测(无bug教程+附代码+数据集) 1.项目背景 在上一期的教程中,我们基于yolov3训练了一个红细…

韩顺平linux(1-11小节)

运维工程师 服务器的规划、调试优化、日常监控、故障处理 物联网linux Linux主要指的是内核 ubuntu&#xff08;python偏爱&#xff09;&#xff0c;centos 发行版本 内核进行包装 1.4服务器领域 linux在服务器领域的应用是最强的。 linux免费、稳定、高效等特点在这里得到了很…

2019 Sichuan Province Programming Contest J. Jump on Axis

题目链接&#xff1a;https://codeforces.com/gym/102821/problem/J 题意&#xff1a;给你一个坐标k&#xff0c;每次从0开始走 每次有三个选择&#xff1a;选择1走一步&#xff0c;选择2走两步&#xff0c;选择3走三步 每次选第i个选择的时候&#xff0c;如果他没有被选过&…

MySQL是如何保证数据不丢失的

一.什么是两阶段提交 1.SQL语句&#xff08;update user set name‘李四’ where id3&#xff09;的执行流程是怎样的呢&#xff1f; 1.执行器先找引擎取 ID3这一行。ID 是主键&#xff0c;引擎直接用树搜索找到这一行。 2.如果 ID3 这一行所在的数据页本来就在内存中&#x…

力扣算法入门刷题

1、回文数 判断输入的整数是否是回文 我的一般思路&#xff1a; 将输入的整数转成字符串&#xff0c;再将这个字符串转成字符数组c&#xff0c;对字符数组进行遍历&#xff0c;如果第i个元素与第 c.length - i - 1 元素不相等&#xff0c;也就是通过比较首尾元素是否相同来判断…

自动化早已不是那个自动化了,谈一谈自动化测试现状和自我感受……

前言 从2017年6月开始接触自动化至今&#xff0c;已经有好几年了&#xff0c;从17年接触UI自动化&#xff08;unittestselenium&#xff09;到18年接触接口自动化&#xff08;unittestrequests&#xff09;再到18年自己编写自动化平台&#xff08;后台使用python的flask&#…

风、光、柴油机、蓄电池、电网交互微电网经济调度优化问题研究附Matlab代码

✅作者简介&#xff1a;热爱科研的Matlab仿真开发者&#xff0c;修心和技术同步精进&#xff0c;matlab项目合作可私信。 &#x1f34e;个人主页&#xff1a;Matlab科研工作室 &#x1f34a;个人信条&#xff1a;格物致知。 更多Matlab仿真内容点击&#x1f447; 智能优化算法 …

爆破校园网的宽带

前提&#xff1a;学校的手机号前7位相同&#xff0c;宽带密码都是手机号后六位。仅供学习。 准备工作&#xff1a;电脑一台&#xff0c;把校园网的宽带水晶头插在电脑上&#xff0c; 步骤&#xff1a; winR输入Rasphone点击新建&#xff0c;宽带&#xff0c;输入宽带名称&am…

Vue复刻华为官网 (一)

1 分析 根据华为网页的布局&#xff0c;我们大体上可以将其划分为7个盒子&#xff0c;如下&#xff0c;由于写一个这样的网页再加上部分动态效果&#xff0c;需要的时间很长&#xff0c;本篇博客只记录了div1、div2、div3的静态效果轮播图的实现。 2 顶部盒子的实现 想要实现的…

【C++AVL树】4种旋转详讲

目录 引子&#xff1a;AVL树是因为什么出现的&#xff1f; 1.AVl树的的特性 2.AVl树的框架 3.AVL树的插入 3.1四种旋转&#xff08;左单旋、右单旋、左右双旋、右左双旋&#xff09; 3.1.1左单旋 3.1.2右单旋 3.1.3左右双旋 3.1.4右左双旋 总结 引子&#xff1a;AVL树是因…

【单片机】单片机的核心思想

&#x1f4ac;推荐一款模拟面试、刷题神器 、从基础到大厂面试题&#xff1a;&#x1f449;点击跳转刷题网站进行注册学习 目录 一、单片机的核心思想 二、单片机核心图 三、上拉电路及应用 排阻的优势 四、单片机的输入输出模式 1、接收外部电压信号 2、向外输出电压信…

0089 时间复杂度,冒泡排序

/* * 排序也称排序算法&#xff08;Sort Algorithm&#xff09; * 排序是将一组数据&#xff0c;依指定的顺序进行排列的过程。 * * 排序分类 * 1.内部排序&#xff1a;将需要处理的所有数据都加载到内存存储器中进行排序&#xff08;使用内存&#xff09; * 插…

彻底搞懂WeakMap和Map

一 、Map Map是一种叫做字典的数据结构&#xff0c;Map 对象保存不重复键值对&#xff0c;并且能够记住键的原始插入顺序 Map的属性和方法* 属性&#xff1a; size&#xff1a; 返回所包含的键值对长度* 操作方法&#xff1a;* set(key,val): 添加新键值对* get(key): 通过传…

Linux--信号signal、父子进程、SIGCHLD信号相关命令

目录 1.概念&#xff1a; 2.信号的存储位置&#xff1a; 3.常见的信号的值以及对应的功能说明&#xff1a; 4.信号的值在系统源码中的定义&#xff1a; 5.响应方式&#xff1a; 6.改变信号的相应方式&#xff1a; (1)设置信号的响应方式: (2)默认:SIG_DFL;忽略:SIG_IGN…

Android Studio 新版本 Logcat 的使用

前言 最近&#xff0c;Android Studio 自动更新了自带的 Logcat 工具&#xff0c;整体外观和使用方法变得和之前完全不同了。一开始我以为是自己按到什么不该按的按钮&#xff0c;把 Logcat 弄坏了&#xff0c;后来才知道是版本更新导致的。新版本的 Logcat 用命令来过滤信息&…

jmeter变量函数以及抓包用法

抓包 代理服务器&#xff1a; 自己启动一个代理服务器 本地&#xff0c;要使用代理服务器的ip和端口&#xff0c;使用自己启动的代理服务器 操作步骤 添加线程组测试计划 > 非测试元件 > http代理服务器一定要修改 修改为** 测试计划>线程 ip就是你自己电脑的ip&…

Activity

Activity生命周期图 官网的 Activity 的生命周期图&#xff1a; 在官方文档中给出了说明&#xff0c;不允许在 onPause() 方法中执行耗时操作&#xff0c;因为这会影响到新 Activity 的启动。 常见情况下Activity生命周期的回调 &#xff08;A 与 B 表示不同的 Activity &a…

(硬件设计)老工程师的经验之道

系列文章目录 1.元件基础 2.电路设计 3.PCB设计 4.元件焊接 5.板子调试 6.程序设计 7.算法学习 8.编写exe 9.检测标准 10.项目举例 11.职业规划 文章目录前言1、用蜡烛油固定电位器2、电路板接插件用彩色接插件前言 送给大学毕业后找不到奋斗方向的你&#xff08;每周不定时…

Python----科学计数法、同时给多个变量赋值、eval函数、math库函数、复数(complex())、内置的数值运算函数、内置的数值运算操作符

科学计数法使用字母"e"或者“E”作为幂的符号&#xff0c;以10为基数&#xff0c;科学计数法的含义如下&#xff1a; 96e4&#xff1a;96乘10的4次幂 4.3e-3&#xff1a;4.3乘10的负三次幂 aeb&#xff1a;a*10*b 同时给多个变量赋值格式: 变量1&#xff0c;变量2表…