【提供源码】ssm+maven+jsp 项目对数据库简单curd案例

文章目录

    • 项目概要
    • 项目条件
    • 步骤:
      • 1.在数据库创建表
      • 2. 创建web项目
      • 3.项目目录结构
      • 4. 在pom.xml文件里添加依赖
      • 5. 写其他配置文件
      • 6. 分层写代码
      • 7. jsp展示数据
      • 8. 补充
      • 9. 运行
      • 10. 项目源码

项目概要

主要做对数据的增删改查操作

项目条件

框架:spring+springMVC+Mybatis
项目管理工具:Maven
代码编写工具:IntelliJ IDEA 2020.1 x64
数据库:MySQL
数据库工具:Navicat Premium

步骤:

1.在数据库创建表

创建表的 sql


CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(10) DEFAULT NULL,
  `age` int(5) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

2. 创建web项目

选择新建项目,在Maven里选择web项目,填写项目名和包名
【提供源码】ssm+maven+jsp 项目对数据库简单curd案例_第1张图片
【提供源码】ssm+maven+jsp 项目对数据库简单curd案例_第2张图片

3.项目目录结构

首次建项目加载比较慢,需要稍等下

查看总项目结构如下:
【提供源码】ssm+maven+jsp 项目对数据库简单curd案例_第3张图片

4. 在pom.xml文件里添加依赖

在pom.xml文件里添加依赖



