什么是SSM?
SSM包含三个部分,分别为:spring,springMVC以及mybatis。
- spring包括ioc以及aop,ioc意为控制反转,将控制权交给spring容器,由spring创建对象。aop为面向切面编程。
- springMVC来控制跳转。
- mybatis则是关于数据库的操作。下面来演示如何创建一个SSM工程以及实现简单的增删改查。
所需开发工具如下:
- IntelliJ IDEA Ultimate 2018.2.2
- Apache-tomcat-7.0.94
- JDK 1.8.0_144
- Mysql 5.5.58
- maven 3.6.0
过程如下:
1.新建项目
点击File->New->Project
在这个地方选择JDK版本
勾选Create from archetype
选择这个选项,点击next
填写这两项,GroupID是项目组织唯一的标识符,实际对应JAVA的包的结构,是main目录里java的目录结构,ArtifactID是项目的唯一的标识符,实际对应项目的名称,就是项目根目录的名称。可以随便填写。点击next
选择maven版本,点击next
点击finish
2.在项目中添加所需文件,构建项目主体
在main包下新建包java,为了防止包重叠,要把这个选项勾掉
右键点击新建的java包,选择Mark Directory as
选择Sources Root
在java包下新建包com,在com包下新建包zhongruan,在包zhongruan下建包bean,controller,dao,service(包名可以随意取,只要记住对应作用即可),如下
在包main新建包resources,更改类型为Resources Root
在bean下新建类UserInfo
在dao下新建接口IUserDao,过程与建类相同,区别在于命名时的kind一栏选择interface,如下
按照这个步骤继续填充文件,结构如下:
3.代码展示
在这里有个小技巧,如果想生成注释,可以使用ctrl+/来生成注释,这样就可以在对应后缀的文件下生成对应的注释,我就是因为在jsp文件中用了别的注释样式,导致错误一直没有检查出来,因为注释那个地方在文件中不会报错。
每个文件的代码如下:
UserInfo
package com.zhongruan.bean;
public class UserInfo {
private int id;
private String username;
private String 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;
}
@Override
public String toString() {
return "UserInfo{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
UserController
package com.zhongruan.controller;
import com.zhongruan.bean.UserInfo;
import com.zhongruan.service.IUserService;
import com.zhongruan.service.impl.UserService;
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("/user")
public class UserController {
@Autowired
private IUserService userService;
// 展示信息
@RequestMapping("/findAll.do")
public ModelAndView findAll(){
List<UserInfo> all = userService.findAll();
ModelAndView mv = new ModelAndView();
mv.addObject("userinfos",all);
mv.setViewName("allUser");
return mv;
}
// 删除用户
@RequestMapping("/delete.do")
public String delete(int id){
userService.delete(id);
// List<UserInfo> all = userService.findAll();
// ModelAndView mv = new ModelAndView();
// mv.addObject("userinfos",all);
// mv.setViewName("allUser");
// return mv;
//redirect为重定向,与上面注释掉的代码作用相同
return "redirect:findAll.do";
}
// 添加用户
@RequestMapping("/save.do")
public String addUser(UserInfo userinfo){
userService.insert(userinfo);
return "redirect:findAll.do";
}
// 跳转到addUser.jsp
@RequestMapping("/toAddUser.do")
public ModelAndView toAddUser(){
ModelAndView mv=new ModelAndView();
mv.setViewName("addUser");
return mv;
}
// 跳转到updateUser.jsp
@RequestMapping("/toUpdate.do")
public ModelAndView toUpdate(int id){
UserInfo userinfo = userService.findid(id);
ModelAndView mv = new ModelAndView();
mv.addObject("userInfo",userinfo);
mv.setViewName("updateUser");
return mv;
}
// 更新用户信息
@RequestMapping("/update.do")
public String update(UserInfo userinfo){
userService.update(userinfo);
return "redirect:findAll.do";
}
}
IUserDao
package com.zhongruan.dao;
import com.zhongruan.bean.UserInfo;
import java.util.List;
public interface IUserDao {
public List<UserInfo> findAll();
public void delete(int id);
public void insert(UserInfo userinfo);
public void update(UserInfo userinfo);
public UserInfo findid(int id);
}
UserServices
package com.zhongruan.service.impl;
import com.zhongruan.bean.UserInfo;
import com.zhongruan.dao.IUserDao;
import com.zhongruan.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService implements IUserService {
@Autowired
private IUserDao userDao;
@Override
public List<UserInfo> findAll() {
return userDao.findAll();
}
@Override
public void delete(int id) {
userDao.delete(id);
}
@Override
public void insert(UserInfo userinfo) {
userDao.insert(userinfo);
}
@Override
public void update(UserInfo userinfo) {
userDao.update(userinfo);
}
// 通过获取用户id来获得用户信息来进行修改
@Override
public UserInfo findid(int id) {
return userDao.findid(id);
}
}
IUserServices
package com.zhongruan.service;
import com.zhongruan.bean.UserInfo;
import java.util.List;
public interface IUserService {
public List<UserInfo> findAll();
public void delete(int id);
public void insert(UserInfo userinfo);
public void update(UserInfo userinfo);
public UserInfo findid(int id);
}
UserMapper
<?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.IUserDao" >
<select id="findAll" resultType="com.zhongruan.bean.UserInfo">
<!--
注释不能用双斜线//
-->
select * from userinfo
</select>
<delete id="delete" parameterType="com.zhongruan.bean.UserInfo">
delete from userinfo where id=#{id}
</delete>
<insert id="insert" parameterType="com.zhongruan.bean.UserInfo">
insert into userinfo values (#{id},#{username},#{password})
</insert>
<update id="update" parameterType="com.zhongruan.bean.UserInfo">
update userinfo set username=#{username},password=#{password} where id=#{id}
</update>
<select id="findid" resultType="com.zhongruan.bean.UserInfo">
select * from userinfo where id=#{id}
</select>
</mapper>
applicationContext
<?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-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 1.配置数据库相关参数properties的属性:${url} -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 2.配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<!--
下面为数据库密码,同db.properties中一致,不要忘了修改
-->
<property name="password" value="123456"/>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="2"/>
</bean>
<!-- 3.配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 扫描bean包 使用别名 -->
<property name="typeAliasesPackage" value="com.zhongruan.bean"></property>
<!--配置加载映射文件 UserMapper.xml-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 自动生成dao,mapper-->
<!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.zhongruan.dao"/>
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!--自动扫描-->
<context:component-scan base-package="com.zhongruan"/>
<!-- 配置事务-->
<!-- 5.配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 6.开启事务注解-->
<tx:annotation-driven></tx:annotation-driven>
</beans>
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/idea?useSSL=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
idea为你的数据库名,username为你的登录名,password为你的登录密码
log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
spring_mvc.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:mvc="http://www.springframework.org/schema/mvc"
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-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 1.注解扫描位置-->
<context:component-scan base-package="com.zhongruan.controller" />
<!-- 2.配置映射处理和适配器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
<!-- 3.视图的解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
allUser.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>
<head>
<title>user列表</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
基于SSM框架的管理系统:简单实现增、删、改、查。
</h1>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>用户列表 —— 显示所有用户</small>
</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/user/toAddUser.do">新增</a>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>id</th>
<th>用户名</th>
<th>密码</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach items="${userinfos}" var="userInfo">
<tr>
<td>${userInfo.id}</td>
<td>${userInfo.username}</td>
<td>${userInfo.password}</td>
<td>
<a href="${pageContext.request.contextPath}/user/toUpdate.do?id=${userInfo.id}">更改</a> |
<a href="${pageContext.request.contextPath}/user/delete.do?id=${userInfo.id}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- 配置加载类路径的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<!-- 配置监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<!-- 解决中文乱码过滤器 -->
<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>
<!-- 前端控制器(加载classpath:spring-mvc.xml 服务器启动创建servlet) -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!-- 服务器启动的时候,让DispatcherServlet对象创建 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<html>
<body>
<a href="${pageContext.request.contextPath}/user/findAll.do">查询所有用户</a>
</body>
</html>
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>0627</groupId>
<artifactId>0627</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>0627 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.7</maven.compiler.source>
<maven.compiler.target>1.7</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>0627</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>
运行结果如图
点击新增按钮,输入id,name,password
点击添加,这里可以看到,用户信息已经成功添加进去
点击更改按钮,将用户名改为22,密码改为222,如下:
点击提交,可以看到,信息更改成功
点击删除按钮,删除刚修改的这个信息:
删除成功!
至此,基于SSM框架的管理系统:关于简单的增、删、改、查已基本实现。后面会更新关于登录以及分页的知识。