实战 :Spring MVC + 注解 +SqlServer 框架搭建及详解

本文详细介绍了Spring3MVC框架的搭建过程,包括创建Web项目、配置核心Jar包及web.xml文件等内容,同时提供了数据库操作类的实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

源码下载:http://download.csdn.NET/detail/u010469432/6786687


先说一下Spring3 MVC的优点:

spring MVC 属于轻量级框架

1、Spring3 MVC的学习难度小于Struts2,Struts2用不上的多余功能太多。呵呵,当然这不是决定因素。

2、Spring3 MVC很容易就可以写出性能优秀的程序,Struts2要处处小心才可以写出性能优秀的程序(指MVC部分)

3、Spring3 MVC的灵活是你无法想像的,Spring的扩展性有口皆碑,Spring3 MVC当然也不会落后,不会因使用了MVC框架而感到有任何的限制。


对于SpringMVC的一些文档型理论知识我不再多加赘述,今天主要是一步一步的开始搭建框架,当然这是我工作中的成果。

不多说,上代码:


1.创建Web project,我使用的是myeclipse。起名为Springmvc(名字自定)


2.引用SpringMVC 需要的核心jar包:


3.配置web.xml文件

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  5.     version="2.5">  
  6.     <!-- 配置监听器 -->  
  7.     <listener>  
  8.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  9.     </listener>  
  10.     <!-- 在项目启动时,加载Src/config下的所有以 spring- 开头的.xml 配置文件 -->  
  11.     <context-param>  
  12.         <param-name>contextConfigLocation</param-name>  
  13.         <param-value>classpath:config/spring-*.xml</param-value>  
  14.     </context-param>  
  15.     <!--项目启动后默认打开的页面 -->  
  16.     <welcome-file-list>  
  17.         <welcome-file>login.jsp</welcome-file>  
  18.     </welcome-file-list>  
  19.     <!--这里的配置是关键,servlet-name  -->  
  20.     <servlet>  
  21.         <servlet-name>springmvc</servlet-name>  
  22.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  23.         <!-- 配置加载相应的文件 -->  
  24.         <init-param>  
  25.             <param-name>contextConfigLocation</param-name>  
  26.             <param-value>classpath*:config/springmvc.xml</param-value>  
  27.         </init-param>  
  28.         <load-on-startup>1</load-on-startup>  
  29.     </servlet>  
  30.     <!-- 配置servlet映射    
  31.       在访问URL时路径要写为:  /service/+ Controller 层@RequestMapping("/admin") 中的admin /+方法上的@RequestMapping(value = "/login")中的 login   
  32.      例如  登陆表单  提交的action就是     /service/admin/login -->  
  33.     <servlet-mapping>  
  34.         <servlet-name>springmvc</servlet-name>  
  35.         <url-pattern>/service/*</url-pattern>  
  36.     </servlet-mapping>  
  37.   
  38. </web-app>  


4.配置Spring.xml文件,此文件的名称必须与web.xml中的servlet-name名称一致。

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:cache="http://www.springframework.org/schema/cache"   xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans    
  8.             http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
  9.             http://www.springframework.org/schema/context    
  10.             http://www.springframework.org/schema/context/spring-context-3.1.xsd    
  11.             http://www.springframework.org/schema/tx    
  12.             http://www.springframework.org/schema/tx/spring-tx-3.1.xsd    
  13.             http://www.springframework.org/schema/jdbc    
  14.             http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd  
  15.             http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd"  
  16.     default-autowire="byName">  
  17.     <!-- 自动搜索@Controller标注的类 -->  
  18.     <context:component-scan base-package="com.yfapp.platform" />  
  19.     <context:annotation-config />  
  20.   
  21.     <bean  
  22.         class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />  
  23.     <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->  
  24.     <bean  
  25.         class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
  26.         <property name = "messageConverters">  
  27.           <list>  
  28.            <bean class="org.springframework.http.converter.StringHttpMessageConverter">  
  29.            <property name="supportedMediaTypes">  
  30.             <list>  
  31.              <value>text/plain;charset=UTF-8</value>  
  32.             </list>  
  33.            </property>  
  34.            </bean>  
  35.           </list>  
  36.         </property>  
  37.     </bean>  
  38.   
  39.     <!-- Default ViewResolver -->  
  40.     <bean id="viewResolver"  
  41.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  42.         <property name="viewClass"  
  43.             value="org.springframework.web.servlet.view.JstlView" />  
  44.         <property name="prefix" value="" />  
  45.         <property name="suffix" value=".jsp"></property>  
  46.     </bean>  
  47.  <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->    
  48.  <cache:annotation-driven cache-manager="cacheManager"/>    
  49. <bean id="cacheManager" class="org.springframework.cache.concurrent.ConcurrentMapCacheManager" />     
  50. </beans>  

5.配置数据库读取文件jdbc.properties放在类文件夹src下我这里加载的是SqlServer数据库

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver     //连接的数据库  
  2. url=jdbc:sqlserver://127.0.0.1:1433; DatabaseName=renji            
  3. username=sa  
  4. password=admin  


6.配置数据库相关的文件

spring-application.xml(文件名称可以自定义,但是需要在web.xml文件中加载这里即对应web.xml中的<!--在你项目启动时加载spring- 开头的.xml文件-->)

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  6.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">  
  7.     <!-- 读取资源文件   步骤5 的文件 -->  
  8.     <bean  
  9.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  10.         <property name="location" value="classpath:jdbc.properties" />  
  11.     </bean>  
  12.     <!-- 这个是Spring的注入技术   给org.apache.commons.dbcp.BasicDataSource 类的属性注入对应的值 ,读取数据库配置信息-->  
  13.     <bean id="dataSource"  
  14.         class="org.apache.commons.dbcp.BasicDataSource">  
  15.         <property name="driverClassName" value="${driverClassName}"></property>  
  16.         <property name="password" value="${password}"></property>  
  17.         <property name="username" value="${username}"></property>  
  18.         <property name="url" value="${url}"></property>  
  19.     </bean>  
  20.     <!-- 这个是向第7步中的 DbUtilsTemplate.java 类的dataSource变量注入值  -->  
  21.     <bean id="dbUtilsTemplate" class="com.yfapp.platform.dao.template.DbUtilsTemplate">   
  22.         <property name="dataSource" ref="dataSource" />   
  23.     </bean>   
  24.       
  25. </beans>  

7.数据库操作类:DbUtilsTemplate.Java这是我封装好的工具类直接使用就可以了。

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. import java.sql.SQLException;  
  2. import java.util.ArrayList;  
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import javax.sql.DataSource;  
  7.   
  8. import org.apache.commons.dbcp.BasicDataSource;  
  9. import org.apache.commons.dbutils.QueryRunner;  
  10. import org.apache.commons.dbutils.handlers.BeanHandler;  
  11. import org.apache.commons.dbutils.handlers.BeanListHandler;  
  12. import org.apache.commons.dbutils.handlers.MapHandler;  
  13. import org.apache.commons.dbutils.handlers.MapListHandler;  
  14. import org.apache.commons.dbutils.handlers.ScalarHandler;  
  15. import org.apache.commons.logging.Log;  
  16. import org.apache.commons.logging.LogFactory;  
  17.   
  18. public class DbUtilsTemplate {  
  19.     private DataSource dataSource;   
  20.     private QueryRunner queryRunner;   
  21.     private static final Log LOG = LogFactory.getLog(DbUtilsTemplate.class);   
  22.   
  23.     public void setDataSource(BasicDataSource dataSource) {   
  24.         this.dataSource = dataSource;   
  25.     }   
  26.   
  27.     /**   
  28.      * 执行sql语句   
  29.      * @param sql sql语句   
  30.      * @return 受影响的行数   
  31.      */   
  32.     public int update(String sql) {   
  33.         return update(sql, null);   
  34.     }   
  35.   
  36.     /**   
  37.      * 执行sql语句   
  38.      * <code>   
  39.      * executeUpdate("update user set username = 'kitty' where username = ?", "hello kitty");   
  40.      * </code>   
  41.      * @param sql sql语句   
  42.      * @param param 参数   
  43.      * @return 受影响的行数   
  44.      */   
  45.     public int update(String sql, Object param) {   
  46.         return update(sql, new Object[] { param });   
  47.     }   
  48.   
  49.     /**   
  50.      * 执行sql语句   
  51.      * @param sql sql语句   
  52.      * @param params 参数数组   
  53.      * @return 受影响的行数   
  54.      */   
  55.     public int update(String sql, Object[] params) {   
  56.         queryRunner = new QueryRunner(dataSource,true);   
  57.         int affectedRows = 0;   
  58.         try {   
  59.             if (params == null) {   
  60.                 affectedRows = queryRunner.update(sql);   
  61.             } else {   
  62.                 affectedRows = queryRunner.update(sql, params);   
  63.             }   
  64.         } catch (SQLException e) {   
  65.             LOG.error("Error occured while attempting to update data", e);   
  66.         }   
  67.         return affectedRows;   
  68.     }   
  69.   
  70.     /**   
  71.      * 执行批量sql语句   
  72.      * @param sql sql语句   
  73.      * @param params 二维参数数组   
  74.      * @return 受影响的行数的数组   
  75.      */   
  76.     public int[] batchUpdate(String sql, Object[][] params) {   
  77.         queryRunner = new QueryRunner(dataSource,true);   
  78.         int[] affectedRows = new int[0];   
  79.         try {   
  80.             affectedRows = queryRunner.batch(sql, params);   
  81.         } catch (SQLException e) {   
  82.             LOG.error("Error occured while attempting to batch update data", e);   
  83.         }   
  84.         return affectedRows;   
  85.     }       
  86.   
  87.     /**   
  88.      * 执行查询,将每行的结果保存到一个Map对象中,然后将所有Map对象保存到List中   
  89.      * @param sql sql语句   
  90.      * @return 查询结果   
  91.      */   
  92.     public List<Map<String, Object>> queryForList(String sql) {   
  93.         return queryForList(sql, null);  
  94.     }   
  95.   
  96.     /**   
  97.      * 执行查询,将每行的结果保存到一个Map对象中,然后将所有Map对象保存到List中   
  98.      * @param sql sql语句   
  99.      * @param param 参数   
  100.      * @return 查询结果   
  101.      */   
  102.     public List<Map<String, Object>> queryForList(String sql, Object param) {   
  103.         return queryForList(sql, new Object[] {param});   
  104.     }   
  105.   
  106.     /**   
  107.      * 执行查询,将每行的结果保存到一个Map对象中,然后将所有Map对象保存到List中   
  108.      * @param sql sql语句   
  109.      * @param params 参数数组   
  110.      * @return 查询结果   
  111.      */   
  112.     @SuppressWarnings("unchecked")   
  113.     public List<Map<String, Object>> queryForList(String sql, Object[] params) {   
  114.         queryRunner = new QueryRunner(dataSource,true);   
  115.         List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();   
  116.         try {   
  117.             if (params == null) {   
  118.                 list = (List<Map<String, Object>>) queryRunner.query(sql, new MapListHandler());   
  119.             } else {   
  120.                 list = (List<Map<String, Object>>) queryRunner.query(sql, new MapListHandler(), params);   
  121.             }   
  122.         } catch (SQLException e) {   
  123.             LOG.error("Error occured while attempting to query data", e);   
  124.         }   
  125.         return list;   
  126.     }   
  127.   
  128.     /**   
  129.      * 执行查询,将每行的结果保存到Bean中,然后将所有Bean保存到List中   
  130.      * @param entityClass 类名   
  131.      * @param sql sql语句   
  132.      * @return 查询结果   
  133.      */   
  134.     public <T> List<T> queryForList(Class<T> entityClass, String sql) {   
  135.         return queryForList(entityClass, sql, null);   
  136.     }   
  137.   
  138.     /**   
  139.      * 执行查询,将每行的结果保存到Bean中,然后将所有Bean保存到List中   
  140.      * @param entityClass 类名   
  141.      * @param sql sql语句   
  142.      * @param param 参数   
  143.      * @return 查询结果   
  144.      */   
  145.     public <T> List<T> queryForList(Class<T> entityClass, String sql, Object param) {   
  146.         return queryForList(entityClass, sql, new Object[] { param });   
  147.     }   
  148.   
  149.     /**   
  150.      * 执行查询,将每行的结果保存到Bean中,然后将所有Bean保存到List中   
  151.      * @param entityClass 类名   
  152.      * @param sql sql语句   
  153.      * @param params 参数数组   
  154.      * @return 查询结果   
  155.      */   
  156.     @SuppressWarnings("unchecked")   
  157.     public <T> List<T> queryForList(Class<T> entityClass, String sql, Object[] params) {   
  158.         queryRunner = new QueryRunner(dataSource,true);   
  159.         List<T> list = new ArrayList<T>();   
  160.         try {   
  161.             if (params == null) {   
  162.                 list = (List<T>) queryRunner.query(sql, new BeanListHandler(entityClass));   
  163.             } else {   
  164.                 list = (List<T>) queryRunner.query(sql, new BeanListHandler(entityClass), params);   
  165.             }   
  166.         } catch (SQLException e) {   
  167.             LOG.error("Error occured while attempting to query data", e);   
  168.         }   
  169.         return list;   
  170.     }   
  171.   
  172.     /**   
  173.      * 查询出结果集中的第一条记录,并封装成对象   
  174.      * @param entityClass 类名   
  175.      * @param sql sql语句   
  176.      * @return 对象   
  177.      */   
  178.     public <T> T query(Class<T> entityClass, String sql) {   
  179.         return queryFirst(entityClass, sql, null);   
  180.     }   
  181.   
  182.     /**   
  183.      * 查询出结果集中的第一条记录,并封装成对象   
  184.      * @param entityClass 类名   
  185.      * @param sql sql语句   
  186.      * @param param 参数   
  187.      * @return 对象   
  188.      */   
  189.     public <T> T queryFirst(Class<T> entityClass, String sql, Object param) {   
  190.         return queryFirst(entityClass, sql, new Object[] { param });   
  191.     }   
  192.   
  193.     /**   
  194.      * 查询出结果集中的第一条记录,并封装成对象   
  195.      * @param entityClass 类名   
  196.      * @param sql sql语句   
  197.      * @param params 参数数组   
  198.      * @return 对象   
  199.      */   
  200.     @SuppressWarnings("unchecked")   
  201.     public <T> T queryFirst(Class<T> entityClass, String sql, Object[] params) {   
  202.         queryRunner = new QueryRunner(dataSource,true);   
  203.         Object object = null;   
  204.         try {   
  205.             if (params == null) {   
  206.                 object = queryRunner.query(sql, new BeanHandler(entityClass));   
  207.             } else {   
  208.                 object = queryRunner.query(sql, new BeanHandler(entityClass), params);   
  209.             }   
  210.         } catch (SQLException e) {   
  211.             LOG.error("Error occured while attempting to query data", e);   
  212.         }   
  213.         return (T) object;   
  214.     }   
  215.   
  216.     /**   
  217.      * 查询出结果集中的第一条记录,并封装成Map对象   
  218.      * @param sql sql语句   
  219.      * @return 封装为Map的对象   
  220.      */   
  221.     public Map<String, Object> queryFirst(String sql) {   
  222.         return queryFirst(sql, null);   
  223.     }   
  224.   
  225.     /**   
  226.      * 查询出结果集中的第一条记录,并封装成Map对象   
  227.      * @param sql sql语句   
  228.      * @param param 参数   
  229.      * @return 封装为Map的对象   
  230.      */   
  231.     public Map<String, Object> queryFirst(String sql, Object param) {   
  232.         return queryFirst(sql, new Object[] { param });   
  233.     }   
  234.   
  235.     /**   
  236.      * 查询出结果集中的第一条记录,并封装成Map对象   
  237.      * @param sql sql语句   
  238.      * @param params 参数数组   
  239.      * @return 封装为Map的对象   
  240.      */   
  241.     @SuppressWarnings("unchecked")   
  242.     public Map<String, Object> queryFirst(String sql, Object[] params) {   
  243.         queryRunner = new QueryRunner(dataSource,true);   
  244.         Map<String, Object> map = null;   
  245.         try {   
  246.             if (params == null) {   
  247.                 map = (Map<String, Object>) queryRunner.query(sql, new MapHandler());   
  248.             } else {   
  249.                 map = (Map<String, Object>) queryRunner.query(sql, new MapHandler(), params);   
  250.             }   
  251.         } catch (SQLException e) {   
  252.             LOG.error("Error occured while attempting to query data", e);   
  253.         }   
  254.         return map;   
  255.     }   
  256.   
  257.     /**   
  258.      * 查询某一条记录,并将指定列的数据转换为Object   
  259.      * @param sql sql语句   
  260.      * @param columnName 列名   
  261.      * @return 结果对象   
  262.      */   
  263.     public Object queryForObject(String sql, String columnName) {   
  264.         return queryForOjbect(sql, columnName, null);   
  265.     }   
  266.   
  267.     /**   
  268.      * 查询某一条记录,并将指定列的数据转换为Object   
  269.      * @param sql sql语句   
  270.      * @param columnName 列名   
  271.      * @param param 参数   
  272.      * @return 结果对象   
  273.      */   
  274.     public Object queryForObject(String sql, String columnName, Object param) {   
  275.         return queryForOjbect(sql, columnName, new Object[] { param });   
  276.     }   
  277.   
  278.     /**   
  279.      * 查询某一条记录,并将指定列的数据转换为Object   
  280.      * @param sql sql语句   
  281.      * @param columnName 列名   
  282.      * @param params 参数数组   
  283.      * @return 结果对象   
  284.      */   
  285.     public Object queryForOjbect(String sql, String columnName, Object[] params) {   
  286.         queryRunner = new QueryRunner(dataSource,true);   
  287.         Object object = null;   
  288.         try {   
  289.             if (params == null) {   
  290.                 object = queryRunner.query(sql, new ScalarHandler(columnName));   
  291.             } else {   
  292.                 object = queryRunner.query(sql, new ScalarHandler(columnName), params);   
  293.             }   
  294.         } catch (SQLException e) {   
  295.             LOG.error("Error occured while attempting to query data", e);   
  296.         }   
  297.         return object;   
  298.     }   
  299.   
  300.     /**   
  301.      * 查询某一条记录,并将指定列的数据转换为Object   
  302.      * @param sql sql语句   
  303.      * @param columnIndex 列索引   
  304.      * @return 结果对象   
  305.      */   
  306.     public Object queryForObject(String sql, int columnIndex) {   
  307.         return queryForObject(sql, columnIndex, null);   
  308.     }   
  309.   
  310.     /**   
  311.      * 查询某一条记录,并将指定列的数据转换为Object   
  312.      * @param sql sql语句   
  313.      * @param columnIndex 列索引   
  314.      * @param param 参数   
  315.      * @return 结果对象   
  316.      */   
  317.     public Object queryForObject(String sql, int columnIndex, Object param) {   
  318.         return queryForObject(sql, columnIndex, new Object[] { param });   
  319.     }   
  320.   
  321.     /**   
  322.      * 查询某一条记录,并将指定列的数据转换为Object   
  323.      * @param sql sql语句   
  324.      * @param columnIndex 列索引   
  325.      * @param params 参数数组   
  326.      * @return 结果对象   
  327.      */   
  328.     public Object queryForObject(String sql, int columnIndex, Object[] params) {   
  329.         queryRunner = new QueryRunner(dataSource,true);   
  330.         Object object = null;   
  331.         try {   
  332.             if (params == null) {   
  333.                 object = queryRunner.query(sql, new ScalarHandler(columnIndex));   
  334.             } else {   
  335.                 object = queryRunner.query(sql, new ScalarHandler(columnIndex), params);   
  336.             }   
  337.         } catch (SQLException e) {   
  338.             LOG.error("Error occured while attempting to query data", e);   
  339.         }   
  340.         return object;   
  341.     }   
  342.     /**  
  343.      * 获取记录数  
  344.      * @param sql  
  345.      * @param entityClass  
  346.      * @return 结果对象  
  347.      */  
  348.     public Object  getCount(String sql,Class entityClass){  
  349.         queryRunner = new QueryRunner(dataSource,true);   
  350.         Object i=null;  
  351.         try {  
  352.             List list = (List) queryRunner.query(sql, new BeanListHandler(entityClass));  
  353.             if(list.size()>0){  
  354.                 i=list.get(0);  
  355.             }  
  356.         } catch (SQLException e) {  
  357.             e.printStackTrace();  
  358.         }  
  359.         return i;  
  360.     }  
  361.   
  362.     /**  
  363.      * 获取记录数  
  364.      * @param sql  
  365.      * @param entityClass  
  366.      * @param param  
  367.      * @return 结果对象  
  368.      */  
  369.     public Object getCount(String sql,Class entityClass,Object param ){  
  370.         return getCount(sql,entityClass,new Object[] { param });  
  371.     }  
  372.     /**  
  373.      * 获取记录数  
  374.      * @param sql  
  375.      * @param entityClass  
  376.      * @param Object[] params  
  377.      * @return 结果对象  
  378.      */  
  379.     public Object getCount(String sql,Class entityClass,Object[] params ){  
  380.         queryRunner = new QueryRunner(dataSource,true);  
  381.         Object i=null;  
  382.         try{  
  383.             if (params == null) {  
  384.                 igetCount(sql,entityClass);  
  385.             }else{  
  386.                 List list = (List) queryRunner.query(sql, new BeanListHandler(entityClass),params);  
  387.                 if(list.size()>0){  
  388.                     i=list.get(0);  
  389.                 }  
  390.             }  
  391.         }catch (Exception e) {  
  392.         }  
  393.         return i;  
  394.     }  
  395. }   
