SSM框架整合思路
-
Spring在整合中起到的作用(面試時常問到)
Spring管理持久層的mapper。
Spring管理業務層的service,service可以調用mapper接口。Spring進行事物控制。
Spring管理表現層的Handler,handler可以調用service接口。
mapper,service,handler都是javabean。
-
Spring的核心(面試時常問到)
Ioc:依賴注入、控制反轉。意思是在一個類中不用new關鍵字來聲明對象,而是在xml文件中配置相應的節點即可,這樣使整個程序變得靈活多樣。
aop:面對切面編程。Spring中AOP代理由Spring的IOC容器負責生成、管理,其依賴關系也由IOC容器負責管理。
-
工程結構
-
管理mybatis的 xml 文件(單獨使用mybatis時需要配置許多,如數據庫連接等,現與Spring進行整合,這些東西配置在了管理Spring的xml文件中)
SqlMapConfig.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="cn.itcast.ssm.po"/> </typeAliases> <!-- <mappers> <package name="cn.study.ssm.mapper" /> </mappers> --> </configuration>
-
Spring配置文件
log4j.properties(日志文件,直接復制即可,開發模式使用DEBUG)
# Global logging configuration # log4j.rootLogger=DEBUG, stdout # 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
數據庫連接文件
db.properties(賬號密碼是我的數據庫的,修改即可)
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/device?characterEncoding=utf-8 jdbc.username=root jdbc.password=root
applicationContext-dao.xml(Spring管理持久層的mapper)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 加載配置文件 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 數據庫連接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="maxActive" value="10"/> <property name="maxIdle" value="5"/> </bean> <!-- SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 數據源 --> <property name="dataSource" ref="dataSource" /> <!--配置mybatis文件 --> <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" /> </bean> <!-- mapper掃描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 掃描包路徑,如果掃描多個包,中間用半角逗號隔開 --> <property name="basePackage" value="cn.itcast.ssm.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> </beans>
applicationContext-service.xml(Spring管理業務層的service)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 留言管理的service --> <bean id="liuyanService" class="cn.itcast.ssm.service.impl.LiuyanServiceImpl" /> </beans>
applicationContext-transaction.xml(Spring進行事物控制)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 事務控制器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 數據源 --> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 傳播行為 --> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> <tx:method name="select*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!-- aop:面向切面編程 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.itcast.ssm.service.impl.*.*(..))"/> </aop:config> </beans>
springmvc.xml(Spring管理表現層的Handler)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <context:component-scan base-package="cn.itcast.ssm.controller" > </context:component-scan> <mvc:annotation-driven></mvc:annotation-driven> <!-- 視圖解析器 解析jsp解析,默認使用jstl標簽,classpath下的得有jstl的包--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
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" 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>Device_web1.1</display-name> <!-- 加載spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <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:spring/springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <filter> <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
-
代碼實現流程
LiuyanMapper.xml-->LiuyanMapper.java-->LiuyanService.java-->LiuyanServiceImpl.java-->LiuyanController.java-->jsp
LiuyanMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace命名空間,作用是對sql分類隔離 --> <mapper namespace="cn.itcast.ssm.mapper.LiuyanMapper"> <select id="findLiuyanList" parameterType="cn.itcast.ssm.po.LiuyanQueryVo" resultType="cn.itcast.ssm.po.LiuyanCustom"> SELECT * FROM liuyan ORDER BY TIMER DESC </select> <select id="findLiuyanByname" parameterType="java.lang.String" resultType="cn.itcast.ssm.po.LiuyanCustom"> SELECT * FROM liuyan WHERE liuyan LIKE '%${value}%' </select> <insert id="insertLiuyan" parameterType="cn.itcast.ssm.po.Liuyan"> insert into liuyan(liuyan) value(#{liuyan}) </insert> <update id="updateLiuyan" parameterType="cn.itcast.ssm.po.Liuyan"> UPDATE liuyan SET liuyan=#{liuyan} WHERE id=#{id} </update> <select id="findLiuyanBynameOne" parameterType="java.lang.String" resultType="cn.itcast.ssm.po.LiuyanCustom"> SELECT * FROM liuyan WHERE liuyan=#{liuyan} </select> <delete id="deleteLiuyanBynameOne" parameterType="java.lang.String"> DELETE FROM liuyan WHERE liuyan=#{liuyan} </delete> </mapper>
LiuyanMapper.java
package cn.itcast.ssm.mapper; import java.util.List; import cn.itcast.ssm.po.Liuyan; import cn.itcast.ssm.po.LiuyanCustom; import cn.itcast.ssm.po.LiuyanQueryVo; public interface LiuyanMapper { public List<LiuyanCustom> findLiuyanList(LiuyanQueryVo liuyanQueryVo) throws Exception; public List<LiuyanCustom> findLiuyanByname(String liuyan) throws Exception; public Liuyan findLiuyanBynameOne(String liuyan) throws Exception; public void insertLiuyan(Liuyan liuyan) throws Exception; int updateLiuyan(Liuyan liuyan) throws Exception; public void deleteLiuyanBynameOne(String liuyan) throws Exception; }
LiuyanService.java
package cn.itcast.ssm.service; import java.util.List; import cn.itcast.ssm.po.Liuyan; import cn.itcast.ssm.po.LiuyanCustom; import cn.itcast.ssm.po.LiuyanQueryVo; public interface LiuyanService { public List<LiuyanCustom> findLiuyanList(LiuyanQueryVo liuyanQueryVo) throws Exception; public List<LiuyanCustom> findLiuyanByname(String liuyan) throws Exception; public Liuyan findLiuyanBynameOne(String liuyan) throws Exception; public void insertLiuyan(Liuyan liuyan) throws Exception; int updateLiuyan(Integer id,Liuyan liuyan) throws Exception; public void deleteLiuyanBynameOne(String liuyan) throws Exception; }
LiuyanServiceImpl.java
package cn.itcast.ssm.service.impl; import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import cn.itcast.ssm.mapper.LiuyanMapper; import cn.itcast.ssm.po.Liuyan; import cn.itcast.ssm.po.LiuyanCustom; import cn.itcast.ssm.po.LiuyanQueryVo; import cn.itcast.ssm.service.LiuyanService; public class LiuyanServiceImpl implements LiuyanService{ @Autowired private LiuyanMapper liuyanMapper; @Override public List<LiuyanCustom> findLiuyanList(LiuyanQueryVo liuyanQueryVo) throws Exception { // TODO 自動生成的方法存根 return liuyanMapper.findLiuyanList(liuyanQueryVo); } @Override public List<LiuyanCustom> findLiuyanByname(String liuyan) throws Exception { // TODO 自動生成的方法存根 List<LiuyanCustom> liuyanCustom = liuyanMapper.findLiuyanByname(liuyan); return liuyanCustom; } @Override public void insertLiuyan(Liuyan liuyan) throws Exception { // TODO 自動生成的方法存根 liuyanMapper.insertLiuyan(liuyan); return ; } @Override public int updateLiuyan(Integer id,Liuyan liuyan) throws Exception { return liuyanMapper.updateLiuyan(liuyan); } @Override public Liuyan findLiuyanBynameOne(String liuyan) throws Exception { // TODO 自動生成的方法存根 liuyanMapper.findLiuyanBynameOne(liuyan); return liuyanMapper.findLiuyanBynameOne(liuyan); } @Override public void deleteLiuyanBynameOne(String liuyan) throws Exception { // TODO 自動生成的方法存根 liuyanMapper.deleteLiuyanBynameOne(liuyan); } }
LiuyanController.java
package cn.itcast.ssm.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import cn.itcast.ssm.po.Liuyan; import cn.itcast.ssm.po.LiuyanCustom; import cn.itcast.ssm.service.LiuyanService; @Controller @RequestMapping("/liuyan") public class LiuyanController { @Autowired private LiuyanService liuyanService; @RequestMapping("/queryLiuyan") public ModelAndView queryLiuyan()throws Exception { //調用service查找 數據庫,查詢商品列表,這里使用靜態數據模擬 List<LiuyanCustom> liuyanList = liuyanService.findLiuyanList(null); //返回ModelAndView ModelAndView modelAndView = new ModelAndView(); //相當 於request的setAttribut,在jsp頁面中通過itemsList取數據 modelAndView.addObject("liuyanList",liuyanList); //modelAndView.addObject("liuyanList", liuyanList); //不可以有空格 modelAndView.setViewName("liuyan/liuyanList"); return modelAndView; } @RequestMapping("/queryLiuyanByname") public ModelAndView queryLiuyanByname()throws Exception { //調用service查找 數據庫,查詢商品列表,這里使用靜態數據模擬 List<LiuyanCustom> liuyanCustom = liuyanService.findLiuyanByname("任秀興"); //返回ModelAndView ModelAndView modelAndView = new ModelAndView(); //相當 於request的setAttribut,在jsp頁面中通過itemsList取數據 modelAndView.addObject("liuyanList",liuyanCustom); //modelAndView.addObject("liuyanList", liuyanList); //不可以有空格 modelAndView.setViewName("liuyan/liuyanList"); return modelAndView; } @RequestMapping("/insertLiuyan") public String insertLiuyan(HttpServletRequest request)throws Exception { //調用service查找 數據庫 String strliuyan = request.getParameter("liuyan"); //String strliuyan1 = request.getParameter("liuyan1"); System.out.println(request.getParameter("liuyan")); //System.out.println(request.getParameter("liuyan1")); Liuyan liuyan = new Liuyan(); liuyan.setLiuyan(strliuyan); liuyanService.insertLiuyan(liuyan); //重定向 return "redirect:queryLiuyan.action"; } @RequestMapping("/updateLiuyan") public ModelAndView updateLiuyan(String liuyan)throws Exception { Liuyan speak = liuyanService.findLiuyanBynameOne(liuyan); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("speak",speak); modelAndView.setViewName("liuyan/updateliuyan"); return modelAndView; } @RequestMapping("/updateLiuyanSubmit") public String updateLiuyanSubmit(HttpServletRequest request,Liuyan liuyan)throws Exception { String strid = request.getParameter("id"); System.out.println(strid); int id = Integer.parseInt(strid); liuyan.setId(id); liuyanService.updateLiuyan(id,liuyan); //重定向 return "redirect:queryLiuyan.action"; } @RequestMapping("/deleteLiuyan") public String deleteLiuyan(HttpServletRequest request)throws Exception { String strliuyan = request.getParameter("liuyan"); liuyanService.deleteLiuyanBynameOne(strliuyan); return "redirect:queryLiuyan.action"; } }
jsp
liuyanList.jsp
<%@page import =" java.text.SimpleDateFormat" %> <%@page import =" java.util.Date" %> <%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>留言板</title> </head> <body> <form action="${pageContext.request.contextPath }/liuyan/insertLiuyan.action" method="post"> 留言: <table width="100%" border=1> <tr> <td> <input type="text" name="liuyan" id="liuyan" /> <!-- <input type="text" name="liuyan1" id="liuyan1" /> --> <input type="submit" value="提交"/></td> </tr> </table> 列表: <table width="100%" border=1> <tr> <td>時間</td> <td>留言</td> <td>修改</td> <td>刪除</td> </tr> <c:forEach items="${liuyanList }" var="speak"> <tr> <% SimpleDateFormat format=new SimpleDateFormat("yyyy年MM月dd日HH時mm分ss秒"); String time=format.format(new Date()); %> <td><fmt:formatDate value="${speak.timer }" pattern="yyyy-MM-dd HH:mm:ss"/></td> <td>${speak.liuyan }</td> <td><a href="${pageContext.request.contextPath }/liuyan/updateLiuyan.action?liuyan=${speak.liuyan}" >修改</a></td> <td><a href="${pageContext.request.contextPath }/liuyan/deleteLiuyan.action?liuyan=${speak.liuyan}" >刪除</a></td> </tr> </c:forEach> </table> </form> </body> </html>