Spring-MVC 返回json 实现增删改查

首先建立一个maven-web工程:
在这里插入图片描述
然后导入依赖:

<?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>springmvc</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 -->
       //包含Spring 框架基本的核心工具类。Spring 其它组件要都要使用到这个包里的类,是其它组件的基本核心
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.3.5</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
        //所有应用都要用到的,它包含访问配置文件、创建和管理bean 以及进行Inversion of Control / Dependency Injection(IoC/DI)操作相关的所有类。如果应用只需基本的IoC/DI 支持,引入spring-core.jar 及spring-beans.jar 文件就可以了。
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.3.5</version>
        </dependency>


        <dependency>
        // Druid是一个JDBC组件,它包括三部分: DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体系。 DruidDataSource 高效可管理的数据库连接池。 SQLParser
            <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>
        //为Spring 核心提供了大量扩展。可以找到使用Spring ApplicationContext特性时所需的全部类,JDNI 所需的全部类,instrumentation组件以及校验Validation 方面的相关类。
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
        <dependency>
        //包含在应用中使用Spring 的AOP 特性时所需的类和源码级元数据支持。使用基于AOP 的Spring特性,如声明型事务管理(Declarative Transaction Management),也要在应用里包含这个jar包。
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.3.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->

         //AspectJ切面的依赖包
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjtools</artifactId>
            <version>1.9.5</version>
        </dependency>
        //AOP联盟的API包,里面包含了针对面向切面的接口
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
         //支持切入点表达式,AOP
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.0</version>
        </dependency>
    //提供了对JDBC操作的完整封装
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.8</version>
        </dependency>
        //提供了对JDBC操作的完整封装
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.5</version>
        </dependency>
        <!--Spring事物依赖 -->
        //负责在spring框架中实现事务管理功能
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.3.5</version>
        </dependency>
        
        //jiangMyBatis 代码无缝地整合到 Spring 
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        
        //mybatis依赖
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>


        //spring web mvc依赖
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.9</version>
        </dependency>

        //servlet-api 是提供编写servlet时要用到 

HttpServletRequestHttpServletResponse 等对象的
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>


//json解析
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.1</version>
        </dependency>



         //Protobuf是Google开发的一种数据描述语言,类似于XML能够将结构化数据序列化,可用于数据存储、通信协议等方面。
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>2.4.1</version>
            <scope>compile</scope>
        </dependency>

         //web项目里面开发jsp页面的时候,使用action调用servlet里面get和post方法的时候需要这个jar包
        <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 -->
        //标签依赖
        //<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>  /引入标签库
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>



    </dependencies>

    <build>
    //下面是我无法找到我的xml配置文件写的
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <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>

建立一个类:

package com.openlab.bean;
public class Employee {
    private int  id;
    private String name;
    private String sex;
    private static  int i=0;

    public static void setI(int i) {
        Employee.i = i;
    }

    public Employee() {
        this.id = 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;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

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

package com.openlab.dao;


import com.openlab.bean.Employee;

import java.util.List;

public interface EmpDao {
    public List<Employee> findall();//查找所有的Employee
    public  void sava (Employee employee);//添加Employee
    public void delete(Integer id);//按id删除Employee
    public  Employee findByid(Integer id);//按id查找Employee
    public void update(Employee employee);//修改Employee

}

实现接口的方法:

package com.openlab.dao.impl;


import com.openlab.bean.Employee;
import com.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>();
    static {
        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() {
        return new ArrayList<>(map.values());
    }

    @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) {
        return map.get(id);
    }

    @Override
    public void update(Employee employee) {
        map.get(employee.getId()).setName(employee.getName());
        map.get(employee.getId()).setSex(employee.getSex());
      );
    }
}

未连接数据库所以我们创建了假数据,我用的map存的数据,有键和值,id是自增的,所以修改方法和添加可以是一个,update()可不写;就用sava()方法就好了。

web.xml配置:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
	 version="2.4">
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
		<!--定时器的自动加载等内容写在spring-mvc.xml。然后把spring-mvc.xml,放在web.xml文件下的servlet中进行初始化-->
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>


	<filter>
	<!--post请求乱码,加入下面-->
		<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>




 <!-- 增加HiddenHttpMethodFilte过滤器:给普通浏览器增加 put|delete请求方式 -->
	<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>
</web-app>

接着写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: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="com.openlab"></context:component-scan>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>
<!--加载静态资源需要加入-->
<mvc:default-servlet-handler></mvc:default-servlet-handler>

   <mvc:annotation-driven/>
    <mvc:view-controller path="/empeer" view-name="emp"></mvc:view-controller>
</beans>

controller类:

package com.openlab.controller;

