一、简介
所谓SSM,即是Spring+SpringMVC+MyBatis三个开源框架的整合,是目前流行的作为WEB项目搭建的框架选择。
这篇文章是自己动手搭建并将过程记录,以便加深印象和方便以后查阅。
二、环境
1.操作系统:windows 10
2.IDE版本:Eclipse Luna Release (4.4.0)
3.JDK版本:jdk1.7.0_60
4.tomcat版本:apache-tomcat-7.0.53
5.maven版本:3.2.1
6.数据库:mysql(事先建好数据库)
三、步骤
(一)创建工程
1.New一个maven工程
2.点击Next,选择默认工作空间位置;如果勾选了create a simple project会自动创建src/main/java,src/test/java,src/test/resources这些maven项目中常见文件夹,但会缺失web项目需要的web.xml等文件;
此处我们不勾选,点击下一步;
3.选择web类型,注意不要选错了,点击Next
4.填写GroupID、ArtifactID及版本信息,点击Finish
5.工程创建完毕
(二)调整项目结构
1.window-Preferences-Server-Runtime Environment添加tomcat,并注意JRE环境为你的jdk版本
2.这时候看到我们JRE System Library后面显示的还是[J2SE-1.5],并且没有maven项目的src/main/java等文件夹,我们需要调整对应的JRE环境,在工程上右键Build Path-Configure Build Path,在Libraries下选中JRE,右侧edit,选择我们自己的jdk版本
3.这时候我们的项目就变成了这个样子,JRE版本也对了,src/main等文件夹也有了,但还是缺少src/test/resources,需要手动创建
4.右键New一个source folder,名称为src/test/resources
5.结构调整完毕
(三)添加pom依赖,下载SSM框架所需jar包
<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.0</modelVersion>
<groupId>test.java.zxf</groupId>
<artifactId>SSMDemo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SSMDemo Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<!-- Spring版本号 -->
<spring.version>4.3.8.RELEASE</spring.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-aop</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-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- AOP相关包 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.0</version>
</dependency>
<!-- MyBatis相关包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<!-- MySQL相关包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.20</version>
</dependency>
<!-- Spring集成MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
<!-- JSP标准标签库 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 日志相关包 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<!-- 单元测试相关包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>SSMDemo</finalName>
</build>
</project>
下载之后可以看到maven依赖下的包已经都有了
(四)配置文件
1.修改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>
<!-- Spring和mybatis的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- /表示全部拦截 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
2.在resources文件夹下创建spring-mybatis.xml
点击finish,创建文件
3.配置spring-mybatis.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:p="http://www.springframework.org/schema/p"
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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自动扫描 -->
<context:component-scan base-package="com.java.zxf" />
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:log4j.properties</value>
</list>
</property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/java/zxf/dao/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.java.zxf.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- 事务管理 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
4.创建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:p="http://www.springframework.org/schema/p"
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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.java.zxf.controller" />
<!-- 定义跳转的文件的前后缀 ,视图模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- controller中return时会自动加上前缀和后缀,变成一个完整的url -->
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
5.创建jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/testdb
jdbc.username=root
jdbc.password=root
6.创建log4j.properties文件
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH:mm:ss}][%c]%m%n
(五)编写服务端代码
1.利用逆向工程生成dao、实体类和mybatis映射文件,具体参考教程https://blog.csdn.net/qq_33236248/article/details/80091214
2.在src/java/main文件夹下新建包com.java.zxf.dao、com.java.zxf.domain
3.将逆向工程生成的三个文件,分别拷贝到对应的目录下;(习惯上把mapper改为dao,可以不改,但如果改了,记住UserMapper.xml中的namespace也要做对应更改,不然会报Invalid bound statement (not found)的异常)
User.java,代码如下:
package com.java.zxf.domain;
public class User {
private String id;
private String userName;
private String userGender;
private String userBirthday;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getUserGender() {
return userGender;
}
public void setUserGender(String userGender) {
this.userGender = userGender == null ? null : userGender.trim();
}
public String getUserBirthday() {
return userBirthday;
}
public void setUserBirthday(String userBirthday) {
this.userBirthday = userBirthday == null ? null : userBirthday.trim();
}
}
UserDao.java,代码如下 :
package com.java.zxf.dao;
import com.java.zxf.domain.User;
public interface UserDao {
int deleteByPrimaryKey(String id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
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.java.zxf.dao.UserDao">
<resultMap id="BaseResultMap" type="com.java.zxf.domain.User">
<id column="id" jdbcType="VARCHAR" property="id" />
<result column="user_name" jdbcType="VARCHAR" property="userName" />
<result column="user_gender" jdbcType="VARCHAR" property="userGender" />
<result column="user_birthday" jdbcType="VARCHAR" property="userBirthday" />
</resultMap>
<sql id="Base_Column_List">
id, user_name, user_gender, user_birthday
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String">
delete from user
where id = #{id,jdbcType=VARCHAR}
</delete>
<insert id="insert" parameterType="com.java.zxf.domain.User">
insert into user (id, user_name, user_gender,
user_birthday)
values (#{id,jdbcType=VARCHAR}, #{userName,jdbcType=VARCHAR}, #{userGender,jdbcType=VARCHAR},
#{userBirthday,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.java.zxf.domain.User">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="userName != null">
user_name,
</if>
<if test="userGender != null">
user_gender,
</if>
<if test="userBirthday != null">
user_birthday,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=VARCHAR},
</if>
<if test="userName != null">
#{userName,jdbcType=VARCHAR},
</if>
<if test="userGender != null">
#{userGender,jdbcType=VARCHAR},
</if>
<if test="userBirthday != null">
#{userBirthday,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.java.zxf.domain.User">
update user
<set>
<if test="userName != null">
user_name = #{userName,jdbcType=VARCHAR},
</if>
<if test="userGender != null">
user_gender = #{userGender,jdbcType=VARCHAR},
</if>
<if test="userBirthday != null">
user_birthday = #{userBirthday,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKey" parameterType="com.java.zxf.domain.User">
update user
set user_name = #{userName,jdbcType=VARCHAR},
user_gender = #{userGender,jdbcType=VARCHAR},
user_birthday = #{userBirthday,jdbcType=VARCHAR}
where id = #{id,jdbcType=VARCHAR}
</update>
</mapper>
4.在src/java/main文件夹下新建包com.java.zxf.service,用来存放service层代码;
5.在service包下新建UserService类,定义接口根据ID查询用户信息
package com.java.zxf.service;
import com.java.zxf.domain.User;
public interface UserService {
/**
* 根据ID获取用户信息
*/
public User getUserById(String id);
}
6.在service包下新建com.java.zxf.service.impl包,用来存放service层实现的代码;
7.在impl包下新建UserServiceImpl类,实现UserService
package com.java.zxf.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.java.zxf.dao.UserDao;
import com.java.zxf.domain.User;
import com.java.zxf.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public User getUserById(String id) {
return userDao.selectByPrimaryKey(id);
}
}
8.在src/java/main文件夹下新建包com.java.zxf.controller,用来存放控制层代码;
9.在controller下新建UserController类,并编写控制层代码;
package com.java.zxf.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.java.zxf.domain.User;
import com.java.zxf.service.UserService;
/**
* 用户控制器
*/
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView login(@RequestParam(value="id",required=true) String id) {
User user = userService.getUserById(id);
ModelAndView mav = new ModelAndView();
if (user == null) {
//跳转至失败页
mav.setViewName("fail");
return mav;
} else {
//跳转至成功页
mav.addObject("id", user.getId());
mav.addObject("name", user.getUserName());
mav.addObject("gender", user.getUserGender());
mav.addObject("birthday", user.getUserBirthday());
mav.setViewName("success");
return mav;
}
}
}
(六)编写前端代码
1.在WEB-INF目录下新建jsp文件夹,用来存放jsp页面
2.在jsp文件夹下分别新建失败页fail.jsp和成功页success.jsp
fail.jsp代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>失败页</title>
</head>
<body>
根据ID查询用户信息失败
</body>
</html>
success.jsp代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>成功页</title>
</head>
<body>
根据ID查询用户信息成功<br/>
用户信息如下:<br/>
用户ID:${id}<br/>
用户名:${name}<br/>
用户性别:${gender}<br/>
用户生日:${birthday}<br/>
</body>
</html>
(七)构建项目
1.在项目上右键,选择run-maven build..,然后输入命令clean install
2.构建成功
(八)部署项目
1.在Servers标签中,新建一个server,可以点击链接,也可以右键New Server;如果没有Server标签,可以在菜单栏依次Window-Show View-Servers即可打开
配置tomcat
2.点击Next,将我们的项目添加到右侧
3.点击finish完成,server就创建完成了
4.在server上双击,打开相关配置,在Timeouts中将服务器启动和关闭时间改为300秒,因为如果项目太大,几十秒肯定启动不完,服务器就停了
5.右键server,点击publish发布(可能失败,多点几次)
6.右键server,点击start,启动服务器
启动成功
(九)访问项目
(在此之前,数据库已经有一条数据)
1.在浏览器地址栏输入http://localhost:8080/SSMDemo/user?id=1
2.成功
3.再测一下失败页,在地址栏输入http://localhost:8080/SSMDemo/user?id=2
4.访问成功
---------------------
作者:张小烦一点都不烦
来源:CSDN
原文:https://blog.csdn.net/qq_33236248/article/details/80095397
版权声明:本文为博主原创文章,转载请附上博文链接!