<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.0modelVersion>

  <groupId>com.tmm.testgroupId>
  <artifactId>MyTestartifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>warpackaging> 

  
  <repositories>
    <repository>
      <id>aliid>
      <url>http://maven.aliyun.com/nexus/content/groups/publicurl>
    repository>
  repositories>

  
  <build>
    <resources>
      <resource>
        <directory>src/main/javadirectory>
        <includes>
          <include>**/*.xmlinclude>
        includes>
        <filtering>falsefiltering>
      resource>
    resources>
  build>

  
  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.7maven.compiler.source>
    <maven.compiler.target>1.7maven.compiler.target>
    <spring.version>4.1.6.RELEASEspring.version>
    <mybatis.version>3.3.1mybatis.version>
  properties>


  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>3.8.2version>
      <scope>testscope>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-coreartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-oxmartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aopartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-context-supportartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${spring.version}version>
    dependency>

    
    <dependency>
      <groupId>org.codehaus.jacksongroupId>
      <artifactId>jackson-mapper-aslartifactId>
      <version>1.9.13version>
    dependency>

    
    <dependency>
      <groupId>commons-fileuploadgroupId>
      <artifactId>commons-fileuploadartifactId>
      <version>1.3.1version>
    dependency>
    <dependency>
      <groupId>commons-iogroupId>
      <artifactId>commons-ioartifactId>
      <version>1.4version>
    dependency>
    <dependency>
      <groupId>commons-codecgroupId>
      <artifactId>commons-codecartifactId>
      <version>1.3version>
    dependency>

    <dependency>
      <groupId>com.github.sgroschupfgroupId>
      <artifactId>zkclientartifactId>
      <version>0.1version>
    dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-coreartifactId>
      <version>2.5.1version>

    dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-annotationsartifactId>
      <version>2.5.0version>
    dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
      <version>2.4.0version>
    dependency>

    <dependency>
      <groupId>javaxgroupId>
      <artifactId>javaee-apiartifactId>
      <version>7.0version>
    dependency>

    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>${mybatis.version}version>
    dependency>
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.1version>
    dependency>

    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.8version>
    dependency>
    <dependency>
      <groupId>commons-dbcpgroupId>
      <artifactId>commons-dbcpartifactId>
      <version>1.2.2version>
    dependency>

    
    <dependency>
      <groupId>jstlgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>
    <dependency>
      <groupId>taglibsgroupId>
      <artifactId>standardartifactId>
      <version>1.1.2version>
    dependency>
  dependencies>
project>

5. 写其他配置文件

首先在 mian 目录下,右键新建 resources 文件夹,确保是资源文件
在 resources 文件夹里新建两个xml文件(spring.xml,spring-mvc.xml),和一个配置文件(jdbc.properties)
配置四个xml文件 jdbc.properties,spring.xml,spring-mvc.xml,web.xml

代码:
jdbc.properties


driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\:///test?useUnicode=xxx&characterEncoding=UTF-8 #自己的数据库名称
username=root
password=xxx #自己的数据库密码

#定义初始连接数
initialSize=0  

#定义最大连接数
maxActive=20  

#定义最大空闲
maxIdle=20  

#定义最小空闲
minIdle=1

#定义最长等待时间
maxWait=60000 

spring.xml



<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-4.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <context:annotation-config />

    
    <context:component-scan base-package="com.tmm.test">context:component-scan>


    
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"/>
    bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />

        
        <property name="initialSize" value="${initialSize}">property>
        
        <property name="maxActive" value="${maxActive}">property>
        
        <property name="maxIdle" value="${maxIdle}">property>
        
        <property name="minIdle" value="${minIdle}">property>
        
        <property name="maxWait" value="${maxWait}">property>
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.tmm.test.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    bean>

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    bean>

beans>

spring-mvc.xml



<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-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    
    <context:component-scan base-package="com.tmm.test.controller"/>

    <mvc:default-servlet-handler />

    
    <mvc:annotation-driven >
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter" >
                
                    <list>
                        <value>application/json;charset=utf-8value>
                        <value>text/html;charset=utf-8value>
                        
                        <value>application/x-www-form-urlencodedvalue>
                    list>
                property>
            bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" >bean>
        mvc:message-converters>
    mvc:annotation-driven>

    
    <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8value>
            list>
        property>
    bean>

    
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter"/>
            list>
        property>
    bean>

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property name="suffix" value=".jsp"/>
        <property name="prefix" value="/"/>

    bean>

    
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        
        <property name="defaultEncoding" value="utf-8"/>
        
        <property name="maxUploadSize" value="10485760000"/>
        
        <property name="maxInMemorySize" value="40960"/>
    bean>
beans>

web.xml




<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

  <display-name>Archetype Created Web Applicationdisplay-name>

  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:spring.xmlparam-value>
  context-param>

  
  <filter>
    <filter-name>encodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      <param-name>encodingparam-name>
            <param-value>UTF-8param-value>

    init-param>
  filter>

  <filter-mapping>
    <filter-name>encodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
  
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
  listener>

  
  <servlet>
    <servlet-name>SpringMVCservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:spring-mvc.xmlparam-value>
    init-param>

    <load-on-startup>1load-on-startup>
    
    <async-supported>trueasync-supported>
  servlet>

  <servlet-mapping>
    <servlet-name>SpringMVCservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>


  <welcome-file-list>
    <welcome-file>index.jspwelcome-file>
  welcome-file-list>
web-app>

6. 分层写代码

在mian下新建包com.tmm.test,在此包下分别新建四个包:

① 新建 entity 包,entity包下再新建实体类 Student
在实体类里将 无参构造函数,有参构造函数,setget方法,toString方法自动生成出来


package com.tmm.test.entity;
import java.io.Serializable;

public class Student implements Serializable {
     
    private Integer id;
    private String name;
    private Integer age;

    //无参构造函数
    public Student() {
     
    }

    //有参构造函数
    public Student(Integer id, String name, Integer age) {
     
        this.id = id;
        this.name = name;
        this.age = age;
    }

    //toString方法
    @Override
    public String toString() {
     
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Integer getId() {
     
        return id;
    }

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

    public String getName() {
     
        return name;
    }

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

    public Integer getAge() {
     
        return age;
    }

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

② 新建 mapper包,mapper包下新建 StudentMapper类
StudentMapper是一接口,用来写增删改查的方法


package com.tmm.test.mapper;
import com.tmm.test.entity.Student;
import java.util.List;

public interface StudentMapper {
     
    //查询所有数据
    List<Student> selectAll();

    //根据id删除
    int  delete(int id);

    //根据id修改
    int update(Student student);

    //添加
    int insert(Student student);

    //通过id查找
    Student findById(int id);
}

③ 在mapper包下新建xml文件 StudentMapper.xml
StudentMapper.xml 是mybatis的映射文件。





<mapper namespace="com.tmm.test.mapper.StudentMapper">

    <resultMap id="BaseResultMap" type="com.tmm.test.entity.Student">
        
        <result column="id" jdbcType="INTEGER" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="age" jdbcType="INTEGER" property="age" />
    resultMap>

    <parameterMap type="com.tmm.test.entity.Student" id="StudentMap">
        <parameter  property="name" resultMap="BaseResultMap"/>
        <parameter  property="age" resultMap="BaseResultMap"/>
    parameterMap>

    <sql id="Base_Column_List">
          id,name,age
    sql>

    
    <select id="selectAll" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from student
    select>

    
    <select id="findById" resultType="com.tmm.test.entity.Student">
       select
        <include refid="Base_Column_List" />
       from student where id =#{id}
    select>

    
    <delete id="delete" parameterType="int">
        delete from student where id =#{id}
    delete>

    
    <update id="update" parameterMap="StudentMap">
        update student set name=#{name},age=#{age} where id=#{id}
    update>

    
    <insert id="insert"  parameterMap="StudentMap">
        insert into student(name,age) values(#{name},#{age})
    insert>

mapper>

④ 新建 service,在 service包下新建StudentService类
StudentService是一接口


package com.tmm.test.service;

import com.tmm.test.entity.Student;

import java.util.List;

public interface StudentService {
     
    //查询所有数据
    public List<Student> selectAll();

    //根据id删除
    public int  delete(int id);

    //根据id修改
    public int update(Student student);

    //添加
    public int insert(Student student);

    //通过id查找
    public Student findById(int id);
}

⑤ 在 service包下,新建 impl包,包里新建 StudentServiceIml
StudentServiceIml 是StudentService类的实现类


package com.tmm.test.service.impl;

import com.tmm.test.entity.Student;
import com.tmm.test.mapper.StudentMapper;
import com.tmm.test.service.StudentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

@Service("studentService")
public class StudentServiceIml implements StudentService {
     

    @Resource
    private StudentMapper studentMapper;

    @Override
    public List<Student> selectAll() {
     
        return studentMapper.selectAll();
    }

    @Override
    public int delete(int id) {
     
        return studentMapper.delete(id);
    }

    @Override
    public int update(Student student) {
     
        return studentMapper.update(student);
    }

    @Override
    public int insert(Student student) {
     
        return studentMapper.insert(student);
    }

    @Override
    public Student findById(int id) {
     
        return studentMapper.findById(id);
    }
}

⑥ 新建 controller包,包里新建 StudentController类


package com.tmm.test.controller;

import com.tmm.test.entity.Student;
import com.tmm.test.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {
     

    @Autowired
    private StudentService studentService;

    /**
     * 查询
     * @param model
     * @return
     */
    @RequestMapping("/select")
    public String list(Model model){
     
        List<Student> student=studentService.selectAll();
        model.addAttribute("student", student);
        return "/show";
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable int id){
      //@PathVariable 映射 URL 绑定的占位符
        int count = studentService.delete(id);
        System.out.println("count:"+count);
        return "redirect:/student/select";
    }

    /**
     * 新增
     * @param student
     * @return
     */
    @RequestMapping("/insert")
    public String insert(Student student){
     
        studentService.insert(student);
        return "redirect:/student/select";
    }

    /**
     * 跳转修改页面,需要先通过id查找到此条数据
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/toUpdate/{id}")
    public String findById(Model model, @PathVariable int id){
     
        Student student = studentService.findById(id);
        model.addAttribute("s",student);//通过id查找到此条数据
        return "/update"; //update.jsp页面
    }
    
	/**
     * 修改
     * @param student
     * @return
     */
    @RequestMapping("/update")
    public String update(Student student){
     
        studentService.update(student);
        return "redirect:/student/select";
    }
}

