在maven基础下集合ssm框架:spring+springmv
本文章将以一个小项目为例,在IntelliJ IDEA下使用maven构建ssm框架,通过体会项目构造基本知道ssm框架的作用与效果。
github地址:https://github.com/giraffecode9668/web_ssm
1.使用maven新建项目
archetype
列表中选择maven-archetype-webapp
新建javaweb项目。
2.创建测试数据库
我们使用的是mysql数据库,一般安装mysql数据库的时候是在doc命令框安装的,所以创建数据库我们也直接在doc命令框中创建,操作如下:
- 进入mysql数据库: 按住
window+R
打开运行,输入cmd,输入mysql -uroot -p
,(root是用户名,如果你的用户名不是root改为对应用户名),按照提示输入密码,ok,进入了mysql了! - 创建数据库:一句句输入以下代码,输完冒号就回车!
CREATE DATABASE ssm;
USE ssm;
CREATE TABLE user(
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(32) DEFAULT NULL,
password varchar(100) NOT NULL,
primary key(id)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
insert into user values(01,'zhangsan','123456');
3.添加jar包
在pom.xml文件dependencies
添加如下javaee-api
,logback-classic
,jackson-databind
,mysql-connector-java
,c3p0
,mybatis
,mybatis-spring
,spring-core
,spring-beans
,spring-context
,spring-jdbc
,spring-tx
,spring-web
,spring-webmvc
,spring-test
,testng
这么多的jar包,哇,真的好多包...基本都会用到吧!!!
简单介绍包的作用:
- spring用的包:
spring-core
,spring-context
- springmvc用的包:
spring-webmvc
,spring-web
- mybatis用到包:
mybatis
- 数据库jdbc连接:
mysql-connector-java
,spring-jdbc
- HttpServlet包:
javaee-api
- 连接池:
c3p0
- spring的一些注释包:
spring-beans
,spring-tx
- 作测试用的包:
spring-test
,testng
- json类传输:
jackson-databind
- 日志输出:
logback-classic
修改pom.xml里边<properties>和<dependengcies>标签如下:(老规矩:记得要import一下)
<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>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- spring版本号 -->
<spring.version>4.3.5.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.4.1</mybatis.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- java ee -->
<!--导入servlet类-->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- 实现slf4j接口并整合 -->
<!--日志-->
<!--解释:https://www.cnblogs.com/warking/p/5710303.html-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.2</version>
</dependency>
<!-- JSON -->
<!--类对象装换:ObjectMapper-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
<!-- 数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
<scope>runtime</scope>
</dependency>
<!-- 数据库连接池 -->
<!--c3p0连接池,之前用过阿里的druid-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</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.3.1</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</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>
<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-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
4.项目结构树
构建以下项目结构,把一些文件也先建起来
设置一些路径,按住
ctrl+alt+shift+s
,或者点击文件-项目结构
,打开项目结构,点击模块(modul),按照以下提示:添加src.main为源路径,也就是package **的时候源路径
添加resources为项目Resources
然后点击应用,再点击确定!
5.为resources的文件添加代码
jdbc.properties代码:
jdbc.driver=com.mysql.cj.jdbc.Driver
#数据库地址
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
#用户名
jdbc.username=root
#密码
jdbc.password=8013
#最大连接数
c3p0.maxPoolSize=30
#最小连接数
c3p0.minPoolSize=10
#关闭连接后不自动commit
c3p0.autoCommitOnClose=false
#获取连接超时时间
c3p0.checkoutTimeout=10000
#当获取连接失败重试次数
c3p0.acquireRetryAttempts=2
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=[%p][%t][%d{yyyy-MM-dd HH:mm:ss}][%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][%t][%d{yyyy-MM-dd HH:mm:ss}][%C] - %m%n
logback.xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
spring-mvc.xml代码:代码添加后IDEA会有提示,点击create,然后再点击确认。
<?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: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">
<!-- 扫描web相关的bean -->
<context:component-scan base-package="controller"/>
<!-- 开启SpringMVC注解模式 -->
<mvc:annotation-driven/>
<!-- 静态资源默认servlet配置 -->
<mvc:default-servlet-handler/>
<!-- 配置jsp 显示ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
spring-mybatis.xml代码:代码添加后IDEA会有提示,点击create,然后再点击确认。
<?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: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">
<!-- 扫描service包下所有使用注解的类型 -->
<context:component-scan base-package="service"/>
<!-- 配置数据库相关参数properties的属性:${url} -->
<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="${c3p0.maxPoolSize}"/>
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
</bean>
<!-- 配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 扫描model包 使用别名 -->
<property name="typeAliasesPackage" value="model"/>
<!-- 扫描sql配置文件:mapper需要的xml文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="dao"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置基于注解的声明式事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
webapp/WEB-INF/web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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">
<display-name>ssm</display-name>
<description>SSM_Alpha_0.0.1</description>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置DispatcherServlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置springMVC需要加载的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.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>
<!-- 匹配所有请求,此处也可以配置成 *.do 形式 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
6.新建代码文件
按照下图新建文件
添加代码:
UserController.java:
package controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import service.IUserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private IUserService asd;
@RequestMapping("/showUser.do")
public void selectUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
Integer userId = Integer.parseInt(request.getParameter("id"));
User user = this.asd.selectUser(userId);
ObjectMapper mapper = new ObjectMapper();
response.getWriter().write(mapper.writeValueAsString(user));
}
}
IUserDao.java:
package dao;
import model.User;
import java.util.List;
public interface IUserDao {
//对于读取结果集
//定义方法 listCategory同Category.xml里面的对应
//查询所有的用户,返回类型为集合
List<User> listCategory();
List<User> list();
//总记录数
int total();
//查询
User selectUser(int id);
//添加
void add(User category);
//删除
void delete(int id);
//更新
void update(User category);
}
IUserDaoTest.java:
package dao;
import model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-mybatis.xml"})
public class IUserDaoTest {
@Autowired
private IUserDao dao;
@Test
public void testSelectUser(){
Integer id = 1;
User user = dao.selectUser(id);
System.out.println(user);
}
}
User.java:
package model;
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer 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 "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
IUserService.java:
package service;
import model.User;
public interface IUserService {
User selectUser(Integer userId);
}
UserServiceImpl.java:
package service.impl;
import dao.IUserDao;
import model.User;
import org.springframework.stereotype.Service;
import service.IUserService;
import javax.annotation.Resource;
@Service("userService")
public class UserServiceImpl implements IUserService {
@Resource
private IUserDao userDao;
public User selectUser(Integer userId){
return this.userDao.selectUser(1);
}
}
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">
<!-- 设置为IUserDao接口方法提供sql语句配置 -->
<mapper namespace="dao.IUserDao">
<select id="selectUser" resultType="User" parameterType="int">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
ChatRobots.sql不用添加...
7.运行测试
- 用IUserDaoTest测试:
打开IUserDaoTest.java文件,点击运行代码
正常显示 - 用web测试以下效果
先修改一下index.jsp:
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<script>
function selectUser() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("test").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "user/showUser.do", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("id=1");
}
</script>
<body>
<p id="test">Hello World!</p>
<button type="button" onclick="selectUser()">onclick test</button>
</body>
</html>
然后配置local tomcat运行吧~~
添加local tomcat
添加artifact
选择exploded
点击应用,再点击确认,然后点击运行
运行
成功运行
成功使用
8.出错?
如果报错的话,一般有可能是mysql连接包版本的问题,本项目使用的是mysql6以上的版本,在jdbc.properties中是相关配置,url和com路径和mysql5版本不太一样,具体操作百度吧!
本项目例子学习自博客:https://blog.csdn.net/m0_37787699/article/details/78805281
但是它的代码没有讲创建数据库还有一个类的代码给重复了...
之前我对每个技术都单独写过文章,它们都是单独使用某项技术创建的小demo,而本文是它们的一个集成。
maven的使用:https://www.jianshu.com/p/d1e994c27748
在maven基础下配置spring:https://www.jianshu.com/p/f3ae5b596b2c
在maven基础下配置springmvc:https://www.jianshu.com/p/4a3c30d8f6c9
在maven基础下配置Mybatis:https://www.jianshu.com/p/3cd4feed6a80