1. 程式人生 > >SSM框架整合完整案例

SSM框架整合完整案例

這篇文章用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/mybatis27?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.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/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>