Spring+SpringMVC+JDBC实现登录
有一位程序员去相亲的时候,非常礼貌得说自己是一名程序员,并解释自己是做底层架构的,于是女方听到"底层"两个字,就一脸嫌弃:什么时候能够到中高级?
用久了框架,把原生都忘记了,本章从零开始,熟悉一遍JDBC实现增删改查
开发环境
jdk 1.8
Maven 3.6
Spring、SpringMVC 4.3.18
dbcp2
jsp
Idea
创建项目
创建项目时,我们选择传统的Maven项目结构
-
在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-JDBCdisplay-name> <welcome-file-list> <welcome-file>index.jspwelcome-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.0modelVersion> <groupId>com.waynegroupId> <artifactId>Demo-JDBCartifactId> <version>1.0-SNAPSHOTversion> <packaging>warpackaging> <properties> <servlet-version>3.1.0servlet-version> <mysql-version>5.1.38mysql-version> <commons-dbcp2-version>2.1.1commons-dbcp2-version> <dbutil-version>1.6dbutil-version> <spring-version>4.3.18.RELEASEspring-version> <jstl-version>1.2jstl-version> properties> <dependencies> <dependency> <groupId>javax.servletgroupId> <artifactId>javax.servlet-apiartifactId> <version>${servlet-version}version> <scope>providedscope> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>${mysql-version}version> dependency> <dependency> <groupId>org.apache.commonsgroupId> <artifactId>commons-dbcp2artifactId> <version>${commons-dbcp2-version}version> dependency> <dependency> <groupId>commons-dbutilsgroupId> <artifactId>commons-dbutilsartifactId> <version>${dbutil-version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webartifactId> <version>${spring-version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webmvcartifactId> <version>${spring-version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-contextartifactId> <version>${spring-version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-testartifactId> <version>${spring-version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-txartifactId> <version>${spring-version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-jdbcartifactId> <version>${spring-version}version> dependency> <dependency> <groupId>javax.servletgroupId> <artifactId>jstlartifactId> <version>${jstl-version}version> dependency> dependencies> <build> <finalName>Demo-JDBCfinalName> <plugins> <plugin> <groupId>org.apache.tomcat.mavengroupId> <artifactId>tomcat7-maven-pluginartifactId> <version>2.2version> <configuration> <port>80port> <path>/path> <uriEncoding>UTF-8uriEncoding> configuration> plugin> <plugin> <groupId>org.apache.maven.pluginsgroupId> <artifactId>maven-compiler-pluginartifactId> <version>3.1version> <configuration> <source>1.8source> <target>1.8target> <encoding>UTF-8encoding> configuration> plugin> plugins> build> <repositories> <repository> <id>publicid> <name>aliyun nexusname> <url>http://maven.aliyun.com/nexus/content/groups/public/url> <releases> <enabled>trueenabled> releases> repository> repositories> <pluginRepositories> <pluginRepository> <id>publicid> <name>aliyun nexusname> <url>http://maven.aliyun.com/nexus/content/groups/public/url> <releases> <enabled>trueenabled> releases> <snapshots> <enabled>falseenabled> snapshots> pluginRepository> pluginRepositories> project>
-
在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: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.ContextLoaderListenerlistener-class> listener> <context-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:spring.xmlparam-value> context-param> <filter> <filter-name>encodingFilterfilter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class> <init-param> <param-name>encodingparam-name> <param-value>UTF-8param-value> init-param> <init-param> <param-name>forceEncodingparam-name> <param-value>trueparam-value> init-param> filter> <filter-mapping> <filter-name>encodingFilterfilter-name> <url-pattern>/*url-pattern> filter-mapping> <servlet> <servlet-name>springmvcservlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class> <init-param> <param-name>contextConfigLocationparam-name> <param-value>classpath*:springmvc.xmlparam-value> init-param> <load-on-startup>1load-on-startup> servlet> <servlet-mapping> <servlet-name>springmvcservlet-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结果的类的详情信息 * @throws DataAccessException SQL执行错误时抛出的异常 */ public staticT insert(String sql, ResultSetHandler 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 结果的类的详情信息 * @throws DataAccessException SQL执行错误时抛出的异常 */ public staticT query(String sql, ResultSetHandler 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,就可以看到我们的首页了
源码下载
[Spring+SpringMVC+JDBC源码下载]
效果展示
预留占位
开发怎能不留扩展字段 (¬_¬)…