SpringMVC实现数据库的增删改查

使用SpringMVC实现数据库的增删改查,配合jQuery技术

      • 提醒:本项目是在IDEA下的Maven工程中构建的,所以需要提前配置好maven,配置maven的详细过程可以参考我的另一篇文章
    • 必要准备

提醒:本项目是在IDEA下的Maven工程中构建的,所以需要提前配置好maven,配置maven的详细过程可以参考我的另一篇文章

必要准备

  1. 添加springmvc.xml
    1、在main下创建文件夹resources,并将其转化为resources root
    2、在此文件夹中创建file 命名为springmvc.xml 并将一下代码复制进去



    
    
    
    
    
    
    
        
        
        
        
    


需要注意这里,如果包的结构很深入com.ssd.controller,则需要把下面这里对应修改
SpringMVC实现数据库的增删改查_第1张图片
2. 配置pom.xml文件
SpringMVC实现数据库的增删改查_第2张图片在中添加一下依赖

//springmvc依赖


      org.springframework
      spring-context
      ${spring-version}
    
    
      org.springframework
      spring-beans
      ${spring-version}
    
    
      org.springframework
      spring-core
      ${spring-version}
    
    
      org.springframework
      spring-web
      ${spring-version}
    
    
      org.springframework
      spring-webmvc
      ${spring-version}
    