8。到此为止,框架已经搭建成功了,可以启动一下项目,


启动成功!

下面我写个测试例子大家看一下:

我的项目是写成了三层分开的架构,控制层(Controller),服务层接口(Service),服务层实现类(ServiceImpl),数据库操作接口(Dao),数据库操作实现类(DaoImpl).


1.login页面:

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%  
  4.     String path = request.getContextPath();  
  5.     String basePath = request.getScheme() + "://"  
  6.             + request.getServerName() + ":" + request.getServerPort()  
  7.             + path + "/";  
  8. %>  
  9. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  10. <html xmlns="http://www.w3.org/1999/xhtml">  
  11. <head>  
  12. <base href="<%=basePath%>">  
  13. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  14. </head>  
  15. <body>  
  16.   
  17.     <form action="service/admin/login" method="post">  
  18.         <div class="user clr">  
  19.             <span class="fl">管 理 员 :</span><input name="adminCode" type="text"  
  20.                 class="fl " />  
  21.         </div>  
  22.         <div class="user clr">  
  23.             <span class="fl">密    码 :</span><input  
  24.                 name="adminPwd" type="password" class="fl" />  
  25.         </div>  
  26.         <div class="user clr">  
  27.             <input name="" type="reset" value="重 置" class="cancel_btn fr" /><input  
  28.                 name="" type="submit" class="login_btn fr" value="登 录" />  
  29.         </div>  
  30.     </form>  
  31.   
  32. </body>  
  33. </html>  

