天天看點

SSM架構整合之練習篇

版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協定,轉載請附上原文出處連結和本聲明。

本文連結:https://blog.csdn.net/zhao1299002788/article/details/102536616

SSM的練習 :
		1開發環境
		資料庫:mysql5.5以上版本。
		Jdk:1.7
		開發環境:Eclipse mars2
		Spring:4.2.4
		Mybatis:3.2.7
		Tomcat:7
		2資料庫
		資料庫使用mysql 資料庫。

		1、建立crm資料庫
		2、将參考資料中的sql腳本導入到資料庫中

		3工程搭建
		工程使用Springmvc、spring、mybatis架構整合完成。

		Dao層:SqlMapConfig.xml(空)
				applicationContext-dao.xml:資料庫連接配接池、SqlSessionFactory、Mapper的掃描器。
		Service層:
			配置包掃描器,掃描所有帶@Service注解的類。事務管理器、切面。
		表現層:
				Springmvc.xml:包掃描器@Controller、配置注解驅動、視圖解析器。
				Jsp:bootstrap
		Web.xml:配置spring監聽器,前端控制器。
		3.1SqlMapConfig.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>

		</configuration>
		3.2applicationContext-dao.xml
		<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"
			xmlns:task="http://www.springframework.org/schema/task" 
			xsi:schemaLocation="http://www.springframework.org/schema/beans 
				http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
				http://www.springframework.org/schema/mvc 
				http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 
				http://www.springframework.org/schema/context 
				http://www.springframework.org/schema/context/spring-context-4.2.xsd 
				http://www.springframework.org/schema/aop 
				http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
				http://www.springframework.org/schema/tx 
				http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
				http://www.springframework.org/schema/task
				http://www.springframework.org/schema/task/spring-task-4.2.xsd">

			<!-- 配置 讀取properties檔案 jdbc.properties -->
			<context:property-placeholder location="classpath:jdbc.properties" />

			<!-- 配置 資料源 -->
			<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
				<!-- 驅動 -->
				<property name="driverClassName" value="${jdbc.driver}" />
				<!-- url -->
				<property name="url" value="${jdbc.url}" />
				<!-- 使用者名 -->
				<property name="username" value="${jdbc.username}" />
				<!-- 密碼 -->
				<property name="password" value="${jdbc.password}" />
			</bean>

			<!-- 配置 Mybatis的工廠 -->
			<bean class="org.mybatis.spring.SqlSessionFactoryBean">
				<!-- 資料源 -->
				<property name="dataSource" ref="dataSource" />
				<!-- 配置Mybatis的核心 配置檔案所在位置 -->
				<property name="configLocation" value="classpath:SqlMapConfig.xml" />
				<!-- 配置pojo别名 -->
				<property name="typeAliasesPackage" value="cn.baidu.core.bean"></property>
			</bean>

			<!-- 配置 1:原始Dao開發 接口實作類 Mapper.xml 三個 2:接口開發 接口 不寫實作類 Mapper.xml 二個 (UserDao、ProductDao 
				、BrandDao。。。。。。。) 3:接口開發、并支援掃描 cn.baidu.core.dao(UserDao。。。。。) 寫在此包下即可被掃描到 -->
			<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
				<property name="basePackage" value="cn.baidu.core.dao" />
			</bean>

		</beans>

		Jdbc.properties
		jdbc.driver=com.mysql.jdbc.Driver
		jdbc.url=jdbc:mysql://localhost:3306/crm?characterEncoding=utf-8
		jdbc.username=root
		jdbc.password=root
		3.3applicationContext-service.xml
		<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"
			xmlns:task="http://www.springframework.org/schema/task"
			xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
			xsi:schemaLocation="http://www.springframework.org/schema/beans 
				http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
				http://www.springframework.org/schema/mvc 
				http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 
				http://www.springframework.org/schema/context 
				http://www.springframework.org/schema/context/spring-context-4.2.xsd 
				http://www.springframework.org/schema/aop 
				http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
				http://www.springframework.org/schema/tx 
				http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
				http://www.springframework.org/schema/task
				http://www.springframework.org/schema/task/spring-task-4.2.xsd
				http://code.alibabatech.com/schema/dubbo        
				http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
				
				
				<!-- 配置  掃描   @Service -->
				<context:component-scan base-package="cn.baidu.core.service"/>
				
				
				
		</beans>

		3.4applicationContext-trans.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:p="http://www.springframework.org/schema/p"
			xmlns:aop="http://www.springframework.org/schema/aop" 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.2.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
			http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
			<!-- 事務管理器 -->
			<bean id="transactionManager"
				class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
				<!-- 資料源 -->
				<property name="dataSource" ref="dataSource" />
			</bean>
			<!-- 通知 -->
			<tx:advice id="txAdvice" transaction-manager="transactionManager">
				<tx:attributes>
					<!-- 傳播行為 -->
					<tx:method name="save*" propagation="REQUIRED" />
					<tx:method name="insert*" propagation="REQUIRED" />
					<tx:method name="add*" propagation="REQUIRED" />
					<tx:method name="create*" propagation="REQUIRED" />
					<tx:method name="delete*" propagation="REQUIRED" />
					<tx:method name="update*" propagation="REQUIRED" />
					<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
					<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
					<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
				</tx:attributes>
			</tx:advice>
			<!-- 切面 -->
			<aop:config>
				<aop:advisor advice-ref="txAdvice"
					pointcut="execution(* cn.baidu.core.service.*.*(..))" />
			</aop:config>
		</beans>
		3.5Springmvc.xml
		<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"
			xmlns:task="http://www.springframework.org/schema/task"
			xsi:schemaLocation="http://www.springframework.org/schema/beans 
				http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
				http://www.springframework.org/schema/mvc 
				http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 
				http://www.springframework.org/schema/context 
				http://www.springframework.org/schema/context/spring-context-4.2.xsd 
				http://www.springframework.org/schema/aop 
				http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
				http://www.springframework.org/schema/tx 
				http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
				http://www.springframework.org/schema/task
				http://www.springframework.org/schema/task/spring-task-4.2.xsd">		
				<!-- 加載屬性檔案 -->
				<context:property-placeholder location="classpath:resource.properties"/>
				<!-- 配置掃描 器 -->
				<context:component-scan base-package="cn.baidu.core.web.controller"/>
				<!-- 配置處理器映射器  擴充卡 -->
				<mvc:annotation-driven/>
				
				<!-- 配置視圖解釋器 jsp -->
				<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
					<property name="prefix" value="/WEB-INF/jsp/"/>
					<property name="suffix" value=".jsp"/>
				</bean>
				
		</beans>

		3.6Web.xml
		<?xml version="1.0" encoding="UTF-8"?>
		<web-app version="2.5" 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/javaee 
			http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
			<welcome-file-list>
				<welcome-file>customer.action</welcome-file>
			</welcome-file-list>
			<!-- 上下文的位置 -->
			<context-param>
				<param-name>contextConfigLocation</param-name>
				<param-value>classpath:applicationContext-*.xml</param-value>
			</context-param>
			<!-- Spring的監聽器 -->
			<listener>
				<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
			</listener>


			<!-- POST送出過濾器 UTF-8 -->
			<filter>
				<filter-name>encoding</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>encoding</filter-name>
				<url-pattern>*.action</url-pattern>
			</filter-mapping>
			<!-- 前端控制器 -->
			<servlet>
				<servlet-name>crm</servlet-name>
				<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
				<init-param>
					<param-name>contextConfigLocation</param-name>
					<!-- 此處不配置 預設找 /WEB-INF/[servlet-name]-servlet.xml -->
					<param-value>classpath:springmvc.xml</param-value>
				</init-param>
				<load-on-startup>1</load-on-startup>
			</servlet>
			<servlet-mapping>
				<servlet-name>crm</servlet-name>
				<!-- 1:*.do *.action 攔截以.do結尾的請求 (不攔截 jsp png jpg .js .css) 2:/ 攔截所有請求 
					(不攔截.jsp) 建議使用此種 方式 (攔截 .js.css .png) (放行靜态資源) 3:/* 攔截所有請求(包括.jsp) 此種方式 不建議使用 -->
				<url-pattern>*.action</url-pattern>
			</servlet-mapping>
		</web-app>


		3.7加入jsp及分頁标簽

		Tld檔案需要放到WEB-INF目錄下, tomcat的規定。當tomcat啟動時會自動加載。

		Jsp中使用标簽:



		4查詢條件初始化
		4.1需求

		初始化查詢條件下拉清單。

		4.2Sql
		SELECT * from base_dict WHERE dict_type_code='006'
		4.3Dao
		<?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">
		<mapper namespace="com.baidu.crm.dao.BaseDictDao">
			<select id="getBaseDictList" parameterType="string" resultType="BaseDict">
				SELECT * from base_dict WHERE dict_type_code=#{typeCode}
			</select>
		</mapper>

		4.4Service
		@Service
		public class BaseDictServiceImpl implements BaseDictService {

			@Autowired
			private BaseDictDao baseDictDao;
			
			@Override
			public List<BaseDict> getBaseDictList(String typeCode) {
				List<BaseDict> list = baseDictDao.getBaseDictList(typeCode);
				return list;
			}

		}

		4.5Controller












		規則:子容器可以通路父容器的對象,父容器不能通路子容器的對象。
		public class CustomerController {
			
			@Autowired
			private BaseDictService baseDictService;
			@Value("${customer.source.code}")
			private String CustomerSourceCode;
			@Value("${customer.industry.code}")
			private String CustomerIndustryCode;
			@Value("${customer.level.code}")
			private String CustomerLevelCode;

			@RequestMapping("/list")
			public String showCustomerList(Model model) {
				//查詢字典表初始化下拉清單
				List<BaseDict> custSourceList = baseDictService.getBaseDictList(CustomerSourceCode);
				List<BaseDict> custIndustryList = baseDictService.getBaseDictList(CustomerIndustryCode);
				List<BaseDict> custLevelList = baseDictService.getBaseDictList(CustomerLevelCode);
				//把清單傳遞給jsp頁面
				model.addAttribute("fromType", custSourceList);
				model.addAttribute("industryType", custIndustryList);
				model.addAttribute("levelType", custLevelList);
				
				return "customer";
			}
		}

		5客戶清單展示
		5.1需求

		展示商品清單,并且可以根據查詢條件過濾查詢結果,并且實作分頁處理。

		5.2Sql
		SELECT
			a.cust_id,
			a.cust_name,
			a.cust_user_id,
			a.cust_create_id,
			b.dict_item_name cust_source,
			c.dict_item_name cust_industry,
			d.dict_item_name cust_level,
			a.cust_linkman,
			a.cust_phone,
			a.cust_mobile,
			a.cust_zipcode,
			a.cust_address,
			a.cust_createtime
		FROM
			customer a
		LEFT JOIN base_dict b ON a.cust_source = b.dict_id
		LEFT JOIN base_dict c ON a.cust_industry = c.dict_id
		LEFT JOIN base_dict d ON a.cust_level = d.dict_id
		WHERE
			cust_name LIKE '%馬%'
		AND cust_source = 6
		AND cust_industry = 2
		AND cust_level = 22

		5.3Dao
		<select id="getCustList" parameterType="QueryVo" resultType="customer">
				SELECT
					a.cust_id,
					a.cust_name,
					a.cust_user_id,
					a.cust_create_id,
					b.dict_item_name cust_source,
					c.dict_item_name cust_industry,
					d.dict_item_name cust_level,
					a.cust_linkman,
					a.cust_phone,
					a.cust_mobile,
					a.cust_zipcode,
					a.cust_address,
					a.cust_createtime
				FROM
					customer a
				LEFT JOIN base_dict b ON a.cust_source = b.dict_id
				LEFT JOIN base_dict c ON a.cust_industry = c.dict_id
				LEFT JOIN base_dict d ON a.cust_level = d.dict_id
				<where>
					<if test="custName!=null and custName!=''">
						AND	cust_name LIKE '%${custName}%'
					</if>
					<if test="custSource!=null and custSource!=''">
						AND cust_source = #{custSource}
					</if>
					<if test="custIndustry!=null and custIndustry!=''">
						AND cust_industry = #{custIndustry}
					</if>
					<if test="custLevel!=null and custLevel!=''">
						AND cust_level = #{custLevel}
					</if>
				</where>
				LIMIT #{start},#{rows}
			</select>

		增加count後的dao
		<mapper namespace="com.baidu.crm.dao.CustomerDao">
			
			<sql id="cust_query_where">
				<where>
					<if test="custName!=null and custName!=''">
						AND	cust_name LIKE '%${custName}%'
					</if>
					<if test="custSource!=null and custSource!=''">
						AND cust_source = #{custSource}
					</if>
					<if test="custIndustry!=null and custIndustry!=''">
						AND cust_industry = #{custIndustry}
					</if>
					<if test="custLevel!=null and custLevel!=''">
						AND cust_level = #{custLevel}
					</if>
				</where>
			</sql>
			
			<select id="getCustList" parameterType="QueryVo" resultType="customer">
				SELECT
					a.cust_id,
					a.cust_name,
					a.cust_user_id,
					a.cust_create_id,
					b.dict_item_name cust_source,
					c.dict_item_name cust_industry,
					d.dict_item_name cust_level,
					a.cust_linkman,
					a.cust_phone,
					a.cust_mobile,
					a.cust_zipcode,
					a.cust_address,
					a.cust_createtime
				FROM
					customer a
				LEFT JOIN base_dict b ON a.cust_source = b.dict_id
				LEFT JOIN base_dict c ON a.cust_industry = c.dict_id
				LEFT JOIN base_dict d ON a.cust_level = d.dict_id
				<include refid="cust_query_where"/>
				LIMIT #{start},#{rows}
			</select>
			<select id="getCustListCount" parameterType="QueryVo" resultType="int">
				SELECT count(*)
				FROM
					customer a
				LEFT JOIN base_dict b ON a.cust_source = b.dict_id
				LEFT JOIN base_dict c ON a.cust_industry = c.dict_id
				LEFT JOIN base_dict d ON a.cust_level = d.dict_id
				<include refid="cust_query_where"/>
			</select>
		</mapper>

		5.4Service
		根據查詢條件查詢資料庫得到客戶清單。分頁條件。
		接收查詢條件QueryVo接收,使用page接收頁碼。
		1、通過page計算start。
		2、調用dao查詢客戶清單。
		3、做count處理。計算出此查詢條件中共查詢到多少條記錄。

		傳回結果:Page對象。
		條件:QueryVo
		@Service
		public class CustomerServiceImpl implements CustomerService {

			@Autowired
			private CustomerDao customerDao;
			
			@Override
			public Page<Customer> getCustList(QueryVo queryVo) {
		queryVo.setStart((queryVo.getPage() - 1) * queryVo.getRows());
				List<Customer> custList = customerDao.getCustList(queryVo);
				Page<Customer> page = new Page<Customer>();
				//設定客戶清單
				page.setRows(custList);
				page.setPage(queryVo.getPage());
				page.setSize(queryVo.getRows());
				//計算查詢總記錄數
				int total = customerDao.getCustListCount(queryVo);
				page.setTotal(total);
				return page;
			}

		}

		5.5Controller
		5.5.1分析
		1、接收頁面送出的查詢參數:
		保證jsp頁面送出的表單中的input 的name屬性和QueryVo中的屬性一緻
		2、調用Service查詢客戶清單
		3、把客戶清單傳遞給頁面。


		@RequestMapping("/list")
			public String showCustomerList(Model model, QueryVo queryVo) throws Exception {
				
				String custName = queryVo.getCustName();
				if (custName != null && !"".equals(custName)) {
					custName = new String(custName.getBytes("iso8859-1"), "utf-8");
					queryVo.setCustName(custName);
				}
				//查詢字典表初始化下拉清單
				List<BaseDict> custSourceList = baseDictService.getBaseDictList(CustomerSourceCode);
				List<BaseDict> custIndustryList = baseDictService.getBaseDictList(CustomerIndustryCode);
				List<BaseDict> custLevelList = baseDictService.getBaseDictList(CustomerLevelCode);
				//查詢客戶清單
				Page<Customer> page = customerService.getCustList(queryVo);
				//把page放到request中
				model.addAttribute("page", page);
				
				//把清單傳遞給jsp頁面
				model.addAttribute("fromType", custSourceList);
				model.addAttribute("industryType", custIndustryList);
				model.addAttribute("levelType", custLevelList);
				
				//頁面回顯
				model.addAttribute("custName", queryVo.getCustName());
				model.addAttribute("custSource", queryVo.getCustSource());
				model.addAttribute("custIndustry", queryVo.getCustIndustry());
				model.addAttribute("custLevel", queryVo.getCustLevel());
				
				
				return "customer";
			}


		6修改客戶資訊
		6.1需求

		1、點選客戶清單中的“修改”按鈕彈出客戶資訊修改對話框,并初始化客戶資訊
		2、點選“儲存修改”按鈕将修改後的結果儲存到資料庫中

		6.2展示客戶資訊

		6.2.1分析
		請求的url:
		customer/edit.action
		參數:cust_id客戶id
		傳回值:響應json資料,直接由Customer轉換而來。需要使用@ResponseBody注解。

		6.2.2Dao層
		根據客戶id查詢客戶資訊。
		<select id="getCustomerById" parameterType="long" resultType="customer">
				select * from customer where cust_id = #{custId}
			</select>

		6.2.3Service層
			@Override
			public Customer getCustomerById(long custId) {
				Customer customer = customerDao.getCustomerById(custId);
				return customer;
			}

		6.2.4Controller
		要求傳回json資料
		請求的url:
		customer/edit.action
		參數:cust_id客戶id
		傳回值:響應json資料
		@RequestMapping("/edit")
			@ResponseBody
			public Customer getCustomerById(Long id) {
				Customer customer = customerService.getCustomerById(id);
				return customer;
			}


		6.3送出修改
		6.3.1分析
		請求的url:customer/update.action
		請求的方法:post
		參數:表單中的資料。
		傳回結果:OK

		6.3.2Dao層
		<update id="updateCustomerById" parameterType="customer">
				UPDATE customer
				<set>
					<if test="cust_name!=null">
					cust_name=#{cust_name},
					</if>
					<if test="cust_user_id!=null">
					cust_user_id=#{cust_user_id},
					</if>
					<if test="cust_create_id!=null">
					cust_create_id=#{cust_create_id},
					</if>
					<if test="cust_source!=null">
					cust_source=#{cust_source},
					</if>
					<if test="cust_industry!=null">
					cust_industry=#{cust_industry},
					</if>
					<if test="cust_level!=null">
					cust_level=#{cust_level},
					</if>
					<if test="cust_linkman!=null">
					cust_linkman=#{cust_linkman},
					</if>
					<if test="cust_phone!=null">
					cust_phone=#{cust_phone},
					</if>
					<if test="cust_mobile!=null">
					cust_mobile=#{cust_mobile},
					</if>
					<if test="cust_zipcode!=null">
					cust_zipcode=#{cust_zipcode},
					</if>
					<if test="cust_address!=null">
					cust_address=#{cust_address},
					</if>
					<if test="cust_createtime!=null">
					cust_createtime=#{cust_createtime},
					</if>
				</set>
				WHERE
					cust_id = #{cust_id}
			</update>
		6.3.3Service層
		@Override
			public void updateCustomerById(Customer customer) {
				customerDao.updateCustomerById(customer);
			}

		6.3.4Controller
		接收參數:Customer接收。
		響應結果:OK字元串。使用@ResponseBody
		請求的url:customer/update.action
		@RequestMapping(value="/update", method=RequestMethod.POST)
			@ResponseBody
			public String updateCustomer(Customer customer) {
				customerService.updateCustomerById(customer);
				//直接向浏覽器響應字元串需要使用@ResponseBody
				return "OK";
				
			}

		7删除客戶
		7.1需求

		點選客戶清單中的删除按鈕,提示“警告資訊”

		點選确定後删除使用者資訊,并重新整理頁面。

		分析:
		請求的url:customer/delete.action

		參數:id(客戶id)
		響應的内容:OK(字元串需要使用@ResponseBody)           

複制