//数据库和jQuery依赖


          mysql
          mysql-connector-java
          5.1.47
      

      org.webjars
      jquery
      1.11.1
    
  1. 修改web.xml文件
    //替换为一下代码


  
  
    springMvc
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath:springmvc.xml
    
    1
  
  
    springMvc
    /
  
  
    characterEncodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
      encoding
      UTF-8
    
    
      forceEncoding
      true
    
  
  
    characterEncodingFilter
    /*
  


  1. 前端页面
    emp2.jsp、add.jsp、update.jsp

emp2.jsp代码:

<%@ page import="entity.Employee" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>



    
    无标题文档
    
    //引入jquery的两句代码
    
    

    
    




<%List list = (List) request.getAttribute("list");%>
<%for (int i = 0; i < list.size();i++){%> <%}%>
id 姓名 性别 年龄 操作
<%=list.get(i).getId()%> <%=list.get(i).getName()%> <%=list.get(i).getGender()%> <%=list.get(i).getAge()%>

add.jsp

<%@ page import="entity.Employee" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>



    
    无标题文档
    
    //引入jquery的两句代码
    
    

    
    




<%List list = (List) request.getAttribute("list");%>
<%for (int i = 0; i < list.size();i++){%> <%}%>
id 姓名 性别 年龄 操作
<%=list.get(i).getId()%> <%=list.get(i).getName()%> <%=list.get(i).getGender()%> <%=list.get(i).getAge()%>

update.jsp

<%@ page import="entity.Employee" %><%--
  Created by IntelliJ IDEA.
  User: GoldBech
  Date: 2019/12/30
  Time: 13:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8"%>



    
    无标题文档
    
    
    




<%Employee emp = (Employee)request.getAttribute("emp");%>

需要注意把这些页面都放在WEB-INF下:
SpringMVC实现数据库的增删改查_第3张图片
实体类对象代码:

package entity;

public class Employee {
    private int id;
    private String name;
    private String gender;
    private int age;

    public Employee(){

    }
    public Employee(String name,String gender, int age){
        this.name = name;
        this.gender = gender;
        this.age = age;
    }
    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 getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

//dao层的代码

package dao;

import entity.Employee;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class EmployeeDao {

    //数据库连接方法
    public Connection getConnection() throws ClassNotFoundException, SQLException {
        String url = "jdbc:mysql://localhost/employees?useSSL=FALSE&serverTimezone=UTC&characterEncoding=utf8";
        String user = "root";
        String password = "password";
        String driver = "com.mysql.jdbc.Driver";
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }

    //数据库关闭方法
    public void closeAll(Connection conn, Statement state, ResultSet resultSet ){
        try {

            if (conn != null) {
                conn.close();
            }
            if (state != null) {
                state.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //查出所有的员工
    public List search() {

        List list = new ArrayList<>();

        Connection conn = null;
        Statement state = null;
        ResultSet resultSet = null;
        try {
            //加载驱动
            conn = getConnection();
            state = conn.createStatement();
            resultSet = state.executeQuery("select * from employee");
            while (resultSet.next()) {
                Employee employee = new Employee();
                employee.setId(resultSet.getInt(1));
                employee.setName(resultSet.getString(2));
                employee.setGender(resultSet.getString(3));
                employee.setAge(resultSet.getInt(4));
                list.add(employee);
            }
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
           closeAll(conn,state,resultSet);
        }
        return list;
    }

    //查找需要修改的员工
    public Employee search(int id) {

        Employee emp = null;
        Connection conn = null;
        PreparedStatement state = null;
        ResultSet resultSet = null;
        try {
            //加载驱动
            conn = getConnection();
            String sql = "select * from employee where id = ?";
            state = conn.prepareStatement(sql);
            state.setInt(1,id);
            resultSet = state.executeQuery();
            while (resultSet.next()) {
                 emp = new Employee();
                emp.setId(resultSet.getInt(1));
                emp.setName(resultSet.getString(2));
                emp.setGender(resultSet.getString(3));
                emp.setAge(resultSet.getInt(4));
            }
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(conn,state,resultSet);
        }
        return emp;
    }


    //判断是否添加成功
    public boolean add(Employee emp){
        Connection conn = null;
        Statement state = null;
        int resultSet = 0;
        try {
            //加载驱动
            conn = getConnection();
            state = conn.createStatement();
            String sqlInsert = "insert into employee(name, gender,age) values ('"+emp.getName()+"','"+emp.getGender()+"',"+emp.getAge()+")";
            resultSet = state.executeUpdate(sqlInsert);
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(conn,state,null);
        }
        return resultSet > 0;
    }

    //判断是否修改成功
    public boolean update(Employee emp){
        Connection conn = null;
        PreparedStatement state = null;
        int resultSet = 0;
        try {
            //加载驱动
            conn = getConnection();
            String sqlAlter = "update employee set name=?,gender=?,age=? where id = ? ";
            state = conn.prepareStatement(sqlAlter);
            state.setString(1,emp.getName());
            state.setString(2,emp.getGender());
            state.setInt(3,emp.getAge());
            state.setInt(4,emp.getId());
            resultSet = state.executeUpdate();
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(conn,state,null);
        }
        return resultSet > 0;
    }

    public boolean delete(int id) {

        Connection conn = null;
        PreparedStatement state = null;
        int resultSet = 0;
        try {
            //加载驱动
            conn = getConnection();
            String sqlAlter = "delete from employee where id = ? ";
            state = conn.prepareStatement(sqlAlter);
            state.setInt(1,id);
            resultSet = state.executeUpdate();
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(conn,state,null);
        }
        return resultSet > 0;

    }
}

//controller层代码
package controller;

import dao.EmployeeDao;
import entity.Employee;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping(“emp”)
public class EmployeeController {

@RequestMapping("search")
public ModelAndView search(){
    EmployeeDao empDao = new EmployeeDao();
    List list = empDao.search();
    ModelAndView mv = new ModelAndView("emp2");
    mv.addObject("list",list);
    return mv;
}


@RequestMapping("showAdd")
public String showAdd(){
    return "add";
}

@RequestMapping("add")
public String add(Employee emp){
        EmployeeDao empDao = new EmployeeDao();
    boolean flag = empDao.add(emp);
    return "redirect:search";

}

@RequestMapping("showUpdate")
public ModelAndView showUpdate(int id){
    EmployeeDao empDao = new EmployeeDao();
    Employee emp = empDao.search(id);
    ModelAndView mv = new ModelAndView("update");
    mv.addObject("emp",emp);
    return mv;
}

@RequestMapping("update")
public String update(Employee emp){
    EmployeeDao empDao = new EmployeeDao();
    boolean flag = empDao.update(emp);
    return "redirect:search";
}

@RequestMapping("delete")
public String delete(int id){
    EmployeeDao empDao = new EmployeeDao();
    empDao.delete(id);
    return "redirect:search";
}
}

运行效果:
SpringMVC实现数据库的增删改查_第4张图片SpringMVC实现数据库的增删改查_第5张图片SpringMVC实现数据库的增删改查_第6张图片SpringMVC实现数据库的增删改查_第7张图片SpringMVC实现数据库的增删改查_第8张图片

你可能感兴趣的:(框架)