SSM框架是Spring、Spring MVC和MyBatis三个开源框架的整合,使得企业级Java应用开发更加简单高效。该框架通过IoC容器、MVC实现和持久层映射简化了应用的开发和维护。文章详细介绍了SSM框架的组成部分、优势和应用场景,并通过实战案例展示了其在项目中的具体应用。
SSM框架简介SSM框架是Spring、Spring MVC和MyBatis三个开源框架的整合,使得企业级Java应用开发变得更加简单、高效和规范。
SSM框架是一种流行的Java Web开发框架,它集成了Spring、Spring MVC和MyBatis框架。Spring框架提供了IoC容器和DI机制,简化了Java应用的开发和测试;Spring MVC是一个基于Spring框架的MVC实现,提供了更为便捷的Web开发体验;而MyBatis框架则是一个优秀的持久层框架,简化了对数据库的操作。
Spring框架:
Spring MVC框架:
优势:
开发环境搭建是SSM框架开发的第一步,需要安装和配置开发工具、JDK以及创建Maven项目。
开发工具的选择:
安装JDK:
java -version
,检查安装是否成功。创建Maven项目:
groupId
、artifactId
、version
等。<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>ssm-demo</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.10</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.10</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.10</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.32</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.32</version> </dependency> </dependencies> </project>
MyBatis核心配置文件:
mybatis-config.xml
:定义数据库连接信息和全局配置。
<configuration> <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/mydb"/> <property name="username" value="root"/> <property name="password" value="password"/> </dataSource> </environment> </environments> </configuration>
<configuration> <properties resource="db.properties"/> <typeAliases> <typeAlias alias="User" type="com.example.model.User"/> </typeAliases> <mappers> <mapper resource="com/example/mapper/UserMapper.xml"/> </mappers> </configuration>
Spring是一个强大的企业级应用框架,它通过控制反转(IoC)和依赖注入(DI)机制来简化Java应用的开发。
控制反转(IoC):
配置文件编写:
applicationContext.xml
。配置文件示例:
<beans xmlns="http://www.springframework.org/schema/beans" 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"> <bean id="exampleBean" class="com.example.ExampleBean"> <property name="property1" value="value1"/> <property name="property2" value="value2"/> </bean> </beans>
Spring容器加载配置文件:
ClassPathXmlApplicationContext
加载配置文件。
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); ExampleBean exampleBean = (ExampleBean) context.getBean("exampleBean");
<bean>
:定义一个Bean。<property>
:设置Bean的属性。<constructor-arg>
:设置构造函数的参数。Bean的创建:
<bean>
标签定义Bean。id
或name
属性指定Bean的名称。class
属性指定Bean的实现类。Bean的作用域:
<bean id="singletonBean" class="com.example.SingletonBean" scope="singleton"/> <bean id="prototypeBean" class="com.example.PrototypeBean" scope="prototype"/>
MyBatis是一个优秀的持久层框架,它简化了Java对数据库的操作。MyBatis主要通过配置文件来定义SQL语句的映射关系,然后通过SqlSession对象执行这些SQL语句。
MyBatis核心配置文件:
mybatis-config.xml
:定义数据库连接信息和全局配置。
<configuration> <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/mydb"/> <property name="username" value="root"/> <property name="password" value="password"/> </dataSource> </environment> </environments> </configuration>
<configuration> <properties resource="db.properties"/> <typeAliases> <typeAlias alias="User" type="com.example.model.User"/> </typeAliases> <mappers> <mapper resource="com/example/mapper/UserMapper.xml"/> </mappers> </configuration>
定义Mapper接口:
public interface UserMapper { List<User> selectAllUsers(); }
编写XML映射文件:
UserMapper.xml
文件中定义SQL语句。
<mapper namespace="com.example.mapper.UserMapper"> <select id="selectAllUsers" resultType="com.example.model.User"> SELECT * FROM users </select> </mapper>
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("SqlMapConfig.xml")); SqlSession sqlSession = sqlSessionFactory.openSession(); List<User> users = sqlSession.selectList("com.example.mapper.UserMapper.selectAllUsers");
整合配置:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="mapperLocations" value="classpath*:mapper/*.xml"/> </bean>
配置Mapper扫描:
MapperScannerConfigurer
扫描Mapper接口。
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.example.mapper"/> </bean>
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.example.mapper"/> </bean>
Spring MVC是一种基于Model-View-Controller(MVC)设计模式的Web框架,它通过前端控制器(DispatcherServlet)将请求分发到相应的处理器(Handler)。
创建Controller类:
@Controller
注解标记Controller类。@RequestMapping
注解映射具体的URL和Handler方法。
@Controller public class UserController { @RequestMapping("/userList") public String getUserList(Model model) { // 业务逻辑 return "userList"; } }
@RequestParam
注解获取请求参数。
@RequestMapping("/user") public String getUserById(@RequestParam("id") String id, Model model) { // 业务逻辑 return "user"; }
创建Model类:
定义数据模型对象,通常使用@Entity
或简单的JavaBean。
public class User { private int id; private String name; private String email; // getter和setter方法 }
public interface UserDao { List<User> findAll(); User findById(int id); }
视图解析器配置:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean>
视图解析器工作原理:
userList.jsp
视图文件。
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>User List</title> </head> <body> <h1>User List</h1> <ul> <c:forEach var="user" items="${users}"> <li>${user.name}</li> </c:forEach> </ul> </body> </html>
案例设计:
项目目录结构:
src/main/java
:存放Java源代码。src/main/resources
:存放配置文件和资源文件。src/main/webapp
:存放Web资源,如JSP页面、静态文件等。目录规划示例:
src/main/java ├── com.example.controller │ └── UserController.java ├── com.example.mapper │ └── UserMapper.java ├── com.example.model │ └── User.java └── com.example.service └── UserService.java src/main/resources ├── mybatis-config.xml ├── mapper │ └── UserMapper.xml └── applicationContext.xml src/main/webapp ├── WEB-INF │ └── views │ └── userList.jsp └── web.xml
UserMapper.java:
public interface UserMapper { List<User> selectAll(); User selectById(int id); }
UserMapper.xml:
<mapper namespace="com.example.mapper.UserMapper"> <select id="selectAll" resultType="com.example.model.User"> SELECT * FROM users </select> <select id="selectById" resultType="com.example.model.User"> SELECT * FROM users WHERE id = #{id} </select> </mapper>
UserService.java:
public class UserService { private UserMapper userMapper; public UserService(UserMapper userMapper) { this.userMapper = userMapper; } public List<User> getAllUsers() { return userMapper.selectAll(); } public User getUserById(int id) { return userMapper.selectById(id); } }
UserController.java:
@Controller @RequestMapping("/user") public class UserController { private UserService userService; public UserController(UserService userService) { this.userService = userService; } @RequestMapping("/list") public String getUserList(Model model) { List<User> users = userService.getAllUsers(); model.addAttribute("users", users); return "userList"; } @RequestMapping("/show/{id}") public String getUserById(@PathVariable("id") int id, Model model) { User user = userService.getUserById(id); model.addAttribute("user", user); return "user"; } }
applicationContext.xml:
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.example.mapper"/> </bean> <bean id="userService" class="com.example.service.UserService"> <constructor-arg> <ref bean="userMapper"/> </constructor-arg> </bean>
web.xml:
<web-app> <display-name>My User Manager</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/dispatcher-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean>
部署步骤:
通过以上步骤,你可以完成一个简单的SSM项目开发,实现用户信息的注册、登录、查询等功能。