Spring-mvc-Restful风格实现增删改查

Restful风格:

一种软件架构风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

URL定义

资源:互联网所有的事物都可以被抽象为资源
资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。
分别对应 添加、 删除、修改、查询。

Restful的特性

资源(Resources):网络上的一个实体,或者说是网络上的一个具体信息。它可以是一段文本、一张图片、一首歌曲、一种服务,总之就是一个具体的存在。可以用一个URI(统一资源定位符)指向它,每种资源对应一个特性的URI。要获取这个资源,访问它的URI就可以,因此URI即为每一个资源的独一无二的识别符。

表现层(Representation):把资源具体呈现出来的形式,叫做它的表现层(Representation)。比如,文本可以用txt格式表现,也可以用HTML格式、XML格式、JSON格式表现,甚至可以采用二进制格式。

状态转换(State Transfer):每发出一个请求,就代表了客户端和服务器的一次交互过程。HTTP协议,是一个无状态协议,即所有的状态都保存在服务器端。因此,如果客户端想要操作服务器,必须通过某种手段,让服务器端发生“状态转换”(State Transfer)。而这种转换是建立在表现层之上的,所以就是“表现层状态转换”。具体说,就是HTTP协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。他们分别对应四种基本操作:GET用来获取资源,POST用来新建资源,PUT用来更新资源,DELETE用来删除资源。

接下来简单实现一下:
首先:建立一个实体类:

