ssm整合实现简单的增删改查操作

前言: 最近学完ssm框架,拿来练练手,代码比较简单

首先导入maven坐标

<?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>com.huanan</groupId>
  <artifactId>student_ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <!--版本锁定-->
  <properties>
    <spring.version>5.0.2.RELEASE</spring.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>5.1.6</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
  </properties>
  
  <!--spring相关坐标-->
  <dependencies>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.8</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    
    <!--单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
    
     <!--数据库驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
     <!--servlet-api-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
    
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!--日志相关-->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

    <!--mybatis相关-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <!--连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.9</version>
    </dependency>

  </dependencies>
  <build>
    <finalName>student_ssm</finalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.2</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <encoding>UTF-8</encoding>
            <showWarnings>true</showWarnings>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

创建实体类student 并生成set和get方法

package com.huanan.domain;

import java.io.Serializable;

public class Student implements Serializable {
    private int id;
    private int studentId;
    private String name;

    public int getId() {
        return id;
    }

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

    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public String getName() {
        return name;
    }

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

创建applicationContext.xml文件整合mybatis和spring mvc

<?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:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        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.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
        <!--配置扫描service包-->
        <context:component-scan base-package="com.huanan.service"/>
        <!--配置连接池-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
                <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="1231"/>
        </bean>
        <!--整合mybatis-->
        <!--配置SqlSessionFactoryBean生成代理对象-->
        <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
                <property name="dataSource" ref="dataSource"/>
        </bean>

        <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
                <property name="sqlSessionFactory" ref="sessionFactory"/>
                <!--扫描dao包-->
                <property name="basePackage" value="com.huanan.dao"/>
        </bean>
        <!--开启事务支持-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                <property name="dataSource" ref="dataSource"/>
        </bean>

        <tx:advice id="txAdvice" transaction-manager="transactionManager">
                <tx:attributes>
                        <tx:method name="find*" read-only="true"/>
                        <tx:method name="*"/>
                </tx:attributes>
        </tx:advice>
        <!--增强-->
        <aop:config>
                <aop:advisor advice-ref="txAdvice" pointcut="execution(public * com.huanan.service.*ServiceImpl.*(..))"/>
        </aop:config>
</beans>

配置web.xml文件

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!--配置监听器-->
  <!--开启applicationContext.xml-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!--解决中文乱码问题-->
  <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>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</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>*.do</url-pattern>
  </servlet-mapping>
</web-app>

创建springmvc文件

<?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-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:component-scan base-package="com.huanan.controller"/>
    <!--视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <mvc:annotation-driven/>
</beans>

最后几步比较简单直接上代码了
controller层

package com.huanan.controller;

import com.huanan.domain.Student;
import com.huanan.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @RequestMapping("/addStudent.do")
    public ModelAndView addStudent(Student student){
        ModelAndView mv = new ModelAndView();
        studentService.addStudent(student);
        mv.setViewName("success");
        return mv;
    }
    @RequestMapping("/deleteStudent.do")
    public ModelAndView deleteStudent(int id){
        ModelAndView mv = new ModelAndView();
        studentService.deleteStudent(id);
        mv.setViewName("delete");
        return mv;
    }

    @RequestMapping("/updateStudent.do")
    public ModelAndView updataStudent(Student student){
        ModelAndView mv = new ModelAndView();
        studentService.updataStudent(student);
        mv.setViewName("update");
        return mv;
    }
    @RequestMapping("/findAllStudent.do")
    public ModelAndView findByIdStudent(){
        ModelAndView mv = new ModelAndView();
        List<Student> list = studentService.findAll();
        mv.addObject("student",list);
        mv.setViewName("findbyid");
        return mv;
    }
}

service层接口以及实现类

package com.huanan.controller;

import com.huanan.domain.Student;
import com.huanan.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @RequestMapping("/addStudent.do")
    public ModelAndView addStudent(Student student){
        ModelAndView mv = new ModelAndView();
        studentService.addStudent(student);
        mv.setViewName("success");
        return mv;
    }
    @RequestMapping("/deleteStudent.do")
    public ModelAndView deleteStudent(int id){
        ModelAndView mv = new ModelAndView();
        studentService.deleteStudent(id);
        mv.setViewName("delete");
        return mv;
    }

    @RequestMapping("/updateStudent.do")
    public ModelAndView updataStudent(Student student){
        ModelAndView mv = new ModelAndView();
        studentService.updataStudent(student);
        mv.setViewName("update");
        return mv;
    }
    @RequestMapping("/findAllStudent.do")
    public ModelAndView findByIdStudent(){
        ModelAndView mv = new ModelAndView();
        List<Student> list = studentService.findAll();
        mv.addObject("student",list);
        mv.setViewName("findbyid");
        return mv;
    }
}

package com.huanan.service;

import com.huanan.dao.StudentDao;
import com.huanan.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class StudentServiceImpl implements StudentService{

    @Autowired
    private StudentDao studentDao;


    @Override
    public void addStudent(Student student) {
        studentDao.addStudent(student);
    }

    @Override
    public void deleteStudent(int id) {
        studentDao.deleteStudent(id);
    }

    @Override
    public void updataStudent(Student student) {
        studentDao.updataStudent(student);
    }

    @Override
    public List<Student> findAll() {
        return studentDao.findAll();
    }

}

dao层接口

package com.huanan.dao;

import com.huanan.domain.Student;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface StudentDao {
    @Insert("insert into student (studentId,name) values(#{studentId},#{name})")
    void addStudent(Student student);

    @Delete("delete from student where id=#{id}")
    void deleteStudent(int id);

    @Update("update student set studentId=#{studentId},name=#{name} where id=#{id}")
    void updataStudent(Student student);

    @Select("select * from student")
    List<Student> findAll();
}

因为本人前端基础比较薄弱,所以就简简单单写了个首页页面用于测试

<%--
  Created by IntelliJ IDEA.
  User: lai
  Date: 2020/2/27
  Time: 16:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
</head>
<body>
    <h3>添加操作</h3>
    <form action="/student/addStudent.do" method="post">
        学号:<input type="text" name="studentId" /><br/>
        姓名:<input type="text" name="name" /><br/>
        <input type="submit" value="保存"/><br/>
    </form>
    <h3>删除</h3><br/>
    <form action="/student/deleteStudent.do" method="post">
        ID为:<input type="text" name="id"/><br/>
        <input type="submit" value="删除"/><br/>
    </form>
    <h3>修改</h3><br/>
    <form action="/student/updateStudent.do" method="post">
        请输入修改的ID: <input type="text" name="id"/><br/>
        请输入修改的学号:<input type="text" name="studentId"/><br/>
        请输入修改的姓名:<input type="text" name="name"/><br/>
        <input type="submit" value="修改"/><br/>
    </form>
    <h3>查询</h3>
    <form action="/student/findAllStudent.do" method="post">
        <input type="submit" value="查询所有"/>
    </form>
</body>
</html>

四个跳转页面我就不写了

总结:算是ssm整合入门的一小步了,自知还有很多不足,望各位多多指教
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值