在目前的企业级Java应用中,Spring框架是必须的。Struts2框架与Spring的整合问题日益凸显,而Spring MVC作为新一代的MVC框架,因其可以与Spring框架无缝整合的特性收到了越来越多的欢迎。Hibernate框架在面对需要存储过程或者复杂SQL时显得力不从心,不能提供高效的数据库控制。而Mybatis框架作为持久层的框架,虽然需要自己编写SQL语句,但是其对高并发高响应的支持,以及对动态SQL和动态绑定的支持使其脱颖而出。
因此SSM框架(Spring + Spring MVC +Mybatis)逐渐取代了之前广泛使用的SSH框架(Spring + Struts2 + Hibernate),成为了目前使用最多的框架。
本文使用IDEA,利用Maven管理项目,整合SSM框架搭建论文管理系统,实现简单的增、删、改、查功能。步骤详细,讲解丰富,适合新手入门。
下面开始详细的讲解项目的开发过程。
1. 新建Maven项目:
点击File -> New -> Project -> Maven -> 勾选 Create from archetype -> 选择 maven-archetype-webapp (注意:此处不要错选成上面的cocoom-22-archetype-webapp)
在弹出的new project 选项卡中填写GroupId和Artifactid,其中GroupID是项目组织唯一的标识符,实际对应JAVA的包的结构,是main目录里java的目录结构,ArtifactID是项目的唯一的标识符,实际对应项目的名称,就是项目根目录的名称。对于入门练习,这两项可以随意填写。
之后点击next 选择Maven版本(其中IDEA 专业版自带Maven,也可以选择自己下载的maven)。之后填写项目名称和项目地址,完成后点击Finish,完成项目骨架的创建。
.
2. 在新建的项目中添加所需要的文件/文件夹
在项目的根目录下新建target文件夹,系统自动将其设置为“Excluded”
在src/main目录下新建Directory:“java”,并将其设置为“Source Root”(即:此项目默认的代码文件源目录)
在刚才新建的java文件下新建“com”包,再在com包下新建四个包,分别命名为:pojo,service,dao,controller。(如果出现下图中所示的包名重叠的情况,可以点击图中所示的图标,将“Hide empty middle package取消掉”)
上面新建的四个包:pojo,service,dao,controller,其所存放的分别是:
在resource包下新建Directory:“mapper”(用于存放xxxMapper.xml文件)和“spring”(用于存放spring-xxx.xml配置文件),新建文件:“jdbc.properties”(mysql数据库配置文件),”log4j.properties”(日志输出配置文件),”mybatis-config.xml”(mybatis框架配置文件)。
在web-inf目录下新建“jsp”包,存放xxx.jsp显示界面。
补充之后的项目目录如下图所示,至此项目骨架搭建完毕,开始写代码实现增删改查功能。
3. 自定义Paper类
在这之前要对项目的pom.xml文件进行配置,在此文件中配置项目所需要的jar包。
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>comgroupId>
<artifactId>firstartifactId>
<packaging>warpackaging>
<version>1.0-SNAPSHOTversion>
<name>first Maven Webappname>
<url>http://maven.apache.orgurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<spring.version>5.0.3.RELEASEspring.version>
<mybatis.version>3.4.4mybatis.version>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>3.8.1version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.2version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>taglibsgroupId>
<artifactId>standardartifactId>
<version>1.1.2version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.4version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.38version>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5.2version>
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>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>1.1.1version>
dependency>
dependencies>
<build>
<finalName>firstfinalName>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<configuration>
<source>1.8source>
<target>1.8target>
configuration>
plugin>
plugins>
build>
project>
本项目所用的数据库为MySQL 5.7 建表语句如下:
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `paper`
-- ----------------------------
DROP TABLE IF EXISTS `paper`;
CREATE TABLE `paper` (
`paper_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'paperID',
`name` varchar(100) NOT NULL COMMENT 'paper名称',
`number` int(11) NOT NULL COMMENT 'paper数量',
`detail` varchar(200) NOT NULL COMMENT 'paper描述',
PRIMARY KEY (`paper_id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COMMENT='paper表';
-- ----------------------------
-- Records of paper
-- ----------------------------
INSERT INTO `paper` VALUES ('1', '机器学习', '2', 'mlmlmlml');
INSERT INTO `paper` VALUES ('2', '深度学习', '3', 'dldldl');
INSERT INTO `paper` VALUES ('3', '大数据', '4', 'bdbdbd');
下面开始写java代码:
package com.pojo;
public class Paper {
private long paperId;
private String paperName;
private int paperNum;
private String paperDetail;
public long getPaperId() {
return paperId;
}
public void setPaperId(long paperId) {
this.paperId = paperId;
}
public String getPaperName() {
return paperName;
}
public void setPaperName(String paperName) {
this.paperName = paperName;
}
public int getPaperNum() {
return paperNum;
}
public void setPaperNum(int paperNum) {
this.paperNum = paperNum;
}
public String getPaperDetail() {
return paperDetail;
}
public void setPaperDetail(String paperDetail) {
this.paperDetail = paperDetail;
}
}
其中getter/setter方法可以在定义完私有属性之后使用IDEA提供的快捷键:ALT+Insert 来实现快速添加
package com.service;
import com.pojo.Paper;
import java.util.List;
public interface PaperService {
int addPaper(Paper paper);
int deletePaperById(long id);
int updatePaper(Paper paper);
Paper queryById(long id);
List queryAllPaper();
}
package com.service.impl;
import com.pojo.Paper;
import com.dao.PaperDao;
import com.service.PaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PaperServiceImpl implements PaperService {
@Autowired
private PaperDao paperDao;
@Override
public int addPaper(Paper paper) {
return paperDao.addPaper(paper);
}
@Override
public int deletePaperById(long id) {
return paperDao.deletePaperById(id);
}
@Override
public int updatePaper(Paper paper) {
return paperDao.updatePaper(paper);
}
@Override
public Paper queryById(long id) {
return paperDao.queryById(id);
}
@Override
public List queryAllPaper() {
return paperDao.queryAllPaper();
}
}
package com.dao;
import com.pojo.Paper;
import java.util.List;
public interface PaperDao {
int addPaper(Paper paper);
int deletePaperById(long id);
int updatePaper(Paper paper);
Paper queryById(long id);
List queryAllPaper();
}
package com.controller;
import com.pojo.Paper;
import com.service.PaperService;
import java.util.List;
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;
@Controller
@RequestMapping("/paper")
public class PaperController {
@Autowired
private PaperService paperService;
@RequestMapping("/allPaper")
public String list(Model model) {
List list = paperService.queryAllPaper();
model.addAttribute("list", list);
return "allPaper";
}
@RequestMapping("toAddPaper")
public String toAddPaper() {
return "addPaper";
}
@RequestMapping("/addPaper")
public String addPaper(Paper paper) {
paperService.addPaper(paper);
return "redirect:/paper/allPaper";
}
@RequestMapping("/del/{paperId}")
public String deletePaper(@PathVariable("paperId") Long id) {
paperService.deletePaperById(id);
return "redirect:/paper/allPaper";
}
@RequestMapping("toUpdatePaper")
public String toUpdatePaper(Model model, Long id) {
model.addAttribute("paper", paperService.queryById(id));
return "updatePaper";
}
@RequestMapping("/updatePaper")
public String updatePaper(Model model, Paper paper) {
paperService.updatePaper(paper);
paper = paperService.queryById(paper.getPaperId());
model.addAttribute("paper", paper);
return "redirect:/paper/allPaper";
}
}
<mapper namespace="com.dao.PaperDao">
<resultMap type="Paper" id="paperResultMap" >
<id property="paperId" column="paper_id"/>
<result property="paperName" column="name"/>
<result property="paperNum" column="number"/>
<result property="paperDetail" column="detail"/>
resultMap>
<insert id="addPaper" parameterType="Paper">
INSERT INTO paper(paper_id,name,number,detail) VALUE (#{paperId},#{paperName}, #{paperNum}, #{paperDetail})
insert>
<delete id="deletePaperById" parameterType="long">
DELETE FROM paper WHERE paper_id=#{paperID}
delete>
<update id="updatePaper" parameterType="Paper">
UPDATE paper
SET NAME = #{paperName},NUMBER = #{paperNum},detail = #{paperDetail}
WHERE paper_id = #{paperId}
update>
<select id="queryById" resultType="Paper" parameterType="long">
SELECT paper_id,name,number,detail
FROM paper
WHERE paper_id=#{paperId}
select>
<select id="queryAllPaper" resultMap="paperResultMap">
SELECT paper_id,name,number,detail
FROM paper
select>
mapper>
spring-dao.xml:(spring-mybatis整合配置文件)
<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:jdbc.properties"/>
<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}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="10000"/>
<property name="acquireRetryAttempts" value="2"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="typeAliasesPackage" value="com.pojo"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.dao"/>
bean>
beans>
spring-mvc.xml:(spring mvc配置文件)
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
bean>
<context:component-scan base-package="com.controller" />
beans>
spring-service.xml
<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: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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.service" />
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
bean>
<tx:annotation-driven transaction-manager="transactionManager" />
beans>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/papersystem?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=12345678
log4j.rootLogger=ERROR, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
<configuration>
<settings>
<setting name="useGeneratedKeys" value="true" />
<setting name="useColumnLabel" value="true" />
<setting name="mapUnderscoreToCamelCase" value="true" />
settings>
configuration>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1" metadata-complete="true">
<display-name>Archetype Created Web Applicationdisplay-name>
<servlet>
<servlet-name>dispatcherservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring/spring-*.xmlparam-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>dispatcherservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
filter-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>
web-app>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%
pageContext.setAttribute("path", request.getContextPath());
%>
<html>
<head>
<title>首页title>
<style type="text/css">
a {
text-decoration: none;
color: black;
font-size: 18px;
}
h3 {
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: deepskyblue;
border-radius: 4px;
}
style>
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>
<br><br>
<h3>
<a href="${path }/paper/allPaper">点击进入管理页面a>
h3>
body>
html>
allPaper.jsp:所有论文显示界面
<%--
Created by IntelliJ IDEA.
User: lenovo
Date: 2018/4/6
Time: 16:57
To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<% String appPath = request.getContextPath(); %>
<html>
<head>
<title>Paper列表title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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="${path}/paper/toAddPaper">新增a>
div>
div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>论文编号th>
<th>论文名字th>
<th>论文数量th>
<th>论文详情th>
<th>操作th>
tr>
thead>
<tbody>
<c:forEach var="paper" items="${requestScope.get('list')}" varStatus="status">
<tr>
<td>${paper.paperId}td>
<td>${paper.paperName}td>
<td>${paper.paperNum}td>
<td>${paper.paperDetail}td>
<td>
<a href="${path}/paper/toUpdatePaper?id=${paper.paperId}">更改a> |
<a href="<%=appPath%>/paper/del/${paper.paperId}">删除a>
td>
tr>
c:forEach>
tbody>
table>
div>
div>
div>
addPaper,jsp:论文添加页面
<%--
Created by IntelliJ IDEA.
User: lenovo
Date: 2018/4/7
Time: 16:45
To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<html>
<head>
<title>新增论文title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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>
<form action="" name="userForm">
论文名称:<input type="text" name="paperName"><br><br><br>
论文数量:<input type="text" name="paperNum"><br><br><br>
论文详情:<input type="text" name="paperDetail"><br><br><br>
<input type="button" value="添加" onclick="addPaper()">
form>
<script type="text/javascript">
function addPaper() {
var form = document.forms[0];
form.action = "<%=basePath %>paper/addPaper";
form.method = "post";
form.submit();
}
script>
div>
updatePaper.jsp:论文更改界面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<html>
<head>
<title>修改论文title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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>
<form action="" name="userForm">
<input type="hidden" name="paperId" value="${paper.paperId}"/>
论文名称:<input type="text" name="paperName" value="${paper.paperName}"/>
论文数量:<input type="text" name="paperNum" value="${paper.paperNum}"/>
论文详情:<input type="text" name="paperDetail" value="${paper.paperDetail }"/>
<input type="button" value="提交" onclick="updatePaper()"/>
form>
<script type="text/javascript">
function updatePaper() {
var form = document.forms[0];
form.action = "<%=basePath %>paper/updatePaper";
form.method = "post";
form.submit();
}
script>
div>
4. 利用tomcat进行项目部署
选择default -> tomcat -> local 选择下载安装到本地的tomcat服务器的地址
切换到Deployment选项页 点击 + 号选择 Arctifact ,
添加 项目名:war exploded 打包
最后在Application context 中选择 空白 那一项,点击 Apply 应用。
5. 运行界面
至此,利用IDEA+Maven+SSM框架实现的简单的增、删、改、查功能已经构建完毕!