SSM框架的搭建与使用
SSM(Spring+SpringMVC+MyBatis)框架集由Spring、MyBatis两个开源框架整合而成(SpringMVC是Spring中的部分内容)。常作为数据源较简单的web项目的框架。
Spring
Spring就像是整个项目中装配bean的大工厂,在配置文件中可以指定使用特定的参数去调用实体类的构造方法来实例化对象。也可以称之为项目中的粘合剂。
Spring的核心思想是IoC(控制反转),即不再需要程序员去显式地new
一个对象,而是让Spring框架帮你来完成这一切。
SpringMVC
SpringMVC在项目中拦截用户请求,它的核心Servlet即DispatcherServlet承担中介或是前台这样的职责,将用户请求通过HandlerMapping去匹配Controller,Controller就是具体对应请求所执行的操作。SpringMVC相当于SSH框架中struts。
mybatis
mybatis是对jdbc的封装,它让数据库底层操作变的透明。mybatis的操作都是围绕一个sqlSessionFactory实例展开的。mybatis通过配置文件关联到各实体类的Mapper文件,Mapper文件中配置了每个类对数据库所需进行的sql语句映射。在每次与数据库交互时,通过sqlSessionFactory拿到一个sqlSession,再执行sql命令。
页面发送请求给控制器,控制器调用业务层处理逻辑,逻辑层向持久层发送请求,持久层与数据库交互,后将结果返回给业务层,业务层将处理逻辑发送给控制器,控制器再调用视图展现数据。
SSM框架的搭建
事前准备好Maven并配置好环境变量,在maven的参数设置中将源镜像修改为阿里云以加快下载外部jar包的速度。
点击IDEA中左上角的Files-New-Project,选择新建一个maven项目,选择…archetype-webapp选项,根据自己的喜好填写GroupId和ArtifactId,一路下一步即可建好。
完成创建后,项目文件有如下内容:
SSM框架的使用
第一次创建maven项目会根据pom.xml文件自动下载并导入外部jar包,需等待一点时间,当输出“Bulid Success”表明项目创建成功,然后需要我们手动创建一些需要的文件:在src/main目录下新建Directory:“java”,并将其设置为“Source Root”(即:此项目默认的代码文件源目录);在刚才新建的java文件下新建“com.zhonruan”包,再在com包下新建四个包,分别命名为:bean,service,dao,controller。新建的四个包:pojo,service,dao,controller,其所存放的分别是:
- bean:
存放自定义的java类。如:paper类,user类,book类等,每个类的属性设为private,并提供public属性的getter/setter方法让外界访问 - dao:定义接口,包含与数据库进行交互的功能。
- service:定义接口,包含系统所提供的功能。(之后还会在service包下再新建impl包)。
- controller:控制器,负责接收页面请求,转发和处理。
新建一个resources文件夹并设为资源文件源目录,在resource包下新建Directory:“mapper”(用于存放xxxMapper.xml文件),新建文件:“db.properties”(mysql数据库配置文件),”log4j.properties”(日志输出配置文件),”applicationContext.xml”(application配置文件),spring-mvc.xml四个文件。内容可以自行导入。
在web-inf目录下新建“jsp”包,存放xxx.jsp显示界面,内部可自行导入web前端页面文件。配置完成的文件结够如图:
将pom.xml文件修改:
<?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</groupId>
<artifactId>day04</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>day04 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!-- spring版本号 -->
<spring.version>5.0.2.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.6</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<c3p0.version>0.9.5.2</c3p0.version>
<taglibs.version>1.1.2</taglibs.version>
</properties>
<dependencies>
<!-- spring核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-oxm</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>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- 导入java ee jar 包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- 导入Mysql数据库链接jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- JSTL标签类 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 数据连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${taglibs.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>
<!-- 导入servlet-api/jsp -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>day04</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
然后开始创建maven项目的java文件,首先在bean包中新建一个UserInfo.class文件,用于实现用户信息类,内容如下:
package com.zhongruan.bean;
public class UserInfo {
private int id;
private String username;
private String password;
@Override
public String toString() {
return "UserInfo{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
在dao包中创建一个UserDao名称的接口文件,写入函数:
package com.zhongruan.dao;
import com.zhongruan.bean.UserInfo;
import java.util.List;
public interface UserDao {
public List<UserInfo> findAll();
public int addUser(UserInfo userInfo);
public int delUser(long id);
public int updateUser(UserInfo userInfo);
public UserInfo queryById(long id);
}
此接口的实现在mapper文件夹下的UserMapper.xml文件中,内容为:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zhongruan.dao.UserDao" >
<select id="findAll" resultType="com.zhongruan.bean.UserInfo">
select * from userinfo;
</select>
<insert id="addUser" parameterType="UserInfo">
insert into userinfo (id,username,password) values (#{id},#{username},#{password});
</insert>
<delete id="delUser" parameterType="long">
DELETE FROM userinfo WHERE id=#{id};
</delete>
<update id="updateUser">
UPDATE userinfo
SET username = #{username},password = #{password}
WHERE id = #{id}
</update>
<select id="queryById" resultType="UserInfo" parameterType="long">
SELECT id,username,password
FROM userinfo
WHERE id=#{id}
</select>
</mapper>
用于实现SQL语句对数据库的操作。
在service包中新建UserService接口文件:
package com.zhongruan.service;
import com.zhongruan.bean.UserInfo;
import java.util.List;
public interface UserService {
public List<UserInfo> findAll();
public int addUser(UserInfo userInfo);
public int delUser(long id);
public int updateUser(UserInfo userInfo);
public UserInfo queryById(long id);
}
在本包下新建一个impl包,在包内新建UserServiceImpl.class文件,用于实现UserService接口文件中定义的函数:
package com.zhongruan.service.impl;
import com.zhongruan.bean.UserInfo;
import com.zhongruan.dao.UserDao;
import com.zhongruan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Override
public List<UserInfo> findAll() {
return userDao.findAll();
}
@Override
public int addUser(UserInfo userInfo) {
return userDao.addUser(userInfo);
}
@Override
public int delUser(long id) {
return userDao.delUser(id);
}
@Override
public int updateUser(UserInfo userInfo) {
return userDao.updateUser(userInfo);
}
@Override
public UserInfo queryById(long id) {
return userDao.queryById(id);
}
}
在controller中创建UserController.class文件,用于实现页面的转接请求:
package com.zhongruan.controller;
import com.zhongruan.bean.UserInfo;
import com.zhongruan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findAll.do")
public ModelAndView findAll() {
List<UserInfo> userInfos = userService.findAll();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("ui", userInfos);
modelAndView.setViewName("allUser");
return modelAndView;
}
@RequestMapping("/toAddUser.do")
public ModelAndView addUser() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("ui");
modelAndView.setViewName("addUser");
return modelAndView;
}
@RequestMapping("/save.do")
public String toAddPaper(UserInfo userInfo) {
userService.addUser(userInfo);
return "redirect:/user/findAll.do";
}
@RequestMapping("/delete.do")
public String delUser(long id) {
userService.delUser(id);
return "redirect:/user/findAll.do";
}
@RequestMapping("/toUpdate.do")
public String toUpdateUser(Model model, long id) {
model.addAttribute("userInfo", userService.queryById(id));
return "updateUser";
}
@RequestMapping("/update.do")
public String updateUser(Model model, UserInfo userInfo) {
userService.updateUser(userInfo);
userInfo = userService.queryById(userInfo.getId());
model.addAttribute("userInfo", userInfo);
return "redirect:/user/findAll.do";
}
/*
@RequestMapping("/toUpdate.do")
public ModelAndView toUpdateUser(){
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("ui");
modelAndView.setViewName("updateUser");
return modelAndView;
}
@RequestMapping("/update.do")
public String updateUser(UserInfo userInfo) {
userService.updateUser(userInfo);
return "redirect:/user/findAll.do";
}
*/
}
最终文件目录如下:
编写完成后,将index.jsp文件修改:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<h2>Hello World!</h2>
<a href="${pageContext.request.contextPath}/user/findAll.do">查询所有用户</a>
</body>
</html>
SSM框架应用的启动配置
点击Run–Edit Configurations,点击左上角的“+”,在窗口中下拉选择xx items more,选择Tomcat Server–Local,在Application Server选择安装Tomcat的根目录;
点击Deployment选项,点击右侧“+”添加Artifact–war exploded,添加后点击apply进行应用:
然后右键index.jsp,点击Run index.jsp运行整个项目,效果如下:
查询用户界面:
点击新增,可以将新用户添加到数据库中:
至此,使用maven项目成功实现了web应用中的添加功能,其他功能实现方式类似,在此仅简单介绍一下增添功能。