題外:做過一陣開發,後來接觸了很多東西,改變了觀念,比較浮躁,嘗試過轉行各種崗位,最後做了網路運營,其間走的彎路中學到了很多東西,時間推移開發扔了很久,故此閑暇時間複習下。 概述:沒有寫技術博客的經驗,看過的博客也不喜歡長篇大論,比較喜歡直觀看代碼,學習的習慣是行動中理解,如果需要深入瞭解我會看一些
題外:做過一陣開發,後來接觸了很多東西,改變了觀念,比較浮躁,嘗試過轉行各種崗位,最後做了網路運營,其間走的彎路中學到了很多東西,時間推移開發扔了很久,故此閑暇時間複習下。
概述:沒有寫技術博客的經驗,看過的博客也不喜歡長篇大論,比較喜歡直觀看代碼,學習的習慣是行動中理解,如果需要深入瞭解我會看一些詳解的文檔,搜索XXX整合關鍵詞的人,大部分應該是應急需求,或新手學習,更想看到的是可以運行註釋詳細的空框架模板,精簡可運行的代碼,至少我是這樣的,故此書寫風格就以此為主。
結構:
一:創建一個maven 項目,配置pom.xml
<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 配置
<?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 配置
<?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 配置
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進行測試。
五:創建Controller
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; } }
運行。。。。。。。
輸入自己的地址+項目名:http://localhsot:8080/spring_v1
完成!
下麵使用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"> &l