2.Controller(控制)层的代码:AdminController.java

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.yfapp.platform.controller;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpServletResponse;  
  5.   
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.stereotype.Controller;  
  8. import org.springframework.web.bind.annotation.RequestMapping;  
  9.   
  10. import com.yfapp.platform.entity.Admin;  
  11. import com.yfapp.platform.service.AdminService;  
  12.   
  13. @Controller  
  14. @RequestMapping("/admin")  
  15. public class AdminController {  
  16.     @Autowired  
  17.     private AdminService adminService;  
  18.   
  19.     /**  
  20.      * 管理员登陆  
  21.      * @param admin    登陆传入的用户对象  
  22.      * @return String  要跳转到的页面  
  23.      */  
  24.     @RequestMapping(value = "/login")  
  25.     public String login(HttpServletRequest request, HttpServletResponse response, Admin admin) throws Throwable {  
  26.         Admin ad =new Admin();  
  27.         if(null!=admin.getAdminPwd()||null!=admin.getAdminCode()){  
  28.             ad = adminService.login(admin);  
  29.         }else{  
  30.             ad=null;  
  31.         }  
  32.         if (null != ad) {  
  33.             request.getSession().setAttribute("admin", ad);  
  34.             return "/indexhome";  
  35.         } else {  
  36.             request.setAttribute("imgs", "请重新登录!");  
  37.             return "/login";  
  38.         }  
  39.     }  
  40. }  
3.服务层接口:AdminService.java  以及 服务层实现类AdminServiceImpl.java


[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.yfapp.platform.service;  
  2.   
  3.   
  4. import com.yfapp.platform.entity.Admin;  
  5.   
  6. public interface AdminService{  
  7.     //登陆  
  8.     Admin login(Admin admin);  
  9. }  
[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.yfapp.platform.service.impl;  
  2.   
  3.   
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.stereotype.Service;  
  6.   
  7. import com.yfapp.platform.dao.AdminDao;  
  8. import com.yfapp.platform.entity.Admin;  
  9. import com.yfapp.platform.service.AdminService;  
  10.   
  11. @Service("adminService")  
  12. public class AdminServiceImpl implements AdminService{  
  13.     @Autowired  
  14.     private AdminDao adminDao;  
  15.   
  16.     /**  
  17.      * 登陆  
  18.      */  
  19.     public Admin login(Admin admin){  
  20.         return adminDao.login(admin);  
  21.     }  
  22. }  
4.数据库操作接口类   BaseDao.java   和  AdminDao.java

BaseDao.java是基础的操作类,这里面可以将写一些基本的数据库操作方法比如增删改查,我这里就不写了,写这个主要是映射数据库连接,创建连接池。

AdminDao.java是功能模块的接口类,如果你要写别的模块的时候只需要想AdminDao一样继承BaseDao就行,当然如果不需要BaseDao 也可以不写BaseDao,这样写只是应用了java的思想。使用了泛型。

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.yfapp.platform.dao;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public interface BaseDao<PO,ID extends Serializable> {  
  6.       
  7. }  
[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.yfapp.platform.dao;  
  2.   
  3.   
  4. import com.yfapp.platform.entity.Admin;  
  5.   
  6.   
  7. public interface AdminDao extends BaseDao<Admin, Integer>{  
  8.   
  9.     // 登陆  
  10.     Admin login(Admin admin);  
  11. }  
5. 数据库操作接口实现类   BaseDaoImpl.java   和  AdminDaoImpl.java

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.yfapp.platform.dao.impl;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6.   
  7. import com.yfapp.platform.dao.BaseDao;  
  8. import com.yfapp.platform.dao.template.DbUtilsTemplate;  
  9.   
  10.   
  11. public class BaseDaoImpl<PO,ID extends Serializable> implements BaseDao<PO,ID>  
  12. {       //这个是之前说的数据库操作帮助类,使用注解的方式,此变量在spring-application.xml中注入值。  
  13.     @Autowired  
  14.     protected DbUtilsTemplate dbUtilsTemplate;  
  15. }  
[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.yfapp.platform.dao.impl;  
  2.   
  3.   
  4. import org.springframework.stereotype.Repository;  
  5.   
  6. import com.yfapp.platform.dao.AdminDao;  
  7. import com.yfapp.platform.entity.Admin;  
  8.   
  9. @Repository  
  10. public class AdminDaoImpl extends BaseDaoImpl<Admin, Integer> implements AdminDao {  
  11.     /**  
  12.      * 管理员登陆  
  13.      */  
  14.     public Admin login(Admin admin) {  
  15.         String sql="select adminCode,adminPwd,loginTime from yf_admin where adminCode=? and adminPwd=?";  
  16.         Object[] params = { admin.getAdminCode(),admin.getAdminPwd() };  
  17.         Admin ad = dbUtilsTemplate.queryFirst(Admin.class, sql, params);  
  18.         return ad;  
  19.     }  
  20. }  

6。我的测试数据库表结构,使用的是SqlServer:


7.登陆成功要跳转的页面:indexhome.jsp

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <%@page import="com.yfapp.platform.entity.Admin"%>  
  2. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  3.     pageEncoding="UTF-8"%>  
  4. <%  
  5.     String path = request.getContextPath();  
  6.     String basePath = request.getScheme() + "://"  
  7.             + request.getServerName() + ":" + request.getServerPort()  
  8.             + path + "/";  
  9.   
  10.     Admin admin = (Admin) request.getSession().getAttribute("admin");  
  11. %>  
  12. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">  
  13. <html xmlns="http://www.w3.org/1999/xhtml">  
  14. <head>  
  15. <base href="<%=basePath%>">  
  16. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  17. </head>  
  18. <body>  
  19.     欢迎您:<%=admin.getAdminCode()%>|上次登录时间:<%=admin.getLoginTime()%>  
  20.     |今天是:  
  21.     <span id="webjx"><script>  
  22.         setInterval(  
  23.                 "webjx.innerHTML=new Date().toLocaleString()+' 星期'+'日一二三四五六'.charAt(new Date().getDay());",  
  24.                 1000);  
  25.     </script> </span>  
  26. </body>  
  27. </html>  

8.重新运行项目:

测试结果:

在浏览器中访问 http://localhost:8080/Springmvc/ 


点击登陆:



完了!

源码下载:http://download.youkuaiyun.com/detail/u010469432/6786687

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值