以后写的每一次博客,目的都要明确,广大的友友们相信你们也是这样,这篇主要是为了对我SSM框架中遭遇的一些问题进行总结,希望能给后来搭建SSM框架的朋友带来帮助........
一.准备开发环境maven:apache-maven-3.3.9jdk:jdk1.8.0_111 配置环境变量tomcat:tomcat-8.0.32mysql:c3p0 连接的mysql
二.进入eclipse配置Maven,Jdk
1、Window——>Preferences——>Maven——>设置自己的User Settings
2、Window——>Preferences——>Java——>Installed JREs——>Add
三、一切准备就绪之后,创建一个maven项目,给pom.xml文件配置整合SSM所需的依赖
<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.fuiou</groupId>
<artifactId>maven-ssm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>maven-ssm Maven Webapp</name>
<url>http://maven.apache.org</url>
<!-- 属性参数 -->
<properties>
<!-- spring版本号 -->
<spring.version>4.3.10.RELEASE</spring.version>
<mybatis.version>3.4.1</mybatis.version>
</properties>
<dependencies>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
<scope>test</scope>
</dependency>
<!-- 依赖的servlet包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- spring核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring的web包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</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-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- jdbc数据库连接包,事务等等 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- springmvc的包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 面向切面的包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 全局context的包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 测试包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</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.3.0</version>
</dependency>
<dependency>
<!-- 数据库驱动 -->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
</dependency>
<!-- jsp页面使用taglib c标签 -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>maven-ssm</finalName>
</build>
![](https://i-blog.csdnimg.cn/blog_migrate/70c32147f0709ecd6bda9749ba9cb05c.png)
![抓狂](https://static-blog.csdn.net/xheditor/xheditor_emot/default/crazy.gif)
![抓狂](https://static-blog.csdn.net/xheditor/xheditor_emot/default/crazy.gif)
![抓狂](https://static-blog.csdn.net/xheditor/xheditor_emot/default/crazy.gif)
private int uid;
private String uname;
private String upwd;
private String status;
return uid;
}
this.uid = uid;
}
return uname;
}
this.uname = uname;
}
return upwd;
}
this.upwd = upwd;
}
return status;
}
this.status = status;
}
public String toString() {
return "UserPojo [uid=" + uid + ", uname=" + uname + ", upwd=" + upwd + ", status=" + status + "]";
}
public List<UserPojo> findAll();
public UserPojo findByName(String name);
public int add(UserPojo userPojo);
}
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.fuiou.ssm.mapper.IUserMapper">
<!-- 实体类和数据库中表的列名一致可不写 -->
<resultMap id="BaseResultMap" type="com.fuiou.ssm.pojo.UserPojo">
<result column="uid" property="uid" jdbcType="INTEGER" />
<result column="uname" property="uname" jdbcType="VARCHAR" />
<result column="upwd" property="upwd" jdbcType="VARCHAR" />
<result column="status" property="status" jdbcType="VARCHAR" />
</resultMap>
<sql id="user_column_list">
uid,uname,upwd,status
</sql>
<select id="findAll" resultMap="BaseResultMap">
SELECT
<include refid="user_column_list" />
FROM DB_USER
</select>
<select id="findByName" resultMap="BaseResultMap" parameterType="String">
SELECT
<include refid="user_column_list" />
FROM DB_USER
WHERE UNAME=#{uname}
</select>
<insert id="add" parameterType="com.fuiou.ssm.pojo.UserPojo">
INSERT INTO DB_USER VALUES(NULL,#{uname},#{upwd},#{status})
</insert>
</mapper>
IUserService.java:
public List<UserPojo> findAll();
public UserPojo login(UserPojo userPojo);
public int register(UserPojo userPojo);
}
UserServiceImpl.java:
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.fuiou.ssm.pojo.UserPojo;
import com.fuiou.ssm.service.IUserService;
//使用注解交给spring
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private IUserMapper ium;
@Override
public List<UserPojo> findAll() {
return ium.findAll();
}
public UserPojo login(UserPojo userPojo) {
UserPojo loginUser=ium.findByName(userPojo.getUname());
if(loginUser!=null) {
if(loginUser.getUpwd().equals(userPojo.getUpwd())) {
return loginUser;
}
}
return null;
}
//注解强制使用事务
//@Transactional(propagation=Propagation.REQUIRED)
public int register(UserPojo userPojo) {
//测试
//ium.insert(userPojo);
//手动制造错误,出错后回滚
//int i = 1/0;
//UserPojo userPojo2= new UserPojo();
//userPojo2.setUname(userPojo.getUname()+"的副本");
return ium.add(userPojo);
}
4.到这里我们先来配置资源文件Spring的applicationContext-db.xml文件和mybatisConfig.xml文件
applicationContext-db.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd ">
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- spring配置接管mybatis -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatisConfig.xml"></property>
</bean>
<!-- 扫描mybatis的mapper映射文件 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描的包 -->
<property name="basePackage" value="com.fuiou.ssm.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- 扫描service层 -->
<context:component-scan base-package="com.fuiou.ssm.service.impl"></context:component-scan>
<!-- 注册事物 -->
<bean id="transManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 开启注解事物 -->
<tx:annotation-driven transaction-manager="transManager" />
</beans>
mybatisConfig.xml:
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" >
<!-- 我这里没配,如果你要用到mybatis的插件就自己配一下 -->
<configuration>
5.到这里为止我们写了这么多也不知道有没有问题,先不要着急把整个框架搭完,我们先来测试一下,现在配的Spring+Mybatis有没有问题,一次性搭完你中途不知道有错误没有,最后项目一启动一堆报错,把自己都要搞懵逼,得不偿失!
回归正题,在src/test/java目录下创建专属测试类,如下
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.fuiou.ssm.pojo.UserPojo;
import com.fuiou.ssm.service.IUserService;
//使用junit和spring-test整合测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext-db.xml"})
public class TestA1 {
@Autowired
private IUserMapper ium;
@Test
public void testAdd() {
UserPojo userPojo=new UserPojo();
userPojo.setUname("意大利炮");
userPojo.setUpwd("eryingzhang");
userPojo.setStatus("正常");
int line=ium.add(userPojo);
System.out.println("进入到测试中,插入了"+line+"数据");
}
}
![偷笑](https://static-blog.csdn.net/xheditor/xheditor_emot/default/titter.gif)
![偷笑](https://static-blog.csdn.net/xheditor/xheditor_emot/default/titter.gif)
![偷笑](https://static-blog.csdn.net/xheditor/xheditor_emot/default/titter.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/db52cbe9a0a59b2193defb5f8a2e6c16.png)
这里注意测试中不仅可以使用mapper层的接口,还可以使用Service层的,他们之间的区别是service层可以有逻辑的操作,也就是业务,可以使用事物,如果你在service层中的新增手动制造一个错误,数据库一刷新你就会发现,这个操作还是执行了,这在现实中是绝对不可以的,添加Spring注解事物可以很好解决这个问题
5.Interceptor层→LoginInterceptor.java
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
/**
* controller执行后且视图返回后调用此方法
* 这里可得到执行controller时的异常信息
* 这里可记录操作日志,资源清理等
*/
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
throws Exception {
System.out.println("完成视图渲染");
}
/**
* controller执行后但未返回视图前调用此方法
* 这里可在返回用户前对模型数据进行加工处理,比如这里加入公用信息以便页面显示
*/
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("退出controller,准备进入视图解析器");
}
/**
* controller执行前调用此方法
* 返回true表示继续执行,返回false中止执行
* 这里可以加入登录校验、权限拦截等
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
System.out.println("进入controller之前");
UserPojo user = (UserPojo) request.getSession().getAttribute("loginUser");
if(user!=null) {
return true;
}else {
response.sendRedirect("login.html");
return false;
}
}
6.再到controller层→LoginUserController.java和TopageController.java
LoginUserController.java:
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
public class LoginUserController {
@Autowired
private IUserService ius;
//登陆之后查询User表所有信息
@RequestMapping("/login.action")
public String login(UserPojo user,HttpSession session,HttpServletRequest request) {
UserPojo loginUser=ius.login(user);
if(loginUser!=null) {
List<UserPojo> userList=ius.findAll();
System.out.println(userList);
request.setAttribute("list", userList);
session.setAttribute("loginUser", loginUser);
return "index";
}else {
return "error";
}
}
}
TopageController.java:
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
//去任何项目任何一个静态页面,默认放在WEN-INF下的jsp不可以直接被访问
@Controller
public class TopageController {
@RequestMapping("/{page}.html")
public String toPage(@PathVariable String page) {
return page;
}
}
7.然后在资源目录下配置springmvc.xml文件,如下
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd ">
<!-- 非注解的bean声明注入 -->
<!-- <bean name="/testController" class="com.fuiou.ssm.controller.TestController"/> -->
<!-- 非注解处理器映射器 -->
<!-- <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> -->
<!-- 非注解处理器适配器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> -->
<!-- 注解映射器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
<!-- 注解适配器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->
<!-- 开启注解驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 允许对静态资源文件的访问 -->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<!-- 扫描 Controller包-->
<context:component-scan base-package="com.fuiou.ssm.controller"></context:component-scan>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置拦截器 -->
<bean id="loginInterceptor" class="com.fuiou.ssm.interceptor.LoginInterceptor"></bean>
<mvc:interceptors>
<!-- 配置一个拦截器 -->
<mvc:interceptor>
<!-- 配置拦截的路径 -->
<mvc:mapping path="/**"/>
<!-- 排除不拦截的路径 -->
<mvc:exclude-mapping path="/login*"/>
<ref bean="loginInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
<!-- 配置让springMVC给script,css,image放行
mvc:resource资源配置
location: 物理文件路径
mapping: 映射文件路径
**: 所有文件
-->
<!-- <mvc:resources location="/image/" mapping="/image/**"/> -->
<!-- <mvc:resources location="/css/" mapping="/css/**"/> -->
<!-- <mvc:resources location="/js/" mapping="/js/**"/> -->
8.整合终于只有最后一步啦,配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">
<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:applicationContext-db.xml</param-value>
</context-param>
<!-- 配置监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- 配置springMVC -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--用来标记是否在项目启动时就加在此Servlet,0或正数表示容器在应用启动时就加载这个Servlet,
当是一个负数时或者没有指定时,则指示容器在该servlet被选择时才加载.正数值越小启动优先值越高 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<!-- 拦截所有请求,千万注意springMVC是(/)而不是(/*) Struts2-->
<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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
9.最后一步就大功告成了,在webapp下导入静态资源文件并在WEB-INF目录下创建jsp目录用于存放jsp文件,把项目使用tomcat跑起来一起去试试吧 最后如下图所示,那么恭喜你成功了!!!!
欢迎页面:
登录页面:
登录成功,去首页:
登录失败,返回错误页面:
五.终于要写完了,我简直了,总结:我搭建SSM框架遇到了一个问题,把它分享出来,希望广大的博客友友不要出这样的错误,真的头痛,分享问题的解决方案,问题:
这个问题是我路径的问题,友友们注意啦,出现404无疑有两种情况:1.配置文件中出了问题,2.路径书写错误,仔细看看哦
配置文件中出了问题:有三个地方需要注意
1.控制层没有被spring扫描到,控制层没有实例化,检查自己的控制层是否被spring扫描到,检查以下配置:<context:component-scan base-package=""/>
2.web.xml配置文件的<url-pattern>标签配置成<url-pattern>/*</url-pattern>,正确的配置应该是<url-pattern>/</url-pattern>
3.使用的是注解实例化控制层,且web.xml的路径配置为<url-pattern>/</url-pattern>,却没有在spring的配置文件使用<mvc:annotation-driven />标签,导致URL解析出错,检查是否加上<mvc:annotation-driven />
我的问题是第二种,当时傻逼了,想了好久,配置看了很多遍没有问题,最后检查路径的时候...................内心崩溃!!!!!!!