概述:沒有寫技術博客的經驗,看過的博客也不喜歡長篇大論,比較喜歡直觀看代碼,學習的習慣是行動中理解,若是須要深刻了解我會看一些詳解的文檔,搜索XXX整合關鍵詞的人,大部分應該是應急需求,或新手學習,更想看到的是能夠運行註釋詳細的空框架模板,精簡可運行的代碼,至少我是這樣的,故此書寫風格就以此爲主。javascript
結構:css
一:建立一個maven 項目,配置pom.xmlhtml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>spring_v1</groupId> <artifactId>spring_v1</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <springmvc.version>4.0.2.RELEASE</springmvc.version> <log4j.version>1.6.6</log4j.version> <mysql-connector-java.version>5.1.34</mysql-connector-java.version> </properties> <dependencies> <!-- spring-mvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${springmvc.version}</version> </dependency> <dependency> <groupId>org.springframework.webflow</groupId> <artifactId>spring-webflow</artifactId> <version>2.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${springmvc.version}</version> </dependency> <!-- freemarker --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.20</version> </dependency> <!-- 阿里jdbc --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>0.2.21</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.24</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.0.2</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector-java.version}</version> </dependency> <!-- 解決@ResponseBody返回JSON數據,頁面拋出406錯誤的解決方案。 --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> </dependencies> </project>
二:web.xml 配置java
<?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/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>spring_v1</display-name> <!-- 集成Web環境的通用配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:/spring-application.xml </param-value> </context-param> <!-- spring上下文 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- springMVC 配置 --> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 編碼格式UTF-8 --> <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> </web-app>
三:spring-application.xml 配置mysql
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:security="http://www.springframework.org/schema/security" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.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.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 默認的註解映射的支持 --> <mvc:annotation-driven /> <!-- 自動掃描的包名 --> <context:component-scan base-package="com" /> <!-- 數據庫配置文件 --> <context:property-placeholder location="classpath:app.properties" /> <!-- 靜態資源文件的訪問 --> <mvc:resources mapping="/resource/**" location="/resource/" cache-period="31556926" /> <!-- 配置數據源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本屬性 --> <property name="url" value="${database.url}" /> <property name="username" value="${database.user}" /> <property name="password" value="${database.password}" /> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="1" /> <property name="minIdle" value="1" /> <property name="maxActive" value="20" /> <!-- 配置獲取鏈接等待超時的時間 --> <property name="maxWait" value="60000" /> <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 'x'" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> </bean> <!-- 配置myBatis --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 掃描sqlMap 自動配置 --> <property name="mapperLocations" value="classpath*:com/common/orm/sqlmap/*.xml" /> </bean> <!-- 自動注入dao --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.common.orm.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!--Jsp視圖解析器-ViewResolver --> <bean id="viewResolverJsp" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/"/> <property name="suffix" value=".jsp"/> <property name="order" value="1"/> </bean> <!-- 配置freeMarker視圖解析器 --> <bean id="viewResolverFtl" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/> <property name="contentType" value="text/html;charset=utf-8"/> <property name="cache" value="true" /> <property name="suffix" value=".ftl" /> <property name="order" value="0"/> </bean> <bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/" /> <property name="freemarkerSettings"> <props> <prop key="default_encoding">UTF-8</prop> <prop key="url_escaping_charset">UTF-8</prop> <prop key="template_update_delay">1</prop> <prop key="tag_syntax">auto_detect</prop> <prop key="whitespace_stripping">true</prop> <prop key="classic_compatible">true</prop> <prop key="number_format">0.##########</prop> <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop> <prop key="template_exception_handler">ignore</prop> <prop key="object_wrapper">freemarker.ext.beans.BeansWrapper</prop> </props> </property> <!-- 自定義模板配置 --> <property name="freemarkerVariables"> <map> <entry key="index_Link" value-ref="indexLinkTag" /> </map> </property> </bean> </beans>
四:app.properties 配置jquery
database.url=jdbc:mysql://localhost:3306/springv?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8 database.driver=com.mysql.jdbc.Driver database.user=root database.password=root
以上四步配置後,建立controller進行測試。web
五:建立Controllerajax
package com.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller //控制器(注入服務) @RequestMapping(value="") //訪問地址,value="index" 則訪問地址爲:XXXX/index public class IndexAction { /** * @param value :值同上用於訪問命名 */ @RequestMapping(value = "" ,method = RequestMethod.GET) public ModelAndView initLoad() throws Exception { //值爲視圖文件所在位置。 ModelAndView mav = new ModelAndView("index"); return mav; } }
運行。。。。。。。spring
輸入本身的地址+項目名:http://localhsot:8080/spring_v1sql
完成!
下面使用service從數據庫調用數據試試看。
這裏使用mybatis的自動生成工具 mybatis-generator
下載地址:http://pan.baidu.com/s/1qXqsN7Y
若是是初學者,提供下教程:
1解壓後,打開lib/generatorConfig.xml
配置以下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 數據庫驅動--> <classPathEntry location="mysql-connector-java-5.1.25-bin.jar"/> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"/> <!-- 是否去除自動生成的註釋 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--數據庫連接URL,用戶名、密碼 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/springv" userId="root" password="root"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成模型的包名和位置--> <javaModelGenerator targetPackage="com.entity" targetProject="src"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成映射文件的包名和位置--> <sqlMapGenerator targetPackage="com.common.orm.sqlmap" targetProject="src"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 生成DAO的包名和位置--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.common.orm.mapper" targetProject="src"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 要生成的表 tableName是數據庫中的表名或視圖名 domainObjectName是實體類名--> <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>
根據本身數據庫狀況,配置好後 按shift+右鍵-在此處打開命令窗口:
輸入:java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite
回車OK。最後把生成好的文件放入項目中,能夠開始寫service了。
數據庫隨便寫了個,來測試。
六:建立service 類
package com.service; import java.util.List; import com.entity.User; public interface UserService { public abstract User findByKey(int userId)throws Exception; }
七:建立serviceImpl 實現類
package com.serviceImpl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.common.orm.mapper.UserMapper; import com.entity.User; import com.service.UserService; @Service("userService") public class UserServiceImpl implements UserService { @Autowired private UserMapper usermapper; @Override public User findByKey(int userId) { return usermapper.selectByPrimaryKey(userId); } }
注意:springmvc的@註解,要填寫上。
八:建立UserAction
package com.controller; import java.util.HashMap; import java.util.Map; 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.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.entity.User; import com.service.UserService; @Controller @RequestMapping(value="user") public class UserAction { @Autowired private UserService userService; @RequestMapping(value = "" ,method = RequestMethod.POST) @ResponseBody public Map<String,Object> findUser(String userId) throws Exception { User user = userService.findByKey(Integer.parseInt(userId)); Map<String,Object> map = new HashMap<String,Object>(); map.put("userName", user.getUserName()); return map; } }
九:JSP
頁面就用index.jsp 寫吧。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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>Insert title here</title> </head> <jsp:include page="/WEB-INF/common.jsp"></jsp:include> <script type="text/javascript"> function toAjaxPost(){ $.ajax({ url: 'user', type: 'POST', data : { 'userId' : $("#userId").val() }, success: function(result) { $("#show").text(result.userName); }, error:function(result){ alert("error"); } });//end } </script> <body> <input id ="userId" /> <button onclick="toAjaxPost()">search</button> <a id="show">---</a> </body> </html>
這裏 include了common.jsp,用來引用js,css等做用,方便之後拓展。
common.jsp 以下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() +"://" + request.getServerName() + ":" + request.getServerPort() + path; %> <base href="http://${header['host']}${pageContext.request.contextPath}/" /> <script type="text/javascript" src="<%=basePath%>/resource/js/jquery-1.8.2.js"></script>
完成以上,
URL地址訪問:localhost:8080/spring_v1
OK!
下面配置freemarker自定義模板。
還記得在spring-application.xml中的這一段代碼。
<!-- 自定義模板配置 --> <property name="freemarkerVariables"> <map> <entry key="index_Link" value-ref="indexLinkTag" /> </map> </property>
十:建立自定義模板
package com.freemarker; import java.io.IOException; import java.io.StringReader; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import com.entity.User; import com.service.UserService; import freemarker.core.Environment; import freemarker.template.ObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; @Component("indexLinkTag") public class IndexLinkTag implements TemplateDirectiveModel { @Autowired private FreeMarkerConfigurer freeMarkerConfigurer; @Autowired private UserService userService;
/* *@param env 系統環境變量,一般用它來輸出相關內容,如Writer out = env.getOut(); *@param loopVars 循環替代變量 *@param body 用於處理自定義標籤中的內容,如<@myDirective>將要被處理的內容</@myDirective>;當標籤是<@myDirective />格式時,body=null */ @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { try { String countval = String.valueOf(params.get("userId")); int userId = Integer.parseInt(countval); User user =userService.findByKey(userId); ArrayList<String> list = new ArrayList<String>(); list.add(user.getUserName()); if (body != null) { TemplateModel sourceVariable = env.getVariable("indexLinkTagList"); env.setVariable("indexLinkTagList", ObjectWrapper.BEANS_WRAPPER.wrap(list)); body.render(env.getOut()); env.setVariable("indexLinkTagList", sourceVariable); } } catch (Exception e) { e.printStackTrace(); } } }
十一:建立ftl(index.ftl)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> </head> <body> [@index_Link userId =5 ] <ul style="color:red"> [#list indexLinkTagList as indexLink] <li style="color:red"> ${indexLink} </li> [/#list] </ul> [/@index_Link] </body> </html>
在Action添加進去
package com.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller //控制器(注入服務) @RequestMapping(value="") //訪問地址,value="index" 則訪問地址爲:XXXX/index public class IndexAction { /** * @param value :值同上用於訪問命名 */ @RequestMapping(value = "" ,method = RequestMethod.GET) public ModelAndView initLoad() throws Exception { //值爲視圖文件所在位置。 ModelAndView mav = new ModelAndView("index"); return mav; } @RequestMapping(value = "ftl" ,method = RequestMethod.GET) public ModelAndView initFltLoad() throws Exception { ModelAndView mav = new ModelAndView("ftl/index"); return mav; } }
訪問 localhost:8080/spring_v1/ftl
搞定!