【JavaEE】之SSM入门项目的搭建
最近学习了一下SSM。SSM是 Spring + SpringMVC + MyBatis 整合框架,非常适合WEB后台开发,也是当前很多人的不二选择。这篇博客带大家来创建一个学习SSM的入门程序,从搭建框架开始,到实现一个小功能,相信新手朋友们通过这篇博客就可以基本入门开发SSM了。
首先介绍一下本博客使用的开发环境的框架版本:
- 开发环境:IntelliJ IDEA 2016.3 + Tomcat 8.5.8 + Maven
- Spring(MVC)版本:4.3.4.RELEASE
- MyBatis版本:2.8.5
1、新建工程
首先打开IntelliJ IDEA开发工具,点击“Create New Project”,如下图所示:
点击后跳转到如下图所示的界面,选择“Empty Project”(如下图所示选择),然后点击“Next”按钮:
跳转到如下图所示的界面,在Project Name一栏中输入项目名称,然后点击Finish:
这时就进入项目了,但是仍然会弹出一个如下图所示的界面,在这个界面中点击图中所示的“加号”,在弹出的窗口中点击“New Module”:
由于我们是要搭建一个SSM的项目,因此我们参照下图所示的界面,一次选择“JAVA”、“Web Project”,然后点击“Next”按钮:
在弹出的界面中输入Module的名称,然后点击“Finish”按钮(IntelliJ、Android Studio这类开发工具与Eclipse不同,它们的Project相当于Eclipse中的WorkSpace,Module才相当于Eclipse中的Project,也就是说,在这类开发工具中,一个Project中可以包含多个Module):
此时会返回上一个页面,如下图所示,可以看到,新的Module已经添加到项目中了,点击OK:
此时就正式进入到了项目中,现在项目的结构如下图所示:
由于我们的项目需要使用Maven进行版本控制,因此我们需要在项目中添加Maven。在项目名上右键选择“Add Framework Support”,如下图所示:
在弹出的页面中选择Maven,然后点击OK按钮,如下图所示:
此时会打开Maven的pom.xml文件,先在这个文件中指定项目的GroupId(一般是基本包名),然后点击右下角的“Import Changes Enable Auto-Import”。如下图所示:
等待项目加载完成,到此,我们的第一个SSM项目就搭建完成了,现在的项目文件体系架构如下图所示:
2、搭建项目框架
下图是一个基本的SSM项目的文件结构:
首先,我们需要在pom.xml中导入Maven依赖,pom.xml文件中的代码如下:
<?xml version="1.0" encoding="UTF-8"?> <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>my.itgungnir.ssm</groupId> <artifactId>SSMTemplate</artifactId> <version>1.0-SNAPSHOT</version> <!-- 避免Mapper.xml和Mapper.java绑定不成功 --> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <include>**/*.tld</include> <include>**/*.jsp</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <include>**/*.tld</include> </includes> <filtering>true</filtering> </resource> </resources> </build> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.3.4.RELEASE</spring.version> <jackson.version>2.8.5</jackson.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>asm</groupId> <artifactId>asm</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.9</version> </dependency> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-ext-jdk15on</artifactId> <version>1.55</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.2.4</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>3.2.4</version> </dependency> <dependency> <groupId>com.fasterxml</groupId> <artifactId>classmate</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.10</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.4.Final</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.21.0-GA</version> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.3.0.Final</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.7</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.7</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.5</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</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-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</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-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</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>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> </dependencies> </project>
db.properties文件中存储的是数据库有关的数据,如数据库驱动器、用户名、密码等。代码如下:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
jdbc.username=root
jdbc.password=root
log4j.properties文件中存储的是日志相关的参数,代码如下:
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
sqlmap.xml文件中存储的是MyBatis中用到的参数,这里由于和Spring进行了整合,一些代码都转到Spring的配置文件中进行维护了,这个文件中只声明类的别名。代码如下:
<?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="my.itgungnir.ssm.pojo"/> </typeAliases> </configuration>
springconf-context.xml文件中存储的是Spring中的一些几乎不发生变化的参数,如数据库连接池、SqlSessionFactory、事务管理器、mapper批量扫描、AOP等等。代码如下:
<?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" xmlns:aop="http://www.springframework.org/schema/aop" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 加载数据库配置设置 --> <context:property-placeholder location="classpath:db.properties"/> <!-- Druid数据库连接池配置 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="initialSize" value="1"/> <property name="maxActive" value="20"/> <property name="minIdle" value="0"/> <property name="maxWait" value="60000"/> <property name="poolPreparedStatements" value="true"/> <property name="maxPoolPreparedStatementPerConnectionSize" value="33"/> <property name="validationQuery" value="SELECT 'x' FROM DUAL"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="testWhileIdle" value="true"/> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <property name="minEvictableIdleTimeMillis" value="25200000"/> <property name="removeAbandoned" value="true"/> <property name="removeAbandonedTimeout" value="1800"/> <property name="logAbandoned" value="true"/> <property name="filters" value="mergeStat"/> </bean> <!-- 配置SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis/sqlmap.xml"/> </bean> <!-- mapper批量扫描 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="my.itgungnir.ssm.mappers"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- 事务管理器 --> <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="save*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> <tx:method name="select*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!-- AOP --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* my.itgungnir.ssm.service.impl.*.*(..))"/> </aop:config> </beans>
springconf-service.xml文件中存储的是对Service接口的实现类的管理,即Service实现类的BEAN容器。代码如下:
<?xml version="1.0" encoding="UTF-8"?> <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"> <!-- 操作用户信息的Service实现类 --> <bean id="usersService" class="my.itgungnir.ssm.service.impl.UsersServiceImpl"/> </beans>
springmvc.xml文件中存储的是SpringMVC中用到的一些组件,如处理器映射器、处理器适配器、试图解析器、文件上传的解析器、处理器全局扫描等。代码如下:
<?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.xsd"> <!-- 全局扫描Handler --> <context:component-scan base-package="my.itgungnir.ssm.controller"/> <!-- 处理器映射器和适配器 --> <mvc:annotation-driven/> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 前缀 --> <property name="suffix" value=".jsp"/> <!-- 后缀 --> </bean> <!-- 文件上传解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="5242880"/> </bean> </beans>
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>ONE</display-name> <!-- 加载spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <!-- /WEB-INF/classes/spring/applicationContext-*.xml这里的路径设置是怎么回事--> <param-value>/WEB-INF/classes/spring/springconf-context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- springmvc前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> <!-- <load-on-startup>1</load-on-startup> --> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <!--配置Druid数据库连接池的内置监控 --> <servlet> <servlet-name>DruidStatView</servlet-name> <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DruidStatView</servlet-name> <url-pattern>/druid/*</url-pattern> </servlet-mapping> <!-- post乱码过虑器 --> <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> <!--设置session存活时间 --> <session-config> <session-timeout>60</session-timeout> </session-config> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
Users.java文件是数据库中的users表映射而成的实体类,代码如下:
import java.util.Date; /** * Users数据表映射成的POJO类 */ public class Users { private Integer id; private String username; private Date birthday; private Character sex; private String address; public Users() { } public Users(String username, Date birthday, Character sex, String address) { this.username = username; this.birthday = birthday; this.sex = sex; this.address = address; } public Users(Integer id, String username, Date birthday, Character sex, String address) { this.id = id; this.username = username; this.birthday = birthday; this.sex = sex; this.address = address; } 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 Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Character getSex() { return sex; } public void setSex(Character sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
UsersMapper.xml类中存储的是从数据库中读取数据的SQL语句。代码如下:
<?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="my.itgungnir.ssm.mappers.UsersMapper"> <!-- 查询所有用户 --> <select id="selectAllUsers" resultType="my.itgungnir.ssm.Users"> SELECT * FROM users </select> </mapper>
UsersMapper.java类是与XML文件对应的Mapper接口,其路径与XML的namespace相同。代码如下:
import pojo.Users; import java.util.List; /** * Users表的Mapper接口 */ public interface UsersMapper { // 查询所有用户 List<Users> selectAllUsers() throws Exception; }
UsersService.java类是Service接口,代码如下:
import pojo.Users; import java.util.List; /** * 映射到Users表的Service接口 */ public interface UsersService { // 查询所有用户 List<Users> selectAllUsers() throws Exception; }
UsersServiceImpl.java类是Service接口的实现类,其中持有一个UsersMapper的引用,通过mapper来处理得到数据。代码如下:
import mapper.UsersMapper; import org.springframework.beans.factory.annotation.Autowired; import pojo.Users; import service.UsersService; import java.util.List; /** * UsersService接口的实现类 */ public class UsersServiceImpl implements UsersService { @Autowired private UsersMapper mapper; // 查询所有用户 public List<Users> selectAllUsers() throws Exception { return mapper.selectAllUsers(); } }
UsersController.java类是处理器类,通过service接口的动态代理来获取数据,并负责界面的跳转。代码如下:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import pojo.Users; import service.UsersService; import java.util.List; /** * Users的Controller */ @Controller public class UsersController { @Autowired private UsersService service; @RequestMapping("selectAllUsers.action") public String selectAllUsers(Model model) throws Exception { List<Users> users = service.selectAllUsers(); model.addAttribute("users", users); return "users/allusers"; } }
allusers.jsp页面中负责从Controller中得到数据并展示。代码如下:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>所有用户</title> </head> <body> <form action="" method="post"> <table width="100%" border="1"> <tr> <td>姓名</td> <td>出生日期</td> <td>性别</td> <td>地址</td> </tr> <c:forEach items="${users}" var="user"> <tr> <td>${user.username}</td> <td>${user.birthday}</td> <td>${user.sex}</td> <td>${user.address}</td> </tr> </c:forEach> </table> </form> </body> </html>
3、搭建服务器
我们使用的是Tomcat服务器。如果还没有给项目配置Tomcat服务器,那么是不能运行的,如下图所示,运行按钮是置灰的:
此时,我们需要按照下图所示的步骤,点击下拉三角并点击“Edit Configureations”:
跳转到下图所示的界面,按照下图所示的指示,依次点击加号、“Tomcat Server”、“Local”:
点击了“Local”之后,界面会变成如下图所示的样子,我们可以修改服务器名称、JRE版本;如果下面提示“No artifacts marked for deployment”,则点击右侧的“Fix”按钮即可解决问题。最后点击OK按钮:
完成之后,可以看到程序已经可以运行,并且已经选中了一个服务器,如下图所示:
我们可以通过点击上图中的Run或Debug运行程序,运行起来之后,在浏览器的地址栏中输入如下URL,回车运行:
http://localhost:8080/selectAllUsers.action
运行结果如下图所示:
至此,我们的第一个SSM的项目就全部完成啦!希望对大家有帮助~
最后的最后贴出这个项目的【GitHub地址】。
posted on 2016-12-22 14:14 ITGungnir 阅读(4774) 评论(2) 编辑 收藏 举报