[手把手教程][JavaWeb]優(yōu)雅的SpringMvc+Mybatis應(yīng)用(八)
項目github地址:https://github.com/pc859107393/SpringMvcMybatis
我的簡書首頁是:http://m.itdecent.cn/users/86b79c50cfb3/latest_articles
上一期是:優(yōu)雅的SpringMvc+Mybatis應(yīng)用(七)
工具
- IDE為idea16
- JDK環(huán)境為1.8
- gradle構(gòu)建,版本:2.14.1
- Mysql版本為5.5.27
- Tomcat版本為7.0.52
- 流程圖繪制(xmind)
本期目標(biāo)
- 多角色控制思路整理
- 第一季項目總結(jié)
多角色控制思路整理
關(guān)于多角色控制,起始用戶角色按照用戶職能分工,一般來說思路如下:
- 登陸成功根據(jù)用戶角色,跳轉(zhuǎn)不同的界面模塊
- 每個界面模塊都有用戶權(quán)限校驗,防止用戶逾越雷池一步
- 后端接口需要做用戶角色校驗,用戶異常調(diào)用接口,就中斷用戶訪問。
- 后端的web頁面根據(jù)不同用戶分組存放,然后各個用戶之間不做關(guān)聯(lián)
第一季項目總結(jié)
第一季的倉庫管理系統(tǒng)到目前為止基本上算是結(jié)束了。雖然說不是完整的系統(tǒng),但是我們在里面已經(jīng)大概把基本的web開發(fā)的東西都梳理過了。我們現(xiàn)在來從頭到尾的梳理一下吧。從我們項目從頭到尾,我們分為幾個階段:
- 項目基本框架選擇
- 項目框架整合、驗證
- 項目需求分析
- 功能模塊開發(fā)思路整理
- Spring經(jīng)典三層應(yīng)用
- 開發(fā)細節(jié)思考
- web頁面簡單優(yōu)化
- js網(wǎng)絡(luò)請求實現(xiàn)
- ··· 等等
項目基本框架選擇:
說實話這是一個技術(shù)活,我們程序員的角度來說無外乎就是實現(xiàn)容易、擴展便捷、運行穩(wěn)定等等。按照軟件工程的話來說就是節(jié)約成本、提高質(zhì)量。
說點人話就是:從產(chǎn)品設(shè)計到編碼,這一切基本都是人的活動,所以我們選擇的框架首先要降低學(xué)習(xí)技術(shù)成本、開發(fā)技術(shù)成本、設(shè)計轉(zhuǎn)換編碼的成本、不同應(yīng)用(模塊)整合成本等等。
再總結(jié)一下:我們程序的編碼語言應(yīng)該是我們最熟悉的,應(yīng)用的各個模塊之間交互應(yīng)該是我們擅長的。
所以我選擇了java作為主要的編程語言,后端框架就是Spring+SpringMVC+Mybatis,后端數(shù)據(jù)庫為Mysql。
項目框架整合、驗證:
首先我們需要使用構(gòu)建工具引入Spring+SpringMVC+Mybatis這些框架的jar包,方式有大概兩種:①自行下載jar包②使用自動化構(gòu)建工具完成下載。方式一中需要我們自行選擇jar包手動下載然后引入到lib文件夾。方式二我們只需要使用類似代碼的方式控制程序自動下載。先進的工具能提高生產(chǎn)力,所以我們選擇自動化構(gòu)建完成jar包引入。
第一步,引入jar包,我們在gradle中引入,代碼如下:
testCompile group: 'junit', name: 'junit', version: '4.11'
compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.1.1'
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.6'
compile group: 'com.alibaba', name: 'druid', version: '1.0.25'
compile group: 'org.mybatis', name: 'mybatis', version: '3.4.1'
compile group: 'org.mybatis', name: 'mybatis-spring', version: '1.3.0'
compile group: 'taglibs', name: 'standard', version: '1.1.2'
compile group: 'jstl', name: 'jstl', version: '1.2'
compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
//Spring 框架基本的核心工具類
compile group: 'org.springframework', name: 'spring-core', version: '4.3.2.RELEASE'
//訪問配置文件、創(chuàng)建和管理bean 以及進行Inversion of Control / Dependency Injection(IoC/DI)操作相關(guān)的所有類。
//如果應(yīng)用只需基本的IoC/DI 支持,引入spring-core.jar 及spring-beans.jar 文件就可以了。
compile group: 'org.springframework', name: 'spring-beans', version: '4.3.2.RELEASE'
//Spring 核心提供了大量擴展??梢哉业绞褂肧pring ApplicationContext特性時所需的全部類,JDNI 所需的全部類,instrumentation組件以及校驗Validation 方面的相關(guān)類。
compile group: 'org.springframework', name: 'spring-context', version: '4.3.2.RELEASE'
//Spring 對JDBC 數(shù)據(jù)訪問進行封裝的所有類。
compile group: 'org.springframework', name: 'spring-jdbc', version: '4.3.2.RELEASE'
//spring-tx 事務(wù)管理
compile group: 'org.springframework', name: 'spring-tx', version: '4.3.2.RELEASE'
//Web 應(yīng)用開發(fā)時,用到Spring 框架時所需的核心類,包括自動載入Web Application Context 特性的類、Struts 與JSF 集成類、文件上傳的支持類、Filter 類和大量工具輔助類。
//外部依賴spring-context, Servlet API, (JSP API, JSTL, Commons FileUpload, COS)。
compile group: 'org.springframework', name: 'spring-web', version: '4.3.2.RELEASE'
//Spring MVC 框架相關(guān)的所有類。包括框架的Servlets,Web MVC框架,控制器和視圖支持。
compile group: 'org.springframework', name: 'spring-webmvc', version: '4.3.2.RELEASE'
compile group: 'org.springframework', name: 'spring-test', version: '4.3.2.RELEASE'
compile group: 'redis.clients', name: 'jedis', version: '2.7.3'
//序列化和反序列化工具
compile group: 'com.dyuproject.protostuff', name: 'protostuff-core', version: '1.0.8'
compile group: 'com.dyuproject.protostuff', name: 'protostuff-runtime', version: '1.0.8'
//文件上傳工具類,不過可以使用Spring自帶的文件工具
compile group: 'commons-collections', name: 'commons-collections', version: '3.2.2'
compile group: 'commons-fileupload', name: 'commons-fileupload', version: '1.3.2'
compile group: 'commons-io', name: 'commons-io', version: '2.5'
//請求的UserAgent拆裝箱工具
compile group: 'eu.bitwalker', name: 'UserAgentUtils', version: '1.20'
runtime group: 'mysql', name: 'mysql-connector-java', version: '5.1.37'
第二步,設(shè)置各個框架,并保存到配置文件中,我們的WebApp最重要的最基本的配置是web.xml,這里配置了我們基本程序的設(shè)定,同樣的我們需要在這里導(dǎo)入一些設(shè)置,如下:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1" metadata-complete="true">
<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>
<!-- 如果是用mvn命令生成的xml,需要修改servlet版本為3.1 -->
<!-- 配置DispatcherServlet -->
<servlet>
<display-name>SSM</display-name>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置springMVC需要加載的配置文件
spring-dao.xml,spring-service.xml,spring-web.xml
Mybatis - > spring -> springmvc
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<!-- 默認匹配所有的請求 -->
<url-pattern>/</url-pattern>
<!--<url-pattern>/css/*</url-pattern>-->
<!--<url-pattern>/images/*</url-pattern>-->
<!--<url-pattern>/fonts/*</url-pattern>-->
</servlet-mapping>
<!-- spring框架提供的字符集過濾器 -->
<!-- spring Web MVC框架提供了org.springframework.web.filter.CharacterEncodingFilter用于解決POST方式造成的中文亂碼問題 -->
<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>
<!-- force強制,促使 -->
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--druid ==> WEB方式監(jiān)控配置-->
<servlet>
<servlet-name>DruidStatView</servlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
<init-param>
<!-- 用戶名 -->
<param-name>loginUsername</param-name>
<param-value>pc859107393</param-value>
</init-param>
<init-param>
<!-- 密碼 -->
<param-name>loginPassword</param-name>
<param-value>laopo5201314</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DruidStatView</servlet-name>
<url-pattern>/druid/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>druidWebStatFilter</filter-name>
<filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
<init-param>
<param-name>exclusions</param-name>
<param-value>/public/*,*.js,*.css,/druid*,*.jsp,*.swf</param-value>
</init-param>
<init-param>
<param-name>principalSessionName</param-name>
<param-value>sessionInfo</param-value>
</init-param>
<init-param>
<param-name>profileEnable</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>druidWebStatFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<error-page>
<error-code>404</error-code>
<location>/static/view/404.html</location>
</error-page>
</web-app>
按照上面所說的,我們生成spring文件的存放路徑后,我們接著應(yīng)該做的是控制spring,那么spring的配置文件如下(很多時候我們可以看到他們有的只有一個配置文件,而我將它們拆分成為三個配置文件),具體實現(xiàn)如下:
- spring-dao.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置整合mybatis過程 -->
<!-- 1.配置數(shù)據(jù)庫相關(guān)參數(shù)properties的屬性:${url} -->
<!-- 這里使用代碼提示工具可以直接生成jdbc的配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 2.數(shù)據(jù)庫連接池,采用阿里巴巴的Druid -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" 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="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="10" />
<!-- 配置獲取連接等待超時的時間 -->
<property name="maxWait" value="10000" />
<!-- 配置間隔多久才進行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一個連接在池中最小生存的時間,單位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="testWhileIdle" value="true" />
<!-- 這里建議配置為TRUE,防止取到的連接不可用 -->
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="false" />
<!-- 打開PSCache,并且指定每個連接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize"
value="20" />
<!-- 這里配置提交方式,默認就是TRUE,可以不用配置 -->
<property name="defaultAutoCommit" value="true" />
<!-- 驗證連接有效與否的SQL,不同的數(shù)據(jù)配置不同 -->
<property name="validationQuery" value="select 1 " />
<property name="filters" value="stat" />
<property name="proxyFilters">
<list>
<ref bean="logFilter" />
</list>
</property>
</bean>
<!-- 3.配置SqlSessionFactory對象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入數(shù)據(jù)庫連接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 掃描entity包 使用別名 -->
<property name="typeAliasesPackage" value="cn.acheng1314.domain"/>
<!-- 掃描sql配置文件:mapper需要的xml文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 4.配置掃描Dao接口包,動態(tài)實現(xiàn)Dao接口,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 給出需要掃描Dao接口包 -->
<property name="basePackage" value="cn.acheng1314.dao"/>
</bean>
<bean id="logFilter" class="com.alibaba.druid.filter.logging.Slf4jLogFilter">
<property name="statementExecutableSqlLogEnable" value="false" />
</bean>
</beans>
-
spring-service.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 掃描service包下所有使用注解的類型 --> <!-- cn.acheng1314為我們應(yīng)用的包名,當(dāng)然也是我們前面提到過的GroupId --> <context:component-scan base-package="cn.acheng1314.service"> <!-- 只掃描標(biāo)記了Service的類 --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> <!-- 配置事務(wù)管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入數(shù)據(jù)庫連接池 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置基于注解的聲明式事務(wù) --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans> -
spring-web.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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 配置SpringMVC --> <!-- 1.開啟SpringMVC注解模式 --> <!-- 簡化配置: (1)自動注冊DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter (2)提供一些列:數(shù)據(jù)綁定,數(shù)字和日期的format @NumberFormat, @DateTimeFormat, xml,json默認讀寫支持 --> <mvc:annotation-driven/> <!-- 2.靜態(tài)資源默認servlet配置 (1)加入對靜態(tài)資源的處理:js,gif,png (2)允許使用"/"做整體映射 --> <mvc:resources mapping="/css/**" location="/static/css/"/> <mvc:resources mapping="/images/**" location="/static/images/"/> <mvc:resources mapping="/view/**" location="/static/view/"/> <mvc:resources mapping="/js/**" location="/static/js/"/> <mvc:resources mapping="/fonts/**" location="/static/fonts/"/> <mvc:default-servlet-handler/> <!-- 訪問攔截 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**/**"/> <bean class="cn.acheng1314.intercepter.LoginHandlerInterceptor"/> </mvc:interceptor> </mvc:interceptors> <!-- 3.配置jsp 顯示ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10000000"/> </bean> <!-- 4.掃描web相關(guān)的bean --> <context:component-scan base-package="cn.acheng1314.mvc"> <!-- 制定掃包規(guī)則 ,只掃描使用@Controller注解的JAVA類 --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>
上面的Spring的配置文件我們完成后,我們需要把對應(yīng)的其他文件配置好,如jdbc、mapper、mybatis等的配置文件,以及開發(fā)、測試的代碼和資源文件的存放目錄等等。這些在我們的第一期就能看到了,這里不再贅述。
關(guān)于項目框架驗證,我們需要在搭建完成后,打開日志調(diào)試來看信息,有這幾點原則:
- 數(shù)據(jù)庫鏈接正常
- 數(shù)據(jù)庫驅(qū)動、數(shù)據(jù)庫服務(wù)
- 數(shù)據(jù)庫配置文件
- 數(shù)據(jù)庫測試
- 網(wǎng)頁資源訪問正常
- 靜態(tài)html、js、css、font、image、MP3等
- 動態(tài)的接口
- 動態(tài)頁面如:jsp
- 提示信息正常
- 異常輸出
- log輸出
- 等等···
具體的檢測我們在第二期里面提到過,這里我們也就跳過吧,畢竟主角還在后面。
項目需求分析,本身來說也不是我們作為程序員應(yīng)該考慮的,畢竟涉及到的東西很多,這里我么略過,我們在以后的開發(fā)中再提。
起始這里我最想說的額就是前面開發(fā)的細節(jié),也就是我們當(dāng)中用到的知識點。按照我們開發(fā)的思路來說,我們先從Dao層來實現(xiàn),來一起看看前面用到的知識點。
首先我們需要一個基類的Dao接口,同時我們需要用泛型來解耦,告訴程序我們這里需要的什么樣的對象來存入數(shù)據(jù)庫,同時某些對象特有的方法那么就在該對象的自身的接口中實現(xiàn)。我們的基類Dao層如下:
/**
* 通過接口編程
*
* @param <T> 泛型用于解耦,同時避免寫重復(fù)代碼
*/
interface Dao<T extends Serializable> {
/**
* 添加某個對象
*
* @param t 待添加的對象
* @return 返回受影響的行數(shù)
*/
int add(T t);
/**
* 刪除某個對象,在企業(yè)開發(fā)中,我們一般不做物理刪除,只是添加某個字段對其數(shù)據(jù)進行可用控制
*
* @param t 待刪除對象
* @return 返回受影響的條數(shù)
*/
int del(T t);
/**
* 更新某個對象
*
* @param t 待更新對象
* @return 返回受影響的條數(shù)
*/
int update(T t);
/**
* 通過ID查找一個對象
*
* @param Id 待查詢的對象的ID
* @return 返回該ID對應(yīng)的對象
*/
T findOneById(Serializable Id);
/**
* 查找對象集合
*
* @return 返回對象集合
*/
List<T> findAll();
}
這里我們需要重點說一下多參數(shù)的Dao方法和返回List的Dao方法,話不多說,直接上代碼:
//Dao層中,多參數(shù)的方法如何讓Mybatis響應(yīng)?
/**
* 分頁查詢
* @param offset 起始位置
* @param limit 每頁數(shù)量
* @return
*/
List<UserActionLog> findAll(@Param("offset") int offset, @Param("limit") int limit);
//從上面我們可以看到,我們方法參數(shù)的前面都加上了注解@Param(),同時在注解中填寫了對應(yīng)的名字,這是為何?請看下面的Mybatis的xml中的內(nèi)容:
<select id="findAll" resultType="cn.acheng1314.domain.UserActionLog" >
SELECT
*
FROM
`user_action_log`
ORDER BY
`id`
DESC
LIMIT #{offset}, #{limit}
</select>
//在上面的Mybatis的xml中的內(nèi)容看來,我們是需要拿到上面參數(shù)對應(yīng)的注解名字。
//同時,我在xml文件中的select語句的id為findAll也和Dao中的方法相對應(yīng),resultType返回數(shù)據(jù)類型設(shè)定為UserActionLog。
//通過這樣簡單的設(shè)定就可以實現(xiàn)列表查找了。
//我們接著看看下面的Dao層的代碼:
int update(User user);
//上面的是在UserDao里復(fù)制出來的,它對應(yīng)的mapper為UserDao.xml,對應(yīng)的方法為:
<!-- 更新用戶信息 -->
<update id="update" parameterType="User">
UPDATE
`user`
SET
`name`=#{name}, `age`=#{age}, `sex`=#{sex}, `duty`=#{duty}, `cell_number`=#{cellNumber}, `photo_url`=#{photoUrl}
WHERE
`login_id`=#{loginId};
</update>
//注意我前面提到過mapper中的id必須和方法名一樣的,“#{字段名}”這種格式表示:
//①如果接口的方法中傳遞的是對象,則表示該字段為對象的某一個屬性
//②如果接口的方法中傳遞的是一個或者多個參數(shù),則該字段對應(yīng)為接口中參數(shù)的注解,如上面的findAll
Service層基本沒啥好復(fù)習(xí)的,畢竟現(xiàn)在是直接調(diào)用Dao層。 Service層作為web應(yīng)用的數(shù)據(jù)驅(qū)動層,我們需要在當(dāng)中加入事務(wù)管理、考慮在Dao層中使用存儲過程等設(shè)計來使我們程序執(zhí)行更加高效。一般來說在java web中,我們后端開發(fā)長提的是面向接口編程,同理我們需要通過泛型解耦然后繼承和實現(xiàn)BaseService接口。我們要使框架自動加載我們的Service我們需要做到以下幾點:
- 在Service的實現(xiàn)上面使用@Service("xxxService")注解
- 在Dao層調(diào)用的地方打上注解@Autowired
- 在controller里面調(diào)用Service這里同樣需要在定義的地方注解@Autowired
起始我們應(yīng)該重點強調(diào)下Controller層,畢竟我們web服務(wù)的動態(tài)資源都是從Controller層這里出來的,好的閑話不說,直接從代碼走起:
@Controller //表明這個是Controller,只要這個類放在Spring配置文件指定的Controller路徑中就能自動裝載
@RequestMapping("/actionLog") //域名后面跟的最外層地址
public class ActionLogController {
@Autowired
ActionLogService actionLogService; //自動注入ActionLogService
/**
* 分頁查找行為日志,其實druid里面已經(jīng)包含了行為日志
*
* @param pageNum 頁碼
* @param pageSize 每一頁的條數(shù)
* @return
*/
@RequestMapping(value = "/findLogList"
, produces = "application/json; charset=utf-8") //這里訪問地址的形式是:http://xxx.cn/actionLog/findLogList,響應(yīng)請求頭的ContentType表明響應(yīng)是json數(shù)據(jù),字符編碼為utf8
@ResponseBody //表明這個方法直接返回的是響應(yīng)體的內(nèi)容
public Object findLog(int pageNum, int pageSize) {
//···代碼省略
return json數(shù)據(jù);
}
//關(guān)于請求的參數(shù)說明:
//①當(dāng)請求的解析方法中有基本數(shù)據(jù)類型的參數(shù)(無論個數(shù))時候,mvc框架會自動把請求數(shù)據(jù)存儲為名稱相同的變量的值
//比如說上面我們的訪問為:http://域名/actionLog/findLogList?pageNum=10&pageSize=10
//②當(dāng)請求的解析方法中有封裝數(shù)據(jù)類型的參數(shù)(無論個數(shù))時候,mvc框架會自動根據(jù)請求數(shù)據(jù)的名字查找封裝數(shù)據(jù)的對應(yīng)字段并且自動存值,且無論該數(shù)據(jù)使用了幾次。
// 比如說我網(wǎng)頁登陸的時候有兩個用戶體系,但是他們是通過用戶名關(guān)聯(lián)在一起的,那么如下:
//請求為:http:acheng1314.cn/user/login?userId=acheng&pwd=123456
//請求的解析方法是:
@RequestMapping(value = "/login"
, produces = "application/json; charset=utf-8")
@ResponseBody //表明這個方法直接返回的是響應(yīng)體的內(nèi)容
public Object findLog(User user, Person person) {
//···代碼省略
System.out.printf("log:\t"+user.toString());
System.out.printf("log:\t"+person.toString());
return json數(shù)據(jù);
}
//我們可以看到輸出的日志為:
User{"userId=acheng, pwd=123456, xxx=xxx···"}
Person{"userId=acheng, pwd=123456, xxx=xxx···"}
//所以當(dāng)你后端接收這里無論你又多少實體,但是只要包含對應(yīng)的字段,那么就會自動賦值。
}
在Controller里面我們要注意的是:
- @RequestMapping 注解在類上
- @RequestMapping 注解在方法上
- 方法里的參數(shù)前面的@RequestParam注解
- URI模板完成RESTful風(fēng)格的站點和API → 下一季會詳細介紹
關(guān)于web只有大概下面幾點:
- 減少每個頁面的請求數(shù)。
- js方法整合到頁面,工具js封裝成工具。
- js方法一般寫在頁面頭部
- web頁面除非整體刷新,其他情況考慮異步請求。
- 頁面圖片資源整合到一起,然后根據(jù)位置取圖片
- web頁面良好體驗可以考慮組件引入
- 頁面需要大量重用的地方可以考慮模板完成
其實很多東西這個總結(jié)都沒詳細的說出來,畢竟開發(fā)細節(jié)的東西都不是三言兩語說的明白的,但是完全不慌,即將開始第二季《完整的博客后端+Android客戶端+分模塊開發(fā)+七牛云存儲+微信支付寶整合》正在蘊量,小伙伴們請鼓勵我一下。
希望喜歡我的這個系列的讀者,可以點擊喜歡和收藏。謝謝。
本期項目包里面有福利,后端請求兼容Form表單提交、json數(shù)據(jù)post接收,請大家自行查找。拜拜,下期見。