SpringMVC 数据库配置

10 篇文章 0 订阅
7 篇文章 0 订阅

数据库mysql,

1.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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.introduce.hua</groupId>
  <artifactId>introduce</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>introduce Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- springmvc start--> 
    <!-- spring-web -->
    <dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-web</artifactId>
	    <version>4.3.2.RELEASE</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-webmvc</artifactId>
	    <version>4.3.2.RELEASE</version>
	</dependency>
	 <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-core</artifactId>
    	<version>4.3.2.RELEASE</version>
    	<type>jar</type>
    	<scope>compile</scope>
    </dependency>
    
	<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-orm</artifactId>
	    <version>4.3.2.RELEASE</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
	<dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>jstl</artifactId>
	    <version>1.2</version>
	</dependency>
	<dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
      <scope>provided</scope>
    </dependency>
    <!-- springmvc end-->  
    
    <!-- Logging start-->  
	<dependency>  
	    <groupId>org.slf4j</groupId>  
	    <artifactId>slf4j-api</artifactId>  
	    <version>1.6.6</version>  
	</dependency>  
	<dependency>  
	    <groupId>org.slf4j</groupId>  
	    <artifactId>jcl-over-slf4j</artifactId>  
	    <version>1.6.6</version>  
	    <scope>runtime</scope>  
	    </dependency>  
	<dependency>  
	    <groupId>org.slf4j</groupId>  
	    <artifactId>slf4j-log4j12</artifactId>  
	    <version>1.6.6</version>  
	    <scope>runtime</scope>  
	</dependency>  
    <!-- Logging e n d-->  

	<!-- mysql驱动包  start-->  
    <dependency>  
        <groupId>mysql</groupId>  
        <artifactId>mysql-connector-java</artifactId>  
        <version>5.1.29</version>  
    </dependency>
    <!-- mysql驱动包  e n d-->
    
    <!-- BasicDataSource start-->
    <!-- <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.4</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.kenai.nbpwr</groupId>
            <artifactId>org-apache-commons-pool</artifactId>
            <version>1.4-201002241055</version>
            <type>nbm</type>
        </dependency> -->
        <dependency>
		    <groupId>org.apache.openejb</groupId>
		    <artifactId>commons-dbcp-all</artifactId>
		    <version>1.3-r699049</version>
		</dependency>
        
    <!-- datasource e n d -->
    
    <!-- javax.servlet.http start -->
	    <dependency>
		    <groupId>org.apache.tomcat</groupId>
		    <artifactId>servlet-api</artifactId>
		    <version>6.0.13</version>
		    <scope>provided</scope>
		</dependency>
     <!-- javax.servlet.http e n d -->
     
      <!--mybatis依赖 -->  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis</artifactId>  
            <version>3.2.1</version>  
        </dependency>  
  
        <!-- mybatis/spring包 -->  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis-spring</artifactId>  
            <version>1.2.0</version>  
        </dependency> 
  </dependencies>
  
  <build>
    <finalName>introduce</finalName>
  </build>
</project>


注意:刚刚只是配置了mysql,以上对mybatis的配置还没有成功。

2.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_2_5.xsd" 
	     version="2.5" >
	
	<!-- 区分项目名称,防止默认重名 -->
	<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>maven.example.root</param-value>
	</context-param>

	<!-- 配置加载log4j.xml文件路径 --> 
	<context-param> 
	  <param-name>log4jConfigLocation</param-name> 
	  <param-value>classpath:log4j/log4j.xml</param-value> 
	</context-param> 
	
	<!-- 配置log4j.xml变量 --> 
	<!-- <context-param> 
	  <param-name>rootLevel</param-name> 
	  <param-value>DEBUG</param-value> 
	</context-param> 
	
	<context-param> 
	  <param-name>loggingLevel</param-name> 
	  <param-value>INFO</param-value> 
	</context-param> -->
	
	<!-- Spring的log4j监听器 -->
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>

	<!-- 字符集 过滤器  -->
	<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>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- Spring view分发器 -->
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<!-- <welcome-file>/webpage/login/login.jsp</welcome-file> -->
		<welcome-file>/WEB-INF/login/login.jsp</welcome-file>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

</web-app>


3.dispatcher-servlet.xml


<?xml version="1.0" encoding="UTF-8"?>
<!--  配置注解的支持    -->
<beans xmlns="http://www.springframework.org/schema/beans" 
	   xmlns:aop="http://www.springframework.org/schema/aop" 
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:mvc="http://www.springframework.org/schema/mvc" 
	   xmlns:tx="http://www.springframework.org/schema/tx" 
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xsi:schemaLocation="http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.0.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<mvc:annotation-driven />
	<!--  启用自动扫描   -->
	<context:component-scan base-package="com.introduce" />

	<!-- mysql 配置 start -->
	<!-- 获取配置文件 -->  
    <bean id="config"  
       class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
       <property name="locations">  
           <list>  
              <value>classpath:db-config.properties</value>  
           </list>
       </property>  
    </bean>  
    <!-- 获取数据源 -->  
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
       <property name="driverClassName">  
           <value>${db.dirverClass}</value>  
       </property>  
       <property name="url">  
           <value>${db.url}</value>  
       </property>  
       <property name="username">  
           <value>${db.username}</value>  
       </property>  
       <property name="password">  
           <value>${db.password}</value>  
       </property>  
    </bean>  
	<!-- mysql 配置 e n d -->
	
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">    
		<property name="dataSource" ref="dataSource"/>    
    </bean> 

	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/webpage/views/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>
4.login.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>登录画面</title>
</head>
<body>
	<form id="loginForm" action="login.do">
		用户名:<input id="userId" name="userId" type="text"/>
		密    码:<input id="password" name="password" type="text">
		<input type="submit" value="登录">
		<input type="reset" value="重置">
	</form>
</body>
</html>


5.LoginController.java

package com.introduce.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.introduce.Model.User;
import com.introduce.service.UserService;


/**
 * 登录用controller
 * @author hua
 *
 */
@Controller
public class LoginController{

	@Autowired
	@Qualifier("userService")
	private UserService userService;
	
	@RequestMapping(value="login.do")
	public ModelAndView login(HttpServletRequest request,HttpServletResponse response){
		
		System.out.println("check");
		// "userId" password check
		String userId = request.getParameter("userId");
		String password = request.getParameter("password");
		User user = userService.selectByUserId(userId);
		if(null == user){
			System.out.println("没有该用户名!");
			return new ModelAndView("success");
		}else{
			user = userService.selectUserByIdPwd(userId, password);
			if (null == user ){
				System.out.println("密码不正确!");
				return new ModelAndView("success");
			}
		}
		
		return new ModelAndView("success");
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	
}


以上是配置mysql的方式,下面接着配置mybatis

1.pom.xml

刚刚已经添加了mybatis的依赖。

2.mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>    
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"    
"http://mybatis.org/dtd/mybatis-3-config.dtd">    
<configuration> 
 <typeAliases>
     <typeAlias alias="User" type="com.introduce.Model.User" />
 </typeAliases>
</configuration>  

3.userMapper.xml

<?xml version="1.0" encoding="UTF-8"?>    
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"    
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.introduce.Dao.UserDao">  
<!-- mapper与dao对应 -->
<!--设置domain类和数据库中表的字段一一对应,注意数据库字段和domain类中的字段名称不致,此处一定要!-->  
    <resultMap id="ResultUser" type="com.introduce.Model.User">  
        <id column="id" property="id" jdbcType="CHAR" />  
        <result column="userId" property="userId" jdbcType="CHAR" />  
        <result column="password" property="password" jdbcType="CHAR" />   
    </resultMap>  
    <!-- 查询单条记录 -->  
    <select id="selectByUserId" parameterType="String" resultMap="ResultUser">  
        SELECT * FROM t_user WHERE userId = #{userId}  
    </select>
    
    <select id="selectUserByIdPwd" parameterType="String" resultMap="ResultUser">  
        select * from t_user where userId = #{userId}  and password = #{password} 
    </select> 
</mapper> 

4.dispatcher-servlet.xml

<!-- spring 查询所用
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">    
		<property name="dataSource" ref="dataSource"/>    
    </bean>  -->
	
	<!-- mybatis  配置  start -->
	<!-- 自动扫描了所有的XxxxMapper.xml对应的mapper接口文件,这样就不用一个一个手动配置Mpper的映射了,只要Mapper接口类和Mapper映射文件对应起来就可以了。 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage"  value="com.introduce.Dao" />  
    </bean>  
  
    <!-- 配置Mybatis的文件 ,mapperLocations配置**Mapper.xml文件位置,configLocation配置mybatis-config文件位置-->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <property name="mapperLocations" value="classpath*:com/introduce/mapper/*.xml"/>    
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />  
        <!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model"   
            /> -->  
    </bean>  
	<!-- mybatis 配置   end -->

以下是这个的目录结构,mybatis配置后,daoImp就不需要的,dao与相对应的mapper.xml文件一一对应即可做到相应的查询语句



要在 SpringMVC 项目中配置 MySQL 数据库连接,需要在项目的配置文件中添加以下信息: 1. 在 pom.xml 文件中添加 MySQL 驱动依赖: ``` <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> ``` 2. 在 application.properties 文件中添加数据库连接信息: ``` spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ``` 上面的配置中,需要修改的是数据库名称(mydatabase)、用户名(root)和密码(password),这些信息应该根据实际情况进行修改。 3. 在 Spring 配置文件中配置数据源: ``` @Configuration public class DataSourceConfig { @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @Value("${spring.datasource.driver-class-name}") private String driverClassName; @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(driverClassName); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } } ``` 在上面的代码中,我们使用了 @Value 注解来获取 application.properties 文件中的属性值,并使用 DriverManagerDataSource 类来创建数据源。 以上就是 SpringMVC 项目配置 MySQL 数据库连接的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值