本文主要是介绍一步一步教你使用idea+maven+spring4搭建ssm框架,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、在mysql中添加数据库,建立t_users表并添加测试数据。如下图:
2、打开idea,建立maven项目如下图:
3、输入GroupId和ArtifactId,如下图:
4、点击Finish结束项目的创建
5、编写pom文件
<?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>com.keji</groupId><artifactId>ssm</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><properties><spring.version>4.0.2.RELEASE</spring.version><mybatis.version>3.2.6</mybatis.version><slf4j.version>1.7.7</slf4j.version><log4j.version>1.2.17</log4j.version><junit.version>4.10</junit.version></properties><dependencies><!-- 添加Spring依赖 --><dependency><groupId>org.springframework</groupId><artifactId>spring-core</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-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-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-tx</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-web</artifactId><version>${spring.version}</version></dependency><dependency><groupId>aspectj</groupId><artifactId>aspectjrt</artifactId><version>1.5.4</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.4</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.58</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>${junit.version}</version><scope>test</scope></dependency><!-- 日志文件管理包 --><!-- log start --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>${log4j.version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>${slf4j.version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>${slf4j.version}</version></dependency><!-- log end --><!--spring单元测试依赖 --><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version><scope>test</scope></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.2.0</version></dependency><!-- mysql驱动包 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.29</version></dependency><!-- javaee-api包 注意和项目使用的JDK版本对应 --><dependency><groupId>javax</groupId><artifactId>javaee-api</artifactId><version>6.0</version><scope>provided</scope></dependency><dependency><groupId>javax</groupId><artifactId>javaee-web-api</artifactId><version>6.0</version><scope>provided</scope></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency></dependencies>
</project>
6、创建项目结构,完整的项目结构如下图:
java下面为项目的包和类,每个包的含义如下:
mapper:保存mapper接口、entity保存实体类、service保存业务层的接口和实现类、controller保存控制器类。
resource保存项目的资源,具体如下:
application.xml为spring的配置文件、jdbc.properties保存访问jdbc的属性信息、log4j.properties保存日志属性信息、mybatis-config.xml保存mybatis的配置信息、spring-mvc.xml保存springmvc的基本配置
webapp为项目的根目录,相当于myEclipse当中的WebRoot目录
7、在entity下编写实体类,如下:
package com.keji.entity;/*** @author 123* @create 2019/9/2*/
public class User {private int userId;private String userName;private String userPassword;private String userEmail;public User() {}public int getUserId() {return userId;}public void setUserId(int userId) {this.userId = userId;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getUserPassword() {return userPassword;}public void setUserPassword(String userPassword) {this.userPassword = userPassword;}public String getUserEmail() {return userEmail;}public void setUserEmail(String userEmail) {this.userEmail = userEmail;}@Overridepublic String toString() {return "User{" +"userId=" + userId +", userName='" + userName + '\'' +", userPassword='" + userPassword + '\'' +", userEmail='" + userEmail + '\'' +'}';}
}
8、在mapper包下编写UserMapper接口,代码如下:
package com.keji.mapper;import com.keji.entity.User;import java.util.List;/*** @author 123* @create 2019/9/2*/
public interface UserMapper {List<User> getUsers();
}
9、编写UserService接口,代码如下:
package com.keji.service;import com.keji.entity.User;import java.util.List;/*** @author 123* @create 2019/9/2*/
public interface UserService {List<User> getUsers();
}
10、编写UserServiceImpl类,代码如下:
package com.keji.service.impl;import com.keji.entity.User;
import com.keji.mapper.UserMapper;
import com.keji.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/*** @author 123* @create 2019/9/2*/@Service
public class UserServiceImpl implements UserService {@AutowiredUserMapper userMapper;public List<User> getUsers() {return userMapper.getUsers();}
}
11、编写IndexController类,代码如下:
package com.keji.controller;import com.keji.entity.User;
import com.keji.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;import java.util.List;/*** @author 123* @create 2019/9/2*/
@Controller
public class IndexController {@Autowiredprivate UserService userService;@RequestMapping("/users")public String users(Model model) {List<User> users = userService.getUsers();model.addAttribute("users",users);return "userList";}
}
12、在resources的mapper目录下创建UserMapper.xml文件,代码如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.keji.mapper.UserMapper"><select id="getUsers" resultType="User">select USER_ID as userId,USER_NAME as userName,USER_PASSWORD as userPassword,USER_EMAIL as userEmail from t_user</select>
</mapper>
13、创建jdbc.properties
jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/ssm
jdbc_username=root
jdbc_password=root
14、创建log4j.properties
log4j.rootLogger=DEBUG,Console,Stdout#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%nlog4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG log4j.appender.Stdout = org.apache.log4j.DailyRollingFileAppender
log4j.appender.Stdout.File = E://logs/log.log
log4j.appender.Stdout.Append = true
log4j.appender.Stdout.Threshold = DEBUG
log4j.appender.Stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.Stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
15、创建mybatis-config.xml,由于主要的配置信息放在了application.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.keji.entity"/></typeAliases>
</configuration>
16、编写application.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd"><!-- 引入jdbc配置文件 --><bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations"><list><value>classpath:*.properties</value><!--要是有多个配置文件,只需在这里继续添加即可 --></list></property></bean><!-- 配置数据源 --><bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><!-- 使用properties来配置 --><property name="driverClassName"><value>${jdbc_driverClassName}</value></property><property name="url"><value>${jdbc_url}</value></property><property name="username"><value>${jdbc_username}</value></property><property name="password"><value>${jdbc_password}</value></property></bean><!-- 自动扫描了所有的XxxxMapper.xml对应的mapper接口文件,这样就不用一个一个手动配置Mpper的映射了,只要Mapper接口类和Mapper映射文件对应起来就可以了。 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage"value="com.keji.mapper" /></bean><!-- 配置Mybatis的文件 ,mapperLocations配置**Mapper.xml文件位置,configLocation配置mybatis-config文件位置--><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="mapperLocations" value="classpath*:com/keji/mapper/**/*.xml"/><property name="configLocation" value="classpath:mybatis-config.xml" /><!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model"/> --></bean><!-- 自动扫描注解的bean --><context:component-scan base-package="com.keji" /><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><tx:advice id="txAdvice"><tx:attributes><tx:method name="find*" propagation="SUPPORTS" /><tx:method name="add*" propagation="REQUIRED" /><tx:method name="del*" propagation="REQUIRED" /><tx:method name="update*" propagation="REQUIRED" /><tx:method name="*" propagation="REQUIRED" /></tx:attributes></tx:advice><!-- 定义切面 --><aop:config><aop:pointcut id="serviceMethod"expression="execution(* com.keji.service..*.*(..))" /><aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" /></aop:config>
</beans>
17、编写spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:p="http://www.springframework.org/schema/p"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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><!-- 扫描controller(controller层注入) --><context:component-scan base-package="com.keji.controller"/><mvc:resources location="/statics/" mapping="/statics/**"></mvc:resources><mvc:annotation-driven><mvc:message-converters><bean class="org.springframework.http.converter.StringHttpMessageConverter"><property name="supportedMediaTypes"><list><value>application/json;charset=UTF-8</value></list></property></bean><bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"><property name="supportedMediaTypes"><list><value>text/html;charset=UTF-8</value><value>application/json</value></list></property><property name="features"><list><!-- Date的日期转换器 --><value>WriteDateUseDateFormat</value></list></property></bean></mvc:message-converters></mvc:annotation-driven><!-- 对模型视图添加前后缀 --><bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"p:prefix="/WEB-INF/view/" p:suffix=".jsp"/><!-- 配置interceptors --><mvc:interceptors><mvc:interceptor><mvc:mapping path="/sys/**"/><bean class="com.keji.web.SysInterceptor"/></mvc:interceptor></mvc:interceptors><!-- 配置MultipartResolver,用于上传文件,使用spring的CommonsMultipartResolver --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="maxUploadSize" value="5000000"/><property name="defaultEncoding" value="UTF-8"/></bean>
</beans>
上面的配置文件当中还使用了拦截器,因此需要在项目当中创建一个拦截器类:
package com.keji.web;import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class SysInterceptor implements HandlerInterceptor {/*** 在访问目标方法之前的前置处理* @param httpServletRequest* @param httpServletResponse* @param o* @return* @throws Exception*/public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {//return false表示拦截,return true表示放行return false;}/*** 访问目标方法之后,渲染视图之前的处理* @param httpServletRequest* @param httpServletResponse* @param o* @param modelAndView* @throws Exception*/public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {}/*** 访问目标方法之后并且已经渲染视图之后的后置处理* @param httpServletRequest* @param httpServletResponse* @param o* @param e* @throws Exception*/public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {}
}
18、编写web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="WebApp_ID" version="2.5"><display-name>Archetype Created Web Application</display-name><!-- 起始欢迎界面 --><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><!-- 读取spring配置文件 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:application.xml</param-value></context-param><!-- 设计路径变量值 --><context-param><param-name>webAppRootKey</param-name><param-value>springmvc.root</param-value></context-param><!-- Spring字符集过滤器 --><filter><filter-name>SpringEncodingFilter</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>SpringEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 日志记录 --><context-param><!-- 日志配置文件路径 --><param-name>log4jConfigLocation</param-name><param-value>classpath:log4j.properties</param-value></context-param><context-param><!-- 日志页面的刷新间隔 --><param-name>log4jRefreshInterval</param-name><param-value>6000</param-value></context-param><listener><listener-class>org.springframework.web.util.Log4jConfigListener</listener-class></listener><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- springMVC核心配置 --><servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><!--spingMVC的配置路径 --><param-value>classpath:spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><!-- 拦截设置 --><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!-- 错误跳转页面 --><error-page><!-- 路径不正确 --><error-code>404</error-code><location>/WEB-INF/errorpage/404.jsp</location></error-page><error-page><!-- 没有访问权限,访问被禁止 --><error-code>405</error-code><location>/WEB-INF/errorpage/405.jsp</location></error-page><error-page><!-- 内部错误 --><error-code>500</error-code><location>/WEB-INF/errorpage/500.jsp</location></error-page>
</web-app>
20、在webapp目录下创建index.jsp文件
<%--Created by IntelliJ IDEA.User: 123Date: 2019/9/2Time: 14:38To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
hello this is ssm project.
<a href="users">userList</a>
</body>
</html>
21、在WEB-INF/wiew下创建userList.jsp
<%--Created by IntelliJ IDEA.User: 123Date: 2019/9/2Time: 14:48To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head><title>Title</title>
</head>
<body>
<table>
<c:forEach items="${users}" var="user"><tr><td>${user.userId}</td><td>${user.userName}</td><td>${user.userPassword}</td><td>${user.userEmail}</td></tr>
</c:forEach>
</table>
</body>
</html>
至此,ssm项目搭建完成,不过要想运行还需要再idea当中进行一些设置:
1)点击File→Project Structure出现如下图的界面:
2)点击旁边的+号选择web,如下图:
选择module为ssm后点击ok
3)点击ok后右侧需要选择项目的web.xml文件的位置和项目的根目录的位置,如下图:
4)同样的道理还需要选择web项目的根目录的位置,我们的项目根目录的位置是webapp目录,如下图:
5)最后需要对tomcat进行设置,如下图:
最后启动项目进行测试,点击运行按钮,如下图:
这是首页的效果,点击超链接可以看到用户列表,如下图:
至此,使用idea+maven搭建ssm框架完成。
这篇关于一步一步教你使用idea+maven+spring4搭建ssm框架的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!