概述:没有写技术博客的经验,看过的博客也不喜欢长篇大论,比较喜欢直观看代码,学习的习惯是行动中理解,如果需要深入了解我会看一些详解的文档,搜索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"> <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
搞定!