Java-搭建SSM项目练习

SSM项目:Spring + SpringMVC + Mybatis

  这是一个SSM项目的搭建基本流程,主要来源于互联网。

第一步:先搭建好数据库:

1
2
3
4
5
6
7
8
9
10
11
12
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`email` varchar(255) NOT NULL COMMENT '用户邮箱',
`password` varchar(255) NOT NULL COMMENT '用户密码',
`username` varchar(255) NOT NULL COMMENT '用户昵称',
`role` varchar(255) NOT NULL COMMENT '用户身份',
`status` int(1) NOT NULL COMMENT '用户状态',
`regTime` datetime NOT NULL COMMENT '注册时间',
`regIp` varchar(255) NOT NULL COMMENT '注册IP',
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

第二步、按项目结构图,在IDEA中搭建项目架构:

第三步、配置其中的各个文件,倒序配置,先配置web.xml文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?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>ChatRobot</display-name>
<description>ChatRobot_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.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

然后配置spring-mybatis.xml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?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">


<!-- 配置数据库相关参数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="com.MySSM.model"/>
<!-- 扫描sql配置文件:mapper需要的xml文件 -->
<property name="mapperLocations" value="classpath:mapper/IUserDao.xml"/>
</bean>

<!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.MySSM.dao"/>
</bean>

<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
</bean>

<!-- 配置基于注解的声明式事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

配置spring-mvc.xml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?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="com.MySSM.*"/>

<!-- 开启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>

配置logback.xml文件

1
2
3
4
5
6
7
8
9
10
11
<?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>

配置jdbc.properties文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
jdbc.driver=com.mysql.jdbc.Driver
#数据库地址
jdbc.url=jdbc:mysql://localhost:3306/myssm #url根据实际情况填写
#用户名
jdbc.username=root
#密码
jdbc.password=12345
#最大连接数
c3p0.maxPoolSize=30
#最小连接数
c3p0.minPoolSize=10
#关闭连接后不自动commit
c3p0.autoCommitOnClose=false
#获取连接超时时间
c3p0.checkoutTimeout=10000
#当获取连接失败重试次数
c3p0.acquireRetryAttempts=2

配置mybatis的映射文件:IUserDao.xml文件

1
2
3
4
5
6
7
8
9
10
11
12
<?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.MySSM.dao.IUserDao">

<select id="selectUser" resultType="User" parameterType="long">
SELECT * FROM user WHERE id = #{id}
</select>

</mapper>

IUserService接口代码:

1
2
3
4
5
6
7
8
9
package com.MySSM.service;

import com.MySSM.model.User;

public interface IUserService {

public User selectUser(long userId);

}

UserServiceImpl 实现类代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.MySSM.service.impl;

import com.MySSM.dao.IUserDao;
import com.MySSM.model.User;
import com.MySSM.service.IUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("userService")
public class UserServiceImpl implements IUserService {

@Resource
private IUserDao userDao;

public User selectUser(long userId) {
return this.userDao.selectUser(userId);
}
}

User 实体类代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.MySSM.model;

import java.util.Date;

public class User {

private long id;
private String email;
private String password;
private String username;
private String role;
private int status;
private Date regTime;
private String regIp;

public long getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getRole() {
return role;
}

public void setRole(String role) {
this.role = role;
}

public int getStatus() {
return status;
}

public void setStatus(int status) {
this.status = status;
}

public Date getRegTime() {
return regTime;
}

public void setRegTime(Date regTime) {
this.regTime = regTime;
}

public String getRegIp() {
return regIp;
}

public void setRegIp(String regIp) {
this.regIp = regIp;
}

}

IUserDao 接口代码:

1
2
3
4
5
6
7
8
9
package com.MySSM.dao;

import com.MySSM.model.User;

public interface IUserDao {

User selectUser(long id);

}

UserController 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.MySSM.controller;

import javax.json.Json;
import javax.servlet.http.HttpServletRequest;

import com.MySSM.model.User;
import com.MySSM.service.IUserService;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
@RequestMapping("/user")
public class UserController {

@Resource
private IUserService userService;

@RequestMapping("/showUser.do")
public void selectUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
long userId = Long.parseLong(request.getParameter("id"));
User user = this.userService.selectUser(userId);

PrintWriter out = response.getWriter();
String jsonString = JSON.toJSONString(user);

if(jsonString != null){
out.write(jsonString);
}else{
out.write("出错了");
}
out.close();
}
}

index.jsp测试页面代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script>
$(function () {
$("#selectUser").click(function () {
var id = $("#userId").val();
$.ajax({
method: "post",
url: "user/showUser.do",
data: {id: id},
dataType: "json",
success: function (result) {
alert(result.username)
}
})
})
}
)
</script>
</head>
<body>
<p id="test">Hello World!</p>
请输入id:<input type="text" id="userId" value="1">
<button type="button" id="selectUser">这是一号</button>
</body>
</html>

基本的搭建情况如图,完成后,将项目部署到Tomcat之后,就可以通过项目的index页面访问到数据库中的数据,并且显示到页面上。点击button按钮,获取数据,并显示。