import com.openlab.bean.Employee;
import com.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;
    //查看所有员工信息
    @RequestMapping (value = "/emp/{id}" ,method = RequestMethod.GET)
    @ResponseBody
    public Employee findemp(@PathVariable("id")Integer id){
        Employee emp=empDaoimpl.findByid(id);
        return emp;
    }
    @GetMapping ("/emp")
    @ResponseBody
    public  List<Employee> findall(){
        return empDaoimpl.findall();
    }
    @DeleteMapping("/emp/{id}")
    @ResponseBody
    public  String delete(@PathVariable("id")Integer id){//通过id删除
        empDaoimpl.delete(id);
        return "success";
    }
    @PostMapping("/emp")
    @ResponseBody
    public String save(Employee employee){//添加
        empDaoimpl.sava(employee);
        return "success";
    }
    @RequestMapping(value = "/emp",method = RequestMethod.PUT)
    @ResponseBody
    public String update(Employee employee){//更新
        empDaoimpl.update(employee);
        return "success";
    }

}

界面jsp文件:

<%--
  Created by IntelliJ IDEA.
  User: 11960
  Date: 2021/9/22
  Time: 18:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>


</head>
<body>
<div id="con">
  <table class="table table-striped " title="table">
      <tr>
          <td>员工编号</td>
          <td>员工姓名</td>
          <td>员工性别</td>
      </tr>
  </table>
</div>

<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal" title="add">
    添加
</button>
<!-- 模态框(Modal-->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel" >
                    添加
                </h4>
            </div>

            <div class="modal-body">
                <form class="form-group">
                    <div id="hid"  hidden="hidden">
                    <label  class="col-sm-2 control-label">员工ID</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" name="id" id="id">
                    </div>
                    </div>
                    <label  class="col-sm-2 control-label">员工姓名</label>
                   <div class="col-sm-10">
                       <input type="text" class="form-control" name="name" id="name">
                   </div>
                    <label  class="col-sm-2 control-label">员工性别</label>
                    <div class="col-sm-10">
                        <input type="radio"  name="sex" title="man"><input type="radio"  name="sex" title="female"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                </button>
                <button type="button" class="btn btn-primary" title="savechange">
                    提交更改
                </button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>




</body>
<script>
    $(function(){
   //获取数据并展示
            $.ajax({
                type:"GET",
                url:"${pageContext.request.contextPath}/emp",
                dataType:"json",
                success:function (jsonarr){
                    $(jsonarr).each(function (i,v){
                        var tr=$("<tr> <td>"+v.id+"</td> <td>"+v.name+"</td><td>"+v.sex+"</td><td> <input type='button' value='修改' title='update' class='btn btn-primary'/> <input type='button'  class='btn btn-info'   value='删除' title='delete'/></td> </tr>");
                        $("[title='table']").append(tr);//添加
                    })
                }
           })
        $("[title='add']").click(function (){
            $("#hid").hide();//隐藏id在模态框
         $(":input").not("[type='button']").val('');//恢复初始值
         $("[name='sex']").each(function (i,v){
             v.checked=false;
         })
        })
        $("#con").on('click','[title="update"]',function (){
            $("#hid").show();//显示id在模态框
            var id=$(this).parents("tr").find("td:first").html();
            $(this).attr("data-toggle","modal");//显示模态框
            $(this).attr("data-target","#myModal");
            $.ajax({
                type:"GET",
                url:"${pageContext.request.contextPath}/emp/"+id,
                dateStyle:"json",
                success:function (json){
                    $("#id").val(json.id);
                    $("#name").val(json.name);
                    if (json.sex=='男'){
                        $("[title='man']").get(0).checked=true;
                    }else{
                        $("[title='female']").get(0).checked=true;
                    }
                }
            })
        })
        $("[title='savechange']").click(function (){
            var  sex='男';
            if ($("[title='female']").get(0).checked){
                sex='女';
            }
            var id=$("#id").val();//获取id,如果是添加id就是null,修改idjiuyou值
            var  date="name="+$("#name").val()+"&sex="+sex;
            if (id==''){//若id为null就进行添加方法
                $.ajax({
                    type:"POST",
                    url:"${pageContext.request.contextPath}/emp",
                    data:date,
                    success:function (info){
                        if (info=='success'){//添加成功刷新一下
                            window.location.reload();
                        }
                    }
                })
            }else {
                $.ajax({
                    type:"POST",
                    //更新为put请求方法,所以我们在传数据时要将post请求更改为put请求用_method=PUT
                    url:"${pageContext.request.contextPath}/emp/",
                    data:"name="+$("#name").val()+"&sex="+sex+"&id="+id+"&_method=PUT",
                    success:function (info){
                        if (info=='success'){
                            $("#hid").hide();
                            window.location.reload();
                        }
                    }
                })

            }
            // var  date="name="+$("[name='name']").val()+"&sex="+sex;
           // alert(date);

            window.location.reload();
        })
        $("#con").on('click','[title="delete"]',function (){
            var id=$(this).parents("tr").find("td:first").html();//获取id值
            $.ajax({
                type:"DELETE",
                url:"${pageContext.request.contextPath}/emp/"+id,
                success:function (info){
                  if (info=='success'){
                      window.location.reload();
                  }
                }
            })

        })
        });
</script>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值