IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> SSM整合小项目 -> 正文阅读

[Java知识库]SSM整合小项目

目录

案例:实现查询所有学生和添加学生

SSM整合

创建父工程

创建dao子工程

创建service子工程

创建controller子工程


?

案例:实现查询所有学生和添加学生

SSM整合

案例需要使用以下技术:

  • 使用Maven创建聚合工程,并使用Maven的tomcat插件运行工程
  • 使用Spring的IOC容器管理对象
  • 使用MyBatis操作数据库
  • 使用Spring的声明式事务进行事务管理
  • 使用SpringMVC作为控制器封装Model并跳转到JSP页面展示数据
  • 使用Junit测试方法
  • 使用Log4j在控制台打印日志Sy

案例的编写流程如下:

  1. 创建maven父工程,添加需要的依赖和插件
  2. 创建dao子工程,配置MyBatis操作数据库,配置Log4j在控制台打印日志。
  3. 创建service子工程,配置Spring声明式事务
  4. 创建controller子工程,配置SpringMVC作为控制器,编写JSP页面展示数据。
  5. 每个子工程都使用Spring进行IOC管理

创建父工程

创建maven父工程,添加需要的依赖和插件

<properties>
  <!--Spring版本-->
  <spring.version>5.2.12.RELEASE</spring.version>
</properties>


<dependencies>
  <!-- mybatis -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.7</version>
  </dependency>
  <!-- mysql驱动 -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.26</version>
  </dependency>
  <!--  druid连接池  -->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.8</version>
  </dependency>
  <!-- MyBatis与Spring的整合包-->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.6</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <!-- springmvc -->
  <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-tx</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.7</version>
  </dependency>
  <!-- jstl -->
  <dependency>
    <groupId>org.apache.taglibs</groupId>
    <artifactId>taglibs-standard-spec</artifactId>
    <version>1.2.5</version>
  </dependency>
  <dependency>
    <groupId>org.apache.taglibs</groupId>
    <artifactId>taglibs-standard-impl</artifactId>
    <version>1.2.5</version>
  </dependency>
  <!-- servlet -->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
  </dependency>
  <!-- jsp -->
  <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
  </dependency>
  <!-- junit -->
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <!-- log4j -->
  <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.12</version>
  </dependency>
</dependencies>


<build>
  <plugins>
    <!-- tomcat插件 -->
    <plugin>
      <groupId>org.apache.tomcat.maven</groupId>
      <artifactId>tomcat7-maven-plugin</artifactId>
      <version>2.1</version>
      <configuration>
        <port>8080</port>
        <path>/</path>
        <uriEncoding>UTF-8</uriEncoding>
        <server>tomcat7</server>
        <systemProperties>
          <java.util.logging.SimpleFormatter.format>%1$tH:%1$tM:%1$tS %2$s%n%4$s: %5$s%6$s%n
          </java.util.logging.SimpleFormatter.format>
        </systemProperties>
      </configuration>
    </plugin>
  </plugins>
</build>

?

创建dao子工程

1、编写实体类和持久层接口

2、编写MyBatis核心配置文件

3、编写Spring核心配置文件,配置数据源、SqlSessionFactoryBean、扫描包对象

4、测试

编写实体类

package com.itbaizhan.pojo;

public class Student {
    private Integer id;
    private String name;
    private String sex;
    private String address;

    public Student(Integer id, String name, String sex, String address) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.address = address;
    }



    public Student() {
    }

    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 String getSex() {
        return sex;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

编写持久层接口

package com.itbaizhan.dao;

import com.itbaizhan.pojo.Student;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface StudentDao {

    //查询所有学生
    @Select("select * from student")
    List<Student> findAll();

    //新增学生
    @Insert("insert into student values(null,#{name},#{sex},#{address})")
    void add(Student student);
}

?编写log4j.properties配置文件(打印日志的)

log4j.rootCategory=debug, CONSOLE, LOGFILE


log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE


log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%d{MM/dd HH:mm:ss}] %-6r [%15.15t] %-5p %30.30c %x - %m\n

编写数据库配置文件druid.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///student
jdbc.username=root
jdbc.password=root

编写MyBatis配置文件SqlMapConfig.xml?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>

