JavaWeb学习之路——SSM框架之Spring(五)
前情提要請(qǐng)看JavaWeb學(xué)習(xí)之路——SSM框架之Spring(四)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 整合Spring和Mybatis框架
1.在項(xiàng)目的lib下導(dǎo)入如下jar包
導(dǎo)入mybatis所有jar和spring的jar基本包,spring-jdbc,spring-tx,spring-aop,spring整合mybatis等
2.編寫spring配置文件applicationContext
在jar包下找到對(duì)應(yīng)的類文件,復(fù)制它的類名,將之加入到對(duì)應(yīng)的bean的Class屬性中,下圖為一個(gè)示例:
?
Spring xml文件配置數(shù)據(jù)庫相關(guān)信息:
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><!-- id表示獲取到對(duì)象標(biāo)識(shí)class 創(chuàng)建哪個(gè)類的對(duì)象--><!-- 數(shù)據(jù)源封裝類,相當(dāng)于mybatis的environment標(biāo)簽,數(shù)據(jù)類在spring-jdbc包中 --><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/likui"/><property name="username" value="root"/><property name="password" value="123456"/></bean><!-- 在mybatis-spring包中 --><bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"></property></bean><!-- 掃描器,相當(dāng)于mybatis下的mappers package標(biāo)簽 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.likui.mapper"></property><!-- 讓factory與數(shù)據(jù)庫相關(guān)聯(lián) --><property name="sqlSessionFactory" ref="factory"></property></bean></beans>對(duì)應(yīng)類:MapperScannerConfigurer->SqlSessionFactoryBean->DriverManagerDataSource,層層嵌套
?
3.使用流程
src下代碼結(jié)構(gòu)圖:
1)在src下創(chuàng)建mapper包,里面是sql語句的使用方法
public interface FlowerMapper {@Select("select * from flower")List<Flower> selAll();}?
2)在src下創(chuàng)建pojo包,里面是類的構(gòu)造方法和setter、getter方法,用來封裝對(duì)象
public class Flower {private int id;private String name;private double price;private String production;public void setList(List<Integer> list) {this.list = list;}public Flower(int id, String name, double price, String production) {this.id = id;this.name = name;this.price = price;this.production = production;}public Flower() {}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 getProduction() {return production;}public void setProduction(String production) {this.production = production;}?
3)創(chuàng)建service包,里面是工程項(xiàng)目的實(shí)現(xiàn)類,接口和它的實(shí)現(xiàn)類都放這里面
(1)接口
public interface FlowerService {List<Flower> show() throws IOException ;? //顯示}(2)實(shí)現(xiàn)類
public class FlowerServiceImpl implements FlowerService{private FlowerMapper flowermapper;public FlowerMapper getFlowermapper() {return flowermapper;}public void setFlowermapper(FlowerMapper flowermapper) {this.flowermapper = flowermapper;}@Overridepublic List<Flower> show() throws IOException {// TODO Auto-generated method stubreturn flowermapper.selAll();}?}?
4)在Spring的beans.xml中創(chuàng)建類的對(duì)象
注意對(duì)應(yīng)的首字母為大寫的類或接口在引用時(shí)需要將首字母小寫,接口不能創(chuàng)建bean,因?yàn)椴荒軐?shí)例化
<bean id="flowerService" class="com.likui.service.FlowerServiceImpl"><property name="flowermapper" ref="flowerMapper"></property></bean>?
5)編寫Test主函數(shù)來實(shí)現(xiàn),在java文件中利用Spring IoC獲取相應(yīng)類對(duì)象
public class Test {public static void main(String[] args) throws IOException {// TODO Auto-generated method stubApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");//獲取所有spring管理的bean的名稱//String []names=ac.getBeanDefinitionNames();//for(String string:names) {//???System.out.println(string);//}FlowerServiceImpl flowerServiceImpl=ac.getBean("flowerService",FlowerServiceImpl.class);List<Flower> list=flowerServiceImpl.show();System.out.println("id\t\tname\t\tprice\t\tproduction");for (Flower flower : list) {System.out.println(flower.getId()+"\t\t"+flower.getName()+"\t\t"+flower.getPrice()+"\t\t"+flower.getProduction());}}}6)實(shí)驗(yàn)結(jié)果展示:
?
4.發(fā)布到Web項(xiàng)目上
因?yàn)镾pring不能管理serverlet,需要用tomcat來管理它,利用tomcat提供的方法來支持Spring
1)在WEB-INF下新建web.xml配置文件。用于加載Spring的配置文件,獲取到相應(yīng)的contextConfigLocation
代碼如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"><!-- 上下文參數(shù) --><context-param><param-name>contextConfigLocation</param-name><!-- spring配置文件 --><param-value>classpath:beans.xml</param-value></context-param><!-- 封裝了一個(gè)監(jiān)聽器,幫助加載Spring的配置文件 --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener></web-app>2)在src下新建serverlet包,里面寫相應(yīng)的serverlet實(shí)現(xiàn)方法
利用init初始化方法來實(shí)例化service中接口實(shí)現(xiàn)類,代碼如下:
@WebServlet("/show")public class ShowServerlet extends HttpServlet{private FlowerService flowerservice;@Overridepublic void init() throws ServletException {// TODO Auto-generated method stub//對(duì)service實(shí)例化//ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");//Spring不能管理serverlet對(duì)象,需要用tomacat來管理它,會(huì)封裝它ApplicationContex?ac=WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());flowerservice=ac.getBean("flowerService",FlowerServiceImpl.class);}@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// TODO Auto-generated method stubreq.setAttribute("list", flowerservice.show());req.getRequestDispatcher("/index.jsp").forward(req, resp);}}3)在WebContent下新建index.jsp用于測試。
代碼如下所示:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body>hello world!<table><tr><th>編號(hào)</th><th>名字</th><th>價(jià)格</th><th>產(chǎn)處</th></tr><c:forEach items="${list }" var="peo"><tr><td>${peo.id }</td><td>${peo.name }</td><td>${peo.price }</td><td>${peo.production }</td></tr></c:forEach></table></body></html>4)實(shí)驗(yàn)結(jié)果:
?
?
?
?
總結(jié)
以上是生活随笔為你收集整理的JavaWeb学习之路——SSM框架之Spring(五)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaWeb学习之路——SSM框架之S
- 下一篇: JavaWeb学习之路——SSM框架之S