package gvn.openlab.bean;
public class Employee {
    private int  id;//id模拟数据库自增
    private String name;
    private String sex;
    private static  int i=0;
    public Employee() {
        this.id = i;
        i++;
    }
    public Employee( String name, String sex) {
       this();
        this.name = name;
        this.sex = sex;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

在建立一个接口定义相应的方法:

package gvn.openlab.dao;

import gvn.openlab.bean.Employee;

import java.util.List;

public interface EmpDao {
    public List<Employee> findall();//查找所有数据
    public  void sava (Employee employee);//添加数据方法
    public void delete(Integer id);//按id删除数据
    public  Employee findByid(Integer id);//按id查找数据
}

实现接口方法:

package gvn.openlab.dao.impl;

import gvn.openlab.bean.Employee;
import gvn.openlab.dao.EmpDao;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class EmpDaoImpl implements EmpDao {
    private  static Map<Integer,Employee> map=new HashMap<Integer,Employee>();//定义一个map装假数据
    static {//静态代码块 加载数据入map
        Employee e=new Employee("若尘","男");
        Employee e1=new Employee("若曦","男");
        Employee e2=new Employee("梓渝","男");
        map.put(e.getId(),e);
        map.put(e1.getId(),e1);
        map.put(e2.getId(),e2);
        System.out.println("sta方法执行");
    }
    @Override
    public List<Employee> findall() {//查寻数据
       // System.out.println(new ArrayList<>(map.values()));
        return new ArrayList<>(map.values());//将map封装成List
    }

    @Override
    public void sava(Employee employee) {//添加方法
        map.put( employee.getId(),employee);
    }

    @Override
    public void delete(Integer id) {//删除方法
        map.remove(id);
    }

    @Override
    public Employee findByid(Integer id) {//通过id进行查找数据
        return map.get(id);
    }
}

没有连接数据库,只是进行假数据的;

jsp文件:
首先进入界面:

<%--
  Created by IntelliJ IDEA.
  User: 11960
  Date: 2021/9/21
  Time: 16:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/emp">查看信息</a>
</body>
</html>

该界面不需要后台所以可以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:p="http://www.springframework.org/schema/p"
       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-4.3.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <context:component-scan base-package="gvn.openlab">
       <!-- 扫描gvn.openlab-->
        </context:component-scan>
        <!-- 我们配置了<mvc:view-controller path="/" view-name="index"></mvc:view-controller>如果不写下面的配置其他需要后台控制的就无法使用-->
    <mvc:annotation-driven/>
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>

</bean>
      <!--如果当前路径是/ 则交给相应的视图解析器直接解析为视图-->
    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>
    <mvc:view-controller path="/save" view-name="save"></mvc:view-controller>

</beans>

展示查询界面的jsp文件

//当我们使用 <c:forEach  var="" items="">要加入下面的不然无法使用
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/save">添加</a>
//点击添加会跳到sava界面 
<table>
    <tr>
        <td>id</td>
        <td>name</td>
        <td>sex</td>
    </tr>
    //循环的将list的数据添加到下面
    <c:forEach  var="employee" items="${list}">
        <tr>
            <td>
                    ${employee.id}
            </td>
            <td>
                    ${employee.name}
            </td>
            <td>${employee.sex}</td>
            <td>
               //点击修改会掉用EmployeeController类的empupdate方法
                <a 
           href="${pageContext.request.contextPath}/emp/${employee.id}">修改</a>

            </td>
            <td>
            //点击删除会掉用EmployeeController类的empdelete方法
                      <a href="javascript:void(0)" onclick="deletedate(${employee.id});">删除</a>
            </td>
        </tr>
    </c:forEach>
</table>//将请求方式改为DELETE
<form action="" method="post" name="from">
<input type="hidden" name="_method" value="DELETE" />
// name="_method"这个属性尽量复制,不然可能会出错
</form>
</body>
<script>
//点击删除是会调用下面函数
    function deletedate(id){
        var form=document.getElementsByName("from")[0];
        form.action="${pageContext.request.contextPath}/emp/"+id;
        form.submit();
    }
</script>
</html>

EmployeeController 控制类

package gvn.openlab.controller;

import gvn.openlab.bean.Employee;
import gvn.openlab.dao.EmpDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
public class EmployeeController {
    @Autowired
    @Qualifier("empDaoImpl")
    private EmpDao empDaoimpl;
    //查看所有员工信息
    @GetMapping("/emp")
    public String empilist(HttpServletRequest request){
        List<Employee> list=empDaoimpl.findall();
        System.out.println(list);
        request.setAttribute("list",list);
        return "show";//转发     
        //将返回到xml下<property name="prefix" value="/WEB-INF/views/"></property>
       // <property name="suffix" value=".jsp"></property>
       //去寻找show.jsp文件在WEB-INF/views下

    }
    //当请求方式是post和url是"/emp"调用下面方法
    @PostMapping("/emp")
    public String empsava(Employee employee){
        empDaoimpl.sava(employee);
        return "redirect:/emp";//重定向
    }
    @DeleteMapping("/emp/{id}")
    public  String empdelete(@PathVariable("id") Integer id){
        empDaoimpl.delete(id);
        return "redirect:/emp";
    }
    @GetMapping ("/emp/{id}")
    public  String empupdate(@PathVariable("id") Integer id,Map<String,Object>map){
        Employee employee=empDaoimpl.findByid(id);
        map.put("employee",employee);//先找到自己想修改的
        return "empupdate";
    }
    @PutMapping("/emp")
    public String empupdate(Employee employee ){
        empDaoimpl.sava(employee);
        return "redirect:/emp";
    }
}

添加的jap文件:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
//点击添加跳掉empilist方法
<form action="${pageContext.request.contextPath}/emp" method="post">
    name:<input type="text" name="name"><br>
    sex:<input type="radio" name="sex" value="男">男
    <input type="radio" name="sex" value="女">女
    <br>
    <input type="submit" value="添加">
</form>
</body>
</html>

更新的jsp文件:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/emp" method="post">
    id:<input type="text" name="id" value="${employee.id}"><br>
    name:<input type="text" name="name" value="${employee.name}"><br>
    sex:<input type="radio" name="sex" value="男" ${employee.sex=="男"?"checked":""}>男
    <input type="radio" name="sex" value="女" ${employee.sex=="女"?"checked":""}>女
    <br>
    <input type="hidden" name="_method" value="put" />
    <input type="submit" value="修改">
</form>
</body>
</html>

结果:
Spring-mvc-Restful风格实现增删改查
Spring-mvc-Restful风格实现增删改查

Spring-mvc-Restful风格实现增删改查
Spring-mvc-Restful风格实现增删改查
Spring-mvc-Restful风格实现增删改查
Spring-mvc-Restful风格实现增删改查
Spring-mvc-Restful风格实现增删改查

Spring-mvc-Restful风格实现增删改查

pom.xml 依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>mvc-spring</artifactId>
    <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.3.5</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.3.5</version>
        </dependency>


        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.3.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->


        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjtools</artifactId>
            <version>1.9.5</version>
        </dependency>

        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.5</version>
        </dependency>
        <!--Spring事物依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.3.5</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>



        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.9</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>









        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>2.4.1</version>
            <scope>compile</scope>
        </dependency>


        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>


        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.2</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/taglibs/standard -->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>



    </dependencies>

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>

</build>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
</project>
上一篇:序列化、Socket、邮件、多线程


下一篇:Springboot线程池并发处理数据优化