SSM整合篇
一、创建mavem项目web工程
1、工程是apche下的maven下的webapp 2、指定项目名称和位置 3、maven的选择。通常是用自己的。默认也行 4、项目的样子 5、在mian下面创建Java和resources目录 7、完整工程如图:
二、数据库文件
CREATE TABLE `user` (
`id` int NOT NULL,
`username` varchar(10) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
三、完整的项目结构
四、SSM整合
1.1、pom文件
<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.version>5.0.2.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>8.0.11</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<!--aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- aspectj面向切面 aop相关的jar -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<!--context 容器-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--web springmvc所需要 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring、springmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--tx 事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!--jdbc模板技术-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--mybatis整合spring要用的jar-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--c3p0数据库连接池-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!--jstl EL表达式那些要用到-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--log4j日志实现-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!--slf4j日志门面-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!--slf4j-log4j12桥接器-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--junit的单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>ssm</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
1.2、配置文件说明
-
applicationContext.xml 管理spring和mybatis的文件
-
springmvc.xml 管理springmvc的文件
-
db.properties 数据库配置文件
-
web.xml web项目核心文件加载applicationContext.xml和springmvc.xml
-
log4j.properties log4j自定义日志文件 (这算是对之前小编一篇日志框架集成log4f+slf4j的补充) 博文==>JAVA日志框架
1.3、配置文件详解
1.3.1、applicationContext.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"
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">
<!-- 使用PropertyOverrideConfigurer后处理器加载数据源参数 -->
<context:property-override location="classpath:db.properties"/>
<!--事务注解的方式,不采用声明式事务-->
<!--<tx:annotation-driven transaction-manager="transactionManager" />-->
<!--方式以:自己指定扫描哪个包-->
<context:component-scan base-package="sqy.service"></context:component-scan>
<context:component-scan base-package="sqy.dao"></context:component-scan>
<context:component-scan base-package="sqy.pojo"></context:component-scan>
<!--方式二: 开启注解的扫描,只处理spring和mybatis(也就是service和dao)-->
<!-- <context:component-scan base-package="sqy">
<!–排除controller,@Controller注解 spring不扫描–>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>-->
<!--配置连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${dataSource.driverClass}"/>
<property name="jdbcUrl" value="${dataSource.jdbcUrl}"/>
<property name="user" value="${dataSource.user}"/>
<property name="password" value="${dataSource.password}"/>
<property name="maxIdleTime" value="${dataSource.maxIdleTime}"/>
<property name="initialPoolSize" value="${dataSource.initialPoolSize}"/>
<property name="minPoolSize" value="${dataSource.minPoolSize}"/>
<property name="maxPoolSize" value="${dataSource.maxPoolSize}"/>
</bean>
<!--配置SqlSessionFactory工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置Dao接口所在包-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="sqy.dao"/>
</bean>
<!--配置Spring框架声明式事务管理-->
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!--配置AOP增强-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* sqy.service.impl.*ServiceImpl.*(..))"/>
</aop:config>
</beans>
1.3.2、springmvc.xml
<?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">
<!--开启SpringMVC注解的支持-->
<mvc:annotation-driven/>
<!-- 配置controller扫描包 -->
<context:component-scan base-package="sqy.controller" />
<!--配置的视图解析器对象-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--过滤静态资源-->
<mvc:resources location="/css/" mapping="/css/**" />
</beans>
1.3.3、db.properties
dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
dataSource.user=root
dataSource.password=root
dataSource.maxPoolSize=10
dataSource.maxIdleTime=1000
dataSource.minPoolSize=5
dataSource.initialPoolSize=5
1.3.4、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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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>
1.3.5、log4j.properties(乞丐版)
完整配置看 ==> JAVA日志框架
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
1.4、实体类
User.java
package sqy.pojo;
import org.springframework.stereotype.Component;
import java.io.Serializable;
@Component
public class User implements Serializable {
private Integer id;
private String username;
private String password;
}
1.4、controller
package sqy.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import sqy.pojo.User;
import sqy.service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
UserService userService;
@GetMapping("/findAll")
public String findAllUser(Model model) {
List<User> users = userService.findAll();
logger.info("用户{}", users);
model.addAttribute("userList", users);
return "list";
}
@RequestMapping("/save")
public void save(User user, HttpServletRequest request, HttpServletResponse response) throws IOException {
userService.saveUser(user);
response.sendRedirect(request.getContextPath() + "/user/findAll");
}
}
1.5、service和impl
UserService.java
package sqy.service;
import sqy.pojo.User;
import java.util.List;
public interface UserService {
public List<User> findAll();
public void saveUser(User user);
}
UserServiceImpl.java
package sqy.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sqy.dao.UserDao;
import sqy.pojo.User;
import sqy.service.UserService;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Override
public List<User> findAll() {
List<User> list = userDao.findAll();
return list;
}
@Override
public void saveUser(User user) {
userDao.saveUser(user);
}
}
1.5、dao接口
package sqy.dao;
import org.springframework.stereotype.Repository;
import sqy.pojo.User;
import java.util.List;
@Repository
public interface UserDao {
List<User> findAll();
void saveUser(User user);
}
1.6、dao对应的xml文件(resources)
注意:包名和层级要保持一致
位置:/resources/sqy/dao/UserDao.xml
UserDao.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="sqy.dao.UserDao">
<select
id="findAll"
resultType="sqy.pojo.User">
select * from user
</select>
<insert
id="saveUser"
parameterType="sqy.pojo.User">
insert into user values(#{id},#{username},#{password})
</insert>
</mapper>
1.7、页面文件和文件夹
如图: 1、创建css文件夹是演示静态资源过滤
2、在WBE-INF安全目录下创建page文件夹和list.jsp演示视图解析器
3、默认加载index.jsp
1.1、index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>默认首页</title>
</head>
<body>
<h1>默认首页</h1>
<form action="/user/save" method="post">
id:<input type="text" name="id"/><br/>
用户名:<input type="text" name="username"/><br/>
密码:<input type="text" name="password"/><br/>
<input type="submit" value="添加"/><br/>
</form>
</body>
</html>
1.2、list.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</title>
</head>
<body>
<h3>WEB-INF/pages/list.jsp</h3>
<c:forEach items="${userList}" var="user">
用户=> ${user.id} -- ${user.username} -- ${user.password}
</c:forEach>
</body>
</html>
1.8、配置tomcat运行
1.9、运行效果
五、完结
可以看看小编的框架整合系类
下一篇:ssm集成redis详细配置 下下篇:ssm整合mqtt (物联网)
|