分享

SSM框架整合完整案例

 春和秋荣 2020-04-25

这篇文章用SSM框架整合来完成一个全查商品表(items),并将所有的商品信息展示到页面(showitems.jsp)中这样的功能,让大家快速熟练使用SSM框架。

一、整合思路

因为spring框架功能强大,涉及到整个web分层,所以这次的整合以spring框架为基础,mybatis负责dao层,spring mvc 负责controller层
最终项目文件结构如下图:
在这里插入图片描述

二、案例实战

1. 项目前期准备

新建web工程,导入SSM框架项目需要的jar包。另外需要在数据库(我这边使用mysql数据库)创建items表,添加数据,数据库表如下图:
在这里插入图片描述

2. 整合dao层

① mybatis全局配置文件(SqlConfig.xml)

<configuration>
	<settings>
		<setting name="logImpl" value="LOG4J"/>
	</settings>
	<typeAliases>
		<!-- 给vo包中的所有java bean起别名,别名就是类名 -->
		<package name="com.byzx.ssm.vo"/>
	</typeAliases>
	<!-- 数据源的配置交给spring -->
	<!-- 关联映射文件交给sping的mapper扫描器 -->
</configuration>

log4j.properties:

# Global logging configuration
# developer-->DEBUG product-->INFO or ERROR
log4j.rootLogger=DEBUG, stdout
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

② 配置spring.xml

	<!-- 扫描service包,让service的注解起作用 -->
    <context:component-scan base-package="com.byzx.ssm.service"></context:component-scan>
    
    <!-- 加载db.properties -->
    <context:property-placeholder location="classpath:db.properties" />
    
    <!-- 配置c3p0数据源 -->
    <bean id="c3p0ds" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driver}" ></property>
		<property name="jdbcUrl" value="${jdbc.url}" ></property>
		<property name= "user" value="${jdbc.username}" ></property>
		<property name= "password" value="${jdbc.password}" ></property>
		<property name="maxPoolSize" value="30"></property>
		<property name="initialPoolSize" value="5"></property>
	</bean>
	
	<!-- 配置SqlSessionFactory -->
	<bean id="ssf" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="c3p0ds"></property>
		<property name="configLocation" value="classpath:SqlConfig.xml"></property>
	</bean>
    
    <!-- mapper扫描器 -->
    <!-- 会自动生成一个标识为mapper接口类型首字母小写的bean -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    	<property name="basePackage" value="com.byzx.ssm.dao"></property>
    	<property name="sqlSessionFactoryBeanName" value="ssf"></property>
    </bean>

db.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456

③ 编写POJO类(java bean)

public class Items {

	private int id;
	private String name;
	private double price;
	private String detail;
	private Date createtime;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String getDetail() {
		return detail;
	}
	public void setDetail(String detail) {
		this.detail = detail;
	}
	public Date getCreatetime() {
		return createtime;
	}
	public void setCreatetime(Date createtime) {
		this.createtime = createtime;
	}
	@Override
	public String toString() {
		return "Items [id=" + id + ", name=" + name + ", price=" + price
				+ ", detail=" + detail + ", createtime=" + createtime + "]";
	}
}

④ 编写ItemsMapper.xml

<mapper namespace="com.byzx.ssm.dao.ItemsMapper">
	<!-- 全查商品表 items -->
	<select id="findAllItem" resultType="Items">
		select * from items
	</select>
</mapper>

⑤ 编写ItemsMapper.java接口

public interface ItemsMapper {
	// 全查商品表
	public List<Items> findAllItem();
}

⑥ 测试dao层

public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
		ItemsMapper itemsMapper = (ItemsMapper)ac.getBean("itemsMapper");
		List<Items> items = itemsMapper.findAllItem();
		for(Items item: items){
			System.out.println(item);
		}
	}

执行结果:
在这里插入图片描述

出现上述结果,说明整个dao层已经写好,接下来到service层

3. 整合service层(使用注解)

ItemsService类:

@Service // 相当于配置了一个标识符为ItemsService类型首字母小写的bean
public class ItemsService {
	// mapper扫描器会自动生成一个标识符为itemsMapper的bean
	// 注解@Autowired 可以将生成的bean赋值给全局变量itemsMapper
	@Autowired
	private ItemsMapper itemsMapper;
	
	// 全查items表
	public List<Items> findAllItem(){
		return itemsMapper.findAllItem();
	}
}

4. 整合spring mvc

① 编写Controller

@Controller
public class ItemsController{
	@Autowired
	private ItemsService itemsService;
	
	@RequestMapping("/queryItems1.action")
	public ModelAndView queryItems1(){ // 方法名可以任意
		List<Items> items = itemsService.findAllItem();
		
		ModelAndView mav = new ModelAndView();
		// 添加数据
		mav.addObject("ITEMS", items);
		// 设置jsp页面路径
		mav.setViewName("jsp/showitems.jsp");
		return mav;
	}
}

② 编写springmvc.xml

<!-- 自动扫描bean -->
	<context:component-scan base-package="com.byzx.ssm.controller"></context:component-scan>
	
	<!-- 注解驱动 -->
	<mvc:annotation-driven></mvc:annotation-driven> 
	
	<!-- 配置视图解析器 ViewResolver -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>

③ 写jsp页面(jsp/showitems.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java./jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java./jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html >
<html>
<head>
<meta charset="UTF-8">
<title>查询商品列表</title>
</head>
<body>
	<form action="${pageContext.request.contextPath }/queryItems1.action"
		method="post">
		查询条件:
		<table width="100%" border=1>
			<tr>
				<td><input type="submit" value="查询" /></td>
			</tr>
		</table>

		商品列表:
		<table width="100%" border=1>
			<tr>
				<td>商品名称</td>
				<td>商品价格</td>
				<td>生产日期</td>
				<td>商品描述</td>
				<td>操作</td>
			</tr>
			<c:forEach items="${ITEMS }" var="item">
				<tr>
					<td>${item.name }</td>
					<td>${item.price }</td>
					<td><fmt:formatDate value="${item.createtime}"
							pattern="yyyy-MM-dd HH:mm:ss" /></td>
					<td>${item.detail }</td>
					<td><a
					   href="${pageContext.request.contextPath }/item/editItem.action?id=${item.id}">修改</a></td>
				</tr>
			</c:forEach>
		</table>
	</form>
</body>
</html>

④ 写web.xml

<!-- 配置前端控制器 DispatcherServlet -->
	<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>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>
	
	<!-- 加载spring容器 -->
	<context-param>
	    <param-name>contextConfigLocation</param-name>
	    <param-value>classpath:spring.xml</param-value>
	</context-param>
    <listener>        
	   	<listener-class>
	    	org.springframework.web.context.ContextLoaderListener
	    </listener-class>
    </listener> 

整个配置完成,进行最终的测试:
运行项目,在showitems.jsp页面点击查询显示数据库表中的所有商品信息
http://localhost:8080/ssm/jsp/showitems.jsp
在这里插入图片描述

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多