?

编写Spring配置文件applicationContext-dao.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:context="http://www.springframework.org/schema/context"
    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">
  <!-- 读取数据库配置文件  -->
  <context:property-placeholder location="classpath:druid.properties"></context:property-placeholder>


  <!--  配置数据源  -->
  <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}"></property>
    <property name="url" value="${jdbc.url}"></property>
    <property name="username" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>
  </bean>


  <!--  SqlSessionFactory  -->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
  </bean>


  <!-- 配置扫描包对象,为包下的接口创建代理对象  -->
  <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.itbaizhan.dao"></property>
  </bean>
</beans>

?

测试持久层接口的方法?

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application-dao.xml")
public class TestStudentDao {

    @Autowired
    private StudentDao studentDao;

    @Test
    public void t1(){
        List<Student> all = studentDao.findAll();
        all.forEach(System.out::println);
    }

    @Test
    public void t2(){
        studentDao.add(new Student("一拳超人","男","网络"));
    }
}

运行t1,查询所有学生(t2已经运行过了,所以查询时有了)

?

?

创建service子工程

1、编写服务层方法

2、创建spring核心配置文件,配置事务

?编写服务层方法

@Service
public class StudentService {

    @Autowired
    private StudentDao studentDao;


    //查询所有学生
    public List<Student> findAllStudent(){
        return studentDao.findAll();
    }

    //添加学生
    public void addStudent(Student student){
        studentDao.add(student);
    }
}

创建spring核心配置文件,配置事务

<?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">

    <!--  扫描包,使注解生效  -->
    <context:component-scan base-package="com.itbaizhan"></context:component-scan>

    <!--  事务管理器  -->
    <bean id="transaction" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--  通知  -->
    <tx:advice id="txAdvice" transaction-manager="transaction">
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!--  切面  -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.itbaizhan.service.*.*(..))"
    </aop:config>
</beans>

?

创建controller子工程

1、编写控制器

2、编写springmvc核心配置文件,配置视图解析器

3、编写web.xml文件,配置前端控制器、字符编码过滤器

4、编写jsp文件

编写控制器


@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    //查询所有学生
    @RequestMapping("/allStudent")
    public String allStudent(HttpServletRequest req){
        req.setAttribute("students",studentService.findAllStudent());
        return "student";
    }

    //新增学生
    @RequestMapping("/addStudent")
    public String addStudent(Student student){
        studentService.addStudent(student);
        return "redirect:/allStudent";
    }
}

?编写springmvc核心配置文件,配置视图解析器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">


    <!-- 扫描Controller包,使注解生效 -->
    <context:component-scan base-package="com.itbaizhan"/>


    <!-- 配置视图解析器 -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!-- 开启SpringMVC注解的支持 -->
    <mvc:annotation-driven/>
    <!-- 放行静态资源 -->
    <mvc:default-servlet-handler />
</beans>

编写web.xml文件,配置前端控制器,编码过滤器

在传递参数时,tomcat8以上能处理get请求的中文乱码,但不能处理post请求的中文乱码

<!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>



  <!--编码过滤器-->
  <filter>
    <filter-name>encFilter</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>encFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- 创建spring容器的监听器 -->
  <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>


  <!--前端控制器-->
  <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>/</url-pattern>
  </servlet-mapping>


</web-app>

编写jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>学生</title>
</head>
<body>
    <form action="/addStudent" method="post">
        姓名:<input name="name">
        性别:<input name="sex">
        地址:<input name="address">
        <input type="submit" value="提交">
    </form>
    <br/>
    <table width="500" cellspacing="0" cellpadding="0" border="1" align="center">
        <tr>
            <th>id</th>
            <th>姓名</th>
            <th>性别</th>
            <th>地址</th>
        </tr>
        <c:forEach items="${requestScope.students}" var="student">
            <tr>
                <td>${student.id}</td>
                <td>${student.name}</td>
                <td>${student.sex}</td>
                <td>${student.address}</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

?启动tomcat,运行父工程,访问allStudent方法路径

?测试添加Student

?

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-10-31 11:40:47  更:2022-10-31 11:45:15 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/19 8:18:59-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码