SSM框架搭建(Eclipse+非Maven版本)
阿新 • • 發佈:2018-11-02
時間:2018年5月26日
目的: 搭建一個簡單的ssm框架,提升自己對ssm框架的理解。 基本步驟: 1、建立web工程 2、匯入ssm相關jar包 3、利用mybatis的generator逆向工程,生成dao介面、xml檔案、實體類 4、配置xml相關檔案 5、編寫service層 6、測試service以及dao層 7、編寫controller開發工具說明: Eclipse Oxygen jdk 1.8 tomcat:8.0
1、建立web工程 以下是專案最終的目錄結構 建立動態web工程,建立兩個source folder 一個放主程式碼, 一個放各類資原始檔
3、利用mybatis的generator逆向工程,生成dao介面、xml檔案、實體類
4、配置xml相關檔案 配置屬性檔案,分離資料庫連線的資訊,便於維護---- jdbc.propert
jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost;databaseName=loraBase
jdbc.username=sa
jdbc.password=123
initialSize=0
maxActive=20
maxIdle=20
minIdle=1
maxWait=60000
配置資料庫連線、事務處理、整合Mybatis等: spring-mybatis.xml
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自動掃描 -->
<!-- 此處掃描 不用包含mvc控制層,在spring-mvc配置檔案,可以單獨對其進行配置掃描, 按需來配置要好一些,畢竟統一配置,專案大了可能會影響效能,思路更清晰,明白你具體都都做了些啥 -->
<context:component-scan base-package="com.ssm.domain" />
<context:component-scan base-package="com.ssm.dao" />
<context:component-scan base-package="com.ssm.service" />
<!-- 引入配置檔案 jdbc.properties-->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:properties/jdbc.properties" />
</bean>
<!-- 連線池配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 初始化連線大小 -->
<property name="initialSize" value="${initialSize}"></property>
<!-- 連線池最大數量 -->
<property name="maxActive" value="${maxActive}"></property>
<!-- 連線池最大空閒 -->
<property name="maxIdle" value="${maxIdle}"></property>
<!-- 連線池最小空閒 -->
<property name="minIdle" value="${minIdle}"></property>
<!-- 獲取連線最大等待時間 -->
<property name="maxWait" value="${maxWait}"></property>
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置對映檔案 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自動掃描mapping.xml檔案 -->
<property name="mapperLocations" value="classpath:com/ssm/dao/xml/*.xml"></property>
</bean>
<!-- DAO介面所在包名,Spring會自動查詢其下的類 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
配置spring mvc相關資訊,檢視解析器、開啟註解掃描等 ---- spring-mvc.xml
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自動掃描該包,使SpringMVC認為包下用了@controller註解的類是控制器 -->
<context:component-scan base-package="com.ssm.web" />
<!-- 會自動註冊RequestMappingHandlerMapping與RequestMappingHandlerAdapter兩個Bean, -->
<!-- 這是Spring MVC為@Controller分發請求所必需的, -->
<!-- 並且提供了資料繫結支援,@NumberFormatannotation支援,@DateTimeFormat支援, -->
<!-- @Valid支援讀寫XML的支援(JAXB)和讀寫JSON的支援(預設Jackson)等功能。 -->
<mvc:annotation-driven />
<!--避免IE執行AJAX時,返回JSON出現下載檔案 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 啟動SpringMVC的註解功能,完成請求和註解POJO的對映 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON轉換器 -->
</list>
</property>
</bean>
<!-- 檢視解析器 -->
<!-- 定義跳轉的檔案的前後綴 ,檢視模式配置 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 這裡的配置我的理解是自動給後面action的方法return的字串加上字首和字尾,變成一個 可用的url地址 -->
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<!--對靜態資原始檔的訪問 -->
<!-- 針對springMVC的restful風格的url而言,配置了 -->
<mvc:resources mapping="/images/**" location="/WEB-INF/images/" />
<mvc:resources mapping="/css/**" location="/WEB-INF/css/" />
<mvc:resources mapping="/js/**" location="/WEB-INF/js/" />
</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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>IOTDemo</display-name>
<!--定製預設首頁,一般可以設定為登陸或者index -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!--springMVC的核心分發器 -->
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定Spring的配置檔案 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- spring容器配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 注意,spring載入配置檔案 -->
<param-value>
classpath:spring/spring-mybatis.xml,
</param-value>
</context-param>
<!-- spring容器監聽器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- charactor encoding -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
擴充套件: 1、mvc核心配置資訊主要是控制層的檔案包掃描、檢視解析器、和<mvc:annotation-driven /> 2、當url採用restful風格時,可能會導致springMVC會攔截靜態資源,這時就需要配置一下,讓靜態資源可以訪問 3、<mvc:resources mapping="/images/**" location="/WEB-INF/images/" /> 當檔案為了提高安全性 放在WEB-INF下面時,就需要注意路徑的正確性 配置日誌檔案輸出,可以輸出再控制檯、文字檔案,配置豐富。 甚至可以配置資訊存入資料庫。----log4j.properties
log4j.rootLogger = info,stdout
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
5、
編寫service層
1、要在類名上標記註解@Service 2、一般可以考慮在Service層匯入日誌功能,輸出各類資訊。 3、依賴注入:@Resource或者@Autowired兩種方式,別人推薦都是@Autowired
擴充套件: 一般可以考慮dao層,方法名直接就是增刪改查selectXXX、addXXX、deleteXXX、updateXXX等。 service層可以考慮,從使用者的角度去對方法命名。比如:登陸--login(),比如註冊--register(),比如:執行秒殺:executeSecKill().....: 6、測試service以及dao層 1、一般編寫完Service層和Dao層以後,就可以進行測試,推薦使用Junt註解單元測試 2、 需要匯入spring-test的jar包,便於依賴注入(已經被託管,所以dao和service是無法new的) 3、建議使用快捷方式,按類自動生成所有方法的測試檔案。優雅而且方便 4、其他獲取springde 例項物件的方式可以參考如下:
簡單的在類檔案裡用ApplicationContext獲得Spring中定義的Bean例項(物件):
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
TestDao testDAO = (TestDao )ac.getBean("TestDao ");
如果是兩個以上配置檔案:
ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml","spring-mybatis.xml"});
或者用萬用字元:
測試流程:
1、選擇需要測試的類:dao或者service的實現類 2、右鍵,找到 Junit Test Case
。。。
new: java資料夾下面的Junit資料夾裡package預設在當前dao或者service裡,推薦建立新的test包 注意選完包名要記得點選Next,不要點選Finish 勾選選擇所有的方法!
結果:(帶上了asert斷言相關語句程式碼)
接下來就是配置Spring-Test相關注解,引入dao和service進行測試! 1、@RunWith(SpringJUnit4ClassRunner.class); 2、@ContestConfiguration(locations = { "classpath:spring/spring-mybatis.xml" }); 獲取相關配置檔案,不需要匯入mvc相關的配置檔案,支援多配置檔案的匯入 3、直接利用@Autowired注入dao或者Service
4、可以考慮引入logger,來進行資料的列印,,而非System.out.println()
7、編寫controller
說明2: 1、controller採用restful風格,所以一般請求都是名詞,動作交給http的GET、POST、PUT、等來表述。行為採用動詞表述 2、請求路徑:最好在類名上也編寫,實現模組化 3、Model 、ModelAndView、 HttpServletRequest、基本資料型別、實體物件、Map都可以作為引數傳入方法 4、@RequestMapping()裡面,路徑都用value=“”,訪問方式都進行說明,採用post還是get, 5、@RequestMapping()裡面,可以給一個方法,配置多個路徑訪問它 6、返回json資料,可以加上produces = { "application/json;charset=utf-8" },進行標記,表明這是json資料 7、提高程式碼健壯性,注意try-catch的靈活應用 8、注意方法註釋的編寫,尤其是service層和controller層! 因為專案是一個團隊在開發,註釋詳寫,對人對己都有好處 9、@PathVariable RestFul風格引數直接在url裡,/iot/details/{userId} ,需要用(@PathVariable(“userId”) int userId)進行引數的獲取
dto封裝前端所需要的資料,在service層進行獲取,controller進行返回
1、dto 配置json資料返回通用格式,即資料獲取是否成功,錯誤資訊, data資料(泛型T的使用,使得該方法更靈活) 2、過載建構函式,以便在其他方法裡,便捷優雅的實現資料的封裝