7. jsp展示数据

main目录下,新建 webapp文件夹,webapp下,新建四个jsp页面
index.jsp — 主页面


<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<html>
<head>
    <title>查看表格title>
head>
<body>
<div style="margin:0 auto;width:250px;height:50px;">
    <button onclick="window.open('${pageContext.request.contextPath }/student/select');">查看表格button>
div>
body>
html>

show.jsp —数据展示页面


<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
    <div align=center>
        <table border=1 cellpadding=0 cellspacing=0 style='height:40px;width:250px;margin-bottom: 20px;'>
            <tr>
                <th>姓名th>
                <th>年纪th>
                <th>操作th>
            tr>
            <c:forEach items="${student}" var="student">
                <tr style="text-align:center">
                    <td>${student.name}td>
                    <td>${student.age}td>
                    <td>
                        <a href="${pageContext.request.contextPath }/student/delete/${student.id}">删除a>
                        <a href="${pageContext.request.contextPath }/student/toUpdate/${student.id}">修改a>
                    td>
                tr>
            c:forEach>
        table>
        <button onclick="window.open('${pageContext.request.contextPath }/add.jsp');">新增button>
    div>
body>
html>

③ add.jsp — 新增页面


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>新建数据title>
head>
<body>
    <form action="student/insert" method="post">
        姓名:<input type="text" name="name"/><br/>
        年龄:<input type="text" name="age"/><br/>
        <input type="submit"/>
    form>
body>
html>

update.jsp —修改页面


<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<%--isELIgnored="false" 表示使用el表达式--%>
<html>
<head>
    <title>数据修改title>
head>
<body>
    <div>
        <form action="${pageContext.request.contextPath }/student/update" method="post">
                 <input type="hidden" name="id" value="${s.id}"> 
            姓名:<input type="text" name="name" value="${s.name}"/><br/>
            年龄:<input type="text" name="age" value="${s.age}"/><br/>
                 <input type="submit" value="提交">
        form>
    div>
body>
html>

8. 补充

注意:
若要修改整个项目的包名,以下几个地方是需要修改的

jdbc.properties文件里的配置修改成自己数据库的
包括数据库名和密码

spring.xml文件里的配置
下面两个地方包名修改成自己项目的

<context:component-scan base-package="com.tmm.test"></context:component-scan>
<property name="basePackage" value="com.tmm.test.mapper"/>

spring-mvc.xml文件里的配置
包名修改成自己的

<context:component-scan base-package="com.tmm.test.controller"/>

StudentMapper.xml文件里的配置
下面两个地方包名修改成自己项目的

<mapper namespace="com.tmm.test.mapper.StudentMapper"> <!--这个是mapper文件-->
<resultMap id="BaseResultMap" type="com.tmm.test.entity.Student"> <!--这个是实体文件-->

9. 运行

配置Tomcat服务器,按图操作

【提供源码】ssm+maven+jsp 项目对数据库简单curd案例_第4张图片
同一页面,继续操作

【提供源码】ssm+maven+jsp 项目对数据库简单curd案例_第5张图片
配置war包
【提供源码】ssm+maven+jsp 项目对数据库简单curd案例_第6张图片

点击右上角的绿色箭头按钮,就会跳到之前配置的浏览器页面。

10. 项目源码

GitHub地址:点击这里
码云地址:点击这里

完毕~

你可能感兴趣的:(ssm+maven,spring,java)