天天看点

SpringMVC中数据库链接配置

从昨天开始一直在纠结数据库链接的问题,现在可以说才从库里面查出数据。这种感觉还是希望和大家分享一下

首先我们来看看我用ecplise创建项目的目录结构:

SpringMVC中数据库链接配置

上面是我的目录结构,和数据库链接的都放在了applicantContent.xml这个配置文件里面了。在最开始学习SpringMVC的时候配置文件的位置真的是一个比较困扰的问题。而且如果你是自学的话找,往往在网上看一篇文章然后跟着做发现在自己本地就是不行,有的时候尽管从望山直接拉下一个别人布置好的SpringMVC你兴致冲冲的导入到ecplise中,可是还是不行,伴随着各种无奈,并不是说人家的项目不行,各种原因吧,可能你本地ecplise配置和人家的不一样都有。好了,不扯这些,我们首先来看看配置文件,首先我们在一开始创建web工程的时候自带的 是一个web.xml,所有的开始我们都从web.xml中进行,而且我还是注意的是web.xml你需要审批,配置什么,别看到网上的代码全部都复制过来。配置文件其实是你的代码里面需要读取的,你需要实现怎样的功能,就配置什么,然后引入相关的jar

那么我们这个地方需实现的是配置jdbc的配置,我们来看看web.xml应该怎样来进行配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  id="WebApp_ID" version="3.1">
  <display-name>Shopping</display-name>
  <!-- 过滤器编码设置 -->
  <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>
  <!-- 信息转发器 -->
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <listener>
  <listener-class>
  org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext.xml</param-value>
  </context-param>
  <!-- 允许访问静态资源 -->
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
  <!-- 欢迎页 -->
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <!-- 配置log4j配置文件路径 -->
  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>log4j.properties</param-value>
  </context-param>
  <!-- 60s 检测日志配置 文件变化 -->
  <context-param>
    <param-name>log4jRefreshInterval</param-name>
    <param-value>60000</param-value>
  </context-param>
  <!-- 配置Log4j监听器 -->
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
</web-app>      

上面是我的web.xml的配置,其中有一段忘记了注释,也是我们这地方比较重要的,那就是

<listener-class>
    org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:applicationContext.xml</param-value>
    </context-param>      

为什么说这一段重要,因为我们从在SpringMVC中许多的bean都是配置在applicantContent.xml中,当然链接数据库也是一样配置到了这个文件,其实这一段为加载配置文件applicantContent.xml只有在加载之后我们在java代码中才能找到这个文件,

从上面的目录中我们可以看到的是还有一个配置文件SpringMVC-Servlet.xml这个配置文件,其实这个是用来控制我们的访问,作为web项目接口不可避免的,为了很好的访问,我们用这个配置文件来进行控制访问的权限,或者对url进行转发。也就是我们在上面注释的信息转发器,那么我们拿出来这个SpringMVC-servlet.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:p="http://www.springframework.org/schema/p"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="
  http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
  http://www.springframework.org/schema/util
  http://www.springframework.org/schema/util/spring-util-4.2.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-4.2.xsd
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

  <!-- 解决中文乱码 -->
  <mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
      <bean class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes">
          <list>
            <value>text/plain;charset=UTF-8</value>
            <value>text/html;charset=UTF-8</value>
            <value>application/json;charset=UTF-8</value>
          </list>
        </property>
      </bean>
    </mvc:message-converters>
  </mvc:annotation-driven>
  <!-- 支持返回json(避免IE在ajax请求时,返回json出现下载 ) -->
  <bean id="utf8Charset" class="java.nio.charset.Charset"
    factory-method="forName">
    <constructor-arg value="UTF-8" />
  </bean>
  <bean
    class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
      <list>
        <bean
          class="org.springframework.http.converter.StringHttpMessageConverter">
          <constructor-arg ref="utf8Charset" />
        </bean>
        <bean id="mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
          <property name="supportedMediaTypes">
            <list>
              <value>text/plain;charset=UTF-8</value>
              <value>application/json;charset=UTF-8</value>
            </list>
          </property>
        </bean>
      </list>
    </property>
  </bean>
  <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter" />
  <bean
    class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
  <bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/html/" />
  </bean>
  <!-- 静态资源处理 -->
  <mvc:default-servlet-handler />
  <mvc:annotation-driven />
  <context:component-scan base-package="com.wdg.controller"></context:component-scan>
</beans>      

对于这个文件的介绍我们就一一多说了,网上有很多详细的介绍,我们来继续看applicantContent.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:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:aop="http://www.springframework.org/schema/aop" 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
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop.xsd">

   <!-- <context:component-scan base-package="com.spring.controller" /> -->
   <!--view -->
   <!-- 获取配置文件 -->
   <bean id="config"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="locations">
         <list>
            <value>classpath*:jdbc.properties</value>
         </list>
      </property>
   </bean>
   <!-- 获取数据源 -->
   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
      destroy-method="close">
      <property name="driverClassName" value="com.mysql.jdbc.Driver" />
      <property name="url" value="jdbc:mysql://localhost:3306/shopping?characterEncoding=utf8" />
      <property name="username" value="root" />
      <property name="password" value="11111" />
   </bean>


   <bean id="userDao" class="com.wdg.dao.UserDao">
      <property name="dataSource" ref="dataSource"></property>
   </bean>

   <bean
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/view/" />
      <property name="suffix" value=".html" />
   </bean>
</beans>      

这个里面配置了数据源,当然在这个过程中会缺少包之类的ClassNotFound,

SpringMVC中数据库链接配置
package com.wdg.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class UserDao extends JdbcDaoSupport {
  @SuppressWarnings("rawtypes")
  public  void getUserName(){
    String sql="select * from userinfo";
    List<Map> result = super.getJdbcTemplate().query(sql, new RowMapper<Map>() {  
      @Override  
          public Map<String,String> mapRow(ResultSet rs, int rowNum) throws SQLException {  
              Map<String,String> row = new HashMap<String, String>();  
              row.put("rowguid", rs.getString("rowguid"));  
              return row;  
      }}); 
      System.out.println(result.toString());
  }
  public UserDao() {
    super();
  }
  
}