Spring+SpringMVC+JDBC实现登录
有一位程序员去相亲的时候,非常礼貌得说自己是一名程序员,并解释自己是做底层架构的,于是女方听到"底层"两个字,就一脸嫌弃:什么时候能够到中高级?
用久了框架,把原生都忘记了,本章从零开始,熟悉一遍JDBC实现增删改查
开发环境
- jdk 1.8
- Maven 3.6
- Spring、SpringMVC 4.3.18
- dbcp2
- jsp
- Idea
创建项目
创建项目时,我们选择传统的Maven项目结构
- 创建项目时不要选择任何模板,直接点Next
- 填写包名及项目名Next --> Finish
- 在main文件夹下创建webapp --> WEB-INF --> web.xml (如下图)
- 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>Demo-JDBC</display-name>
<!-- 欢迎页 -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
引入jar包,添加Spring、SpringMVC配置
- 在pom.xml中添加需要用到的jar包
<?xml version="1.0" encoding="UTF-8"?>
<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>com.wayne</groupId>
<artifactId>Demo-JDBC</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!-- 统一控制jar包版本 -->
<properties>
<servlet-version>3.1.0</servlet-version>
<mysql-version>5.1.38</mysql-version>
<commons-dbcp2-version>2.1.1</commons-dbcp2-version>
<dbutil-version>1.6</dbutil-version>
<spring-version>4.3.18.RELEASE</spring-version>
<jstl-version>1.2</jstl-version>
</properties>
<!-- jar包依赖 -->
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons-dbcp2-version}</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>${dbutil-version}</version>
</dependency>
<!-- spring-mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl-version}</version>
</dependency>
</dependencies>
<build>
<finalName>Demo-JDBC</finalName>
<plugins>
<!-- Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>80</port>
<path>/</path>
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
<!-- 编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
<!-- 资源仓库地址: 阿里云仓库 -->
<repositories>
<repository>
<id>public</id>
<name>aliyun nexus</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<!-- 插件仓库下载地址 -->
<pluginRepositories>
<pluginRepository>
<id>public</id>
<name>aliyun nexus</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
pom.xml
- 在resources下创建spring.xml,并添加一下内容
<!-- 自动扫描的包 -->
<context:component-scan base-package="com.wayne">
<!-- 扫描是忽略的注解 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
- 在resources下创建springmvc.xml,并添加一下内容
<!-- 开启自动扫描 -->
<context:component-scan base-package="com.wayne">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 开启基于注解的mvc -->
<mvc:annotation-driven/>
<!-- 开启静态资源访问 -->
<mvc:default-servlet-handler/>
<!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
- 此时项目结构如下
- 配置监听器及中央控制器,在web.xml中添加如下内容
<!-- 监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<!-- 字符过滤器 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置中央控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
- 至此,项目基础配置完成,我们顺便将项目所用各包创建完成,稍后介绍各类所起作用,此时项目结构如下
配置数据库连接
- 在resources下的config.properties中声明我们要访问的数据库
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/db_test
jdbc.username=你的数据库用户名
jdbc.password=你的数据库密码
- 在utils包下的ConnectionManager中配置数据库连接池
package com.wayne.utils;
import org.apache.commons.dbcp2.BasicDataSource;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;
/**
* 数据库连接池
* @author Wayne
* @date 2019/5/24
*/
public class ConnectionManager {
private static BasicDataSource dataSource = new BasicDataSource();
private static String DRIVER;
private static String URL;
private static String USERNAME;
private static String PASSWORD;
static {
try {
// 加载config.properties中配置的数据库连接信息
Properties prop = new Properties();
prop.load(ConnectionManager.class.getClassLoader().getResourceAsStream("config.properties"));
DRIVER = prop.getProperty("jdbc.driver");
URL = prop.getProperty("jdbc.url");
USERNAME = prop.getProperty("jdbc.username");
PASSWORD = prop.getProperty("jdbc.password");
} catch (IOException e) {
e.printStackTrace();
}
dataSource.setDriverClassName(DRIVER);
dataSource.setUrl(URL);
dataSource.setUsername(USERNAME);
dataSource.setPassword(PASSWORD);
// 配置数据库连接池参数
dataSource.setInitialSize(2);
dataSource.setMaxIdle(5);
dataSource.setMinIdle(1);
dataSource.setMaxWaitMillis(5000);
}
public static DataSource getConection() {
return dataSource;
}
}
- 在utils下的DBHelp编写CRUD工具类
package com.wayne.utils;
import com.wayne.exception.DataAccessException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import java.sql.SQLException;
/**
* CRUD工具类
* @author Wayne
* @date 2019/5/24
*/
public class DbHelp {
// 从连接池中获得连接
private static QueryRunner runner = new QueryRunner(ConnectionManager.getConection());
/**
* 新增
* @param sql 待执行的SQL
* @param rsh 结果集处理方式
* @param params SQL中的参数
* @param <T> 结果的类的详情信息
* @throws DataAccessException SQL执行错误时抛出的异常
*/
public static <T> T insert(String sql, ResultSetHandler<T> rsh, Object...params) throws DataAccessException {
T t = null;
try {
t = runner.insert(sql, rsh, params);
} catch (SQLException e) {
throw new DataAccessException("执行: " + sql + "异常");
}
return t;
}
/**
* @param sql 待执行的SQL
* @param params 结果集处理方式
* @throws DataAccessException SQL执行错误时抛出的异常
*/
public static void update(String sql, Object... params) throws DataAccessException {
try {
runner.update(sql, params);
} catch (SQLException e) {
throw new DataAccessException("执行: " + sql + "异常");
}
}
/**
* @param sql 待执行的SQL
* @param rsh 结果集处理方式
* @param params SQL中的参数
* @param <T> 结果的类的详情信息
* @throws DataAccessException SQL执行错误时抛出的异常
*/
public static <T> T query(String sql, ResultSetHandler<T> rsh, Object... params) throws DataAccessException {
T t = null;
try {
t = runner.query(sql, rsh, params);
} catch (SQLException e) {
throw new DataAccessException("执行: " + sql + "异常");
}
return t;
}
}
- 在exception包下自定义DataAccessException异常
package com.wayne.exception;
/**
* 自定义异常类,用于转化sql异常
* @author Wayne
* @date 2019/5/24
*/
public class DataAccessException extends RuntimeException {
private static final long serialVersionUID = 1L;
public DataAccessException() {
}
public DataAccessException(String message) {
super(message);
}
public DataAccessException(Throwable th) {
super(th);
}
public DataAccessException(String message, Throwable th) {
super(message, th);
}
}
- 至此,工具类配置完成,可以开始写页面和接口了,我们顺带将登录页一并创建,此时项目结构如下
业务代码
此时就可以开始写我们的登录流程了,文末会放出完整代码,此处就不再展示,只讲逻辑;
- 因为我们在web.xml中配置了index.jsp为欢迎页,所以当我们访问localhost:(端口号)时,会自动跳转到我们的index.jsp;
- 此种项目结构,WEB-INF包及其子包下的所有内容,是无法通过前端直接访问到的,所以我们在index.jsp做了一个向后台请求的动作,请求接口为/user/login.html,此接口通过请求转发,访问到login.jsp;
启动项目
因为我们在项目内部集成了tomcat7插件,所以在启动的时候我们不需要额外配置tomcat,只需要通过maven命令启动即可
- 选择Edit Configurations...
- 点击+,选择maven,在Command line输入 clean tomcat7:run,点击ok
- 点击绿色符号,就可以启动项目了
- 启动完成后,访问localhost,就可以看到我们的首页了
效果展示
预留占位
开发怎能不留扩展字段 (¬_¬)…