一步步教你整合SSM框架(Spring MVC+Spring+MyBatis)详细教程
什么是SSM框架?
SSM框架是Spring MVC + Spring + MyBatis三个框架的组合。它们都是Java企业级应用程序开发中非常流行的框架。Spring MVC框架负责请求处理,Spring框架负责业务逻辑处理和依赖注入,MyBatis框架负责数据库操作。
整合SSM框架的好处
- 提高代码复用率和软件维护性;
- 提高开发效率;
- 可以快速搭建Java Web应用;
- 对于一些复杂的应用,使用SSM框架可以有效地降低开发难度和维护成本,提高整个应用的性能。
整合SSM框架的步骤
- 引入相关依赖
在pom.xml文件中添加如下依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
- 配置Spring
在src/main/resources目录下创建一个名为applicationContext.xml的文件,添加如下内容:
<!-- 开启自动扫描注解 -->
<context:component-scan base-package="com.example.controller" />
<context:component-scan base-package="com.example.service" />
<context:component-scan base-package="com.example.dao" />
<!-- MyBatis的SqlSessionFactory配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath*:com/example/dao/*.xml" />
</bean>
<!-- 数据源配置 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=utf8" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean>
<!-- MyBatis的MapperScannerConfigurer配置 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.dao" />
</bean>
<!-- 开启Spring MVC注解驱动,静态资源处理 -->
<mvc:annotation-driven />
<mvc:resources mapping="/static/**" location="/static/" />
<!-- 配置ViewResolver,返回freemarker模板 -->
<bean id="freemarkerConf" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/freemarker/" />
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="order" value="1" />
<property name="prefix" value="" />
<property name="suffix" value=".ftl" />
<property name="contentType" value="text/html;charset=UTF-8" />
<property name="cache" value="false" />
</bean>
- 配置Spring MVC
在web.xml文件中添加如下内容:
<!-- 配置DispatcherServlet -->
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置字符编码过滤器 -->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- 配置MyBatis
在src/main/resources目录下创建一个名为mybatis.xml的文件,添加如下内容:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 别名 -->
<typeAliases>
<package name="com.example.model" />
</typeAliases>
<!-- 数据库连接配置 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=utf8" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<!-- 映射器 -->
<mappers>
<mapper resource="com/example/dao/UserMapper.xml"/>
</mappers>
</configuration>
- 编写数据库操作代码
package com.example.dao;
import com.example.model.User;
import org.apache.ibatis.annotations.Param;
public interface UserDao {
User getUserByUsername(@Param("username") String username);
}
<?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.example.dao.UserDao">
<!-- 通过username获取用户信息 -->
<select id="getUserByUsername" parameterType="string" resultType="com.example.model.User">
select * from user where username = #{username}
</select>
</mapper>
- 编写业务逻辑代码
package com.example.service;
import com.example.model.User;
public interface UserService {
User getUserByUsername(String username);
}
package com.example.service.impl;
import com.example.dao.UserDao;
import com.example.model.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User getUserByUsername(String username) {
return userDao.getUserByUsername(username);
}
}
- 编写控制器代码
package com.example.controller;
import com.example.model.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/{username}")
public String getUserByUsername(@PathVariable String username, ModelMap map) {
User user = userService.getUserByUsername(username);
map.put("user", user);
return "user";
}
}
- 编写视图文件
在WEB-INF/freemarker目录下创建一个名为user.ftl的文件,添加如下内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户信息</title>
</head>
<body>
<h1>用户信息</h1>
<p>用户名:${user.username}</p>
<p>密码:${user.password}</p>
</body>
</html>
示例说明
示例一:获取用户信息
- 在数据库中添加一条用户信息:
INSERT INTO `test`.`user`(`username`, `password`) VALUES ('admin', '123456');
- 启动Web服务器,访问URL:
http://localhost:8080/user/admin
就可以看到输出用户信息的页面。
示例二:修改用户密码
- 在UserDao中添加一个updateUserPassword方法:
package com.example.dao;
import com.example.model.User;
import org.apache.ibatis.annotations.Param;
public interface UserDao {
User getUserByUsername(@Param("username") String username);
void updateUserPassword(@Param("username") String username, @Param("newPassword") String newPassword);
}
<?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.example.dao.UserDao">
<!-- 通过username获取用户信息 -->
<select id="getUserByUsername" parameterType="string" resultType="com.example.model.User">
select * from user where username = #{username}
</select>
<!-- 修改用户密码 -->
<update id="updateUserPassword" parameterType="map">
update user set password = #{newPassword} where username = #{username}
</update>
</mapper>
- 在UserService中添加一个updateUserPassword方法:
package com.example.service;
public interface UserService {
void updateUserPassword(String username, String newPassword);
}
package com.example.service.impl;
import com.example.dao.UserDao;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
@Transactional
public void updateUserPassword(String username, String newPassword) {
userDao.updateUserPassword(username, newPassword);
}
}
- 在UserController中添加一个updateUserPassword方法:
package com.example.controller;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/{username}")
public String getUserByUsername(@PathVariable String username, ModelMap map) {
User user = userService.getUserByUsername(username);
map.put("user", user);
return "user";
}
@RequestMapping("/updatePassword/{username}/{newPassword}")
public String updateUserPassword(@PathVariable String username, @PathVariable String newPassword) {
userService.updateUserPassword(username, newPassword);
return "success";
}
}
- 在WEB-INF/freemarker目录下创建一个名为success.ftl的文件,添加如下内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改密码成功</title>
</head>
<body>
<h1>修改密码成功</h1>
</body>
</html>
- 启动Web服务器,访问URL:
http://localhost:8080/user/updatePasword/admin/654321
就可以看到提示修改密码成功的页面。
以上是整合SSM框架的详细教程和两个示例的说明。如果您需要更多的框架资料和帮助,可以查看官方网站或者其他技术博客。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:一步步教你整合SSM框架(Spring MVC+Spring+MyBatis)详细教程 - Python技术站