永州做网站费用,个人建站,网络运维工程师周报,开放平台如何赚钱在上一篇文章中#xff0c;我已经向您展示了如何设置基本的Spring 3 MVC Web应用程序 。 重复使用该项目设置作为模板#xff0c;我将向您展示如何增强它以与JDBC一起使用。 有了它#xff0c;您可以存储和检索数据库中的数据。 我们将通过Spring添加一个新的控制器和一个数… 在上一篇文章中我已经向您展示了如何设置基本的Spring 3 MVC Web应用程序 。 重复使用该项目设置作为模板我将向您展示如何增强它以与JDBC一起使用。 有了它您可以存储和检索数据库中的数据。 我们将通过Spring添加一个新的控制器和一个数据服务以便您可以看到Spring注入和注释配置如何协同工作。 与完整的ORM例如Hibernate相比基于JDBC的直接应用程序易于安装。 您无需担心AOPTranactionManager实体映射和其他配置的完整阵列。 在JDK的java.jdbc API java.jdbc Spring附带了spring-jdbc模块该模块可以通过其众所周知的JdbcTemplate类有效地引导您。 让我们探讨如何将其设置并作为Web应用程序运行。 入门和项目设置 出于演示目的我将使用H2Database的内存版本作为JDBC存储。 使用和设置都很简单。 而且如果您决定使用他们的基于FILE或TCP的数据库则只需重新设置数据源然后您就可以继续探索更多内容。 我们将从向您现有的spring-web-annotation/pom.xml文件添加新的依赖关系开始。 dependencygroupIdcom.h2database/groupIdartifactIdh2/artifactIdversion1.3.163/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-jdbc/artifactIdversion3.2.4.RELEASE/version/dependency 这样您将可以访问Spring模块类进行配置。 在现有项目中找到先前的src/main/java/springweb/WebApp.java文件并在下面添加新内容 package springweb;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;import javax.sql.DataSource;public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer {Overrideprotected Class?[] getRootConfigClasses() {return new Class?[]{ RootConfig.class };}Overrideprotected Class?[] getServletConfigClasses() {return new Class?[]{ WebAppConfig.class };}Overrideprotected String[] getServletMappings() {return new String[]{ / };}ConfigurationEnableWebMvcComponentScan(springweb.controller)public static class WebAppConfig {}ConfigurationComponentScan(springweb.data)public static class RootConfig {Beanpublic DataSource dataSource() {DataSource bean new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).addScript(classpath:schema.sql).build();return bean;}}
} 这里的新功能是我们引入了一个新的RootConfig类该类将在getRootConfigClasses()方法中加载。 RootConfig只是另一个基于Spring注释的配置它为bean定义创建了一个新的Spring上下文。 我们在那里创建了一个将运行内存数据库的bean。 构建器返回的bean还方便地实现了javax.sql.DataSource接口因此我们实际上可以将其注入任何数据服务中并立即开始使用它。 关于Spring嵌入式数据库构建器的另一件事很酷那就是它在启动过程中还可以运行任何SQL脚本 对于此演示我们将在src/main/resources/schema.sql文件中创建一个PING表。 由于Maven标准的源代码结构该文件对于Spring在CLASSPATH的根目录中是可见的。 CREATE TABLE PING (ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,TAG VARCHAR(1024) NOT NULL,TS DATETIME NOT NULL
); 这就是数据源设置。 现在请注意我没有将此数据源Spring bean定义添加到现有的WebAppConfig类中。 原因是我们希望一个单独的Spring上下文来配置所有服务级别的bean同时为所有与Spring MVC相关的bean例如ControllerURL映射等保留WebAppConfig 。 这有助于按Spring上下文的层次结构组织bean定义。 将RootConfig作为父层将WebAppConfig作为子层。 这也意味着在所有的服务组件RootConfig是自动可见WebAppConfig ; 为了注射等目的 还要注意使用分离的配置类我们可以指定两个不同的程序包来扫描服务组件 我们将springweb.controller用于WebAppConfig 将springweb.data用于RootConfig 。 这很重要它可以为您省去一些麻烦让Spring自动检测所有这些基于注释的组件。 创建数据服务 现在是时候使用JDBC了让我们在src/main/java/springweb/data/PingService.java文件下编写一个数据服务类。 package springweb.data;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;import javax.sql.DataSource;
import java.util.Date;
import java.util.List;
import java.util.Map;Repository
public class PingService {public static Log LOG LogFactory.getLog(PingService.class);private JdbcTemplate jdbcTemplate;Autowiredpublic void setDataSource(DataSource dataSource) {this.jdbcTemplate new JdbcTemplate(dataSource);}public void insert(String tag) {LOG.info(Inserting Ping tag: tag);jdbcTemplate.update(INSERT INTO PING(TAG, TS) VALUES(?, ?), tag, new Date());}public ListMapString, Object findAllPings() {return jdbcTemplate.queryForList(SELECT * FROM PING ORDER BY TS);}
} 这项服务非常简单。 我展示了两种方法一种用于插入一种用于检索所有Ping数据。 注意我使用Repository向Spring指示该类是执行数据服务的组件服务。 还要注意我们如何使用setter方法注入DataSource 然后将JdbcTemplate实例化为成员字段。 由此我们可以充分利用Spring JDBC API进行查询和更新。 关于日志的注释。 Spring核心本身使用Apache common-logging 因此我重用了该API甚至没有在我的pom.xml明确声明它们。 如果要从日志输出中查看更多详细信息则应将log4j logger实施添加到项目中并且它应会自动运行。 我将把它留作您的锻炼。 接下来我们将需要编写一个Controller来将数据带到Web UI页面。 我们将在src/main/java/springweb/controller/PingController.java文件下创建此文件。 package springweb.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springweb.data.PingService;import java.util.List;
import java.util.Map;Controller
public class PingController {Autowiredprivate PingService pingService;RequestMapping(value/ping/{tag}, producestext/plain)ResponseBodypublic String pingTag(PathVariable(tag) String tag) {pingService.insert(tag);return Ping tag tag has been inserted. ;}RequestMapping(value/pings, producestext/plain)ResponseBodypublic String pings() {ListMapString, Object result pingService.findAllPings();if (result.size() 0)return No record found.;StringBuilder sb new StringBuilder();for (MapString, Object row : result) {sb.append(Ping row).append(\n);}return sb.toString();}
} 在此控制器中您可以轻松地看到通过我们的数据服务通过注入获取并更新了Ping数据。 我已经声明并映射URL /ping/{tag}以将Ping数据插入数据库。 Spring具有这种非常好的简写语法注释映射可以从您的URL中提取参数。 我允许用户设置一个简单的标记词作为Ping记录插入以便我们可以识别数据库中的源。 另一个控制器处理程序/pings URL非常简单 它只是返回PING表中的所有记录。 出于演示目的我选择不使用JSP作为视图而是直接从Controller返回纯文本。 Spring通过在处理程序方法中添加ResponseBody来实现此ResponseBody 。 还要注意我们可以直接使用注释将内容类型指定为text/plain作为输出。 测试中 要查看上面的内容您只需要运行Maven tomcat插件即可。 上一篇文章向您显示了执行此操作的命令。 重新启动后您应该可以打开浏览器并使用这些URL进行测试。 http// localhost8081 / spring-web-annotation / ping / tester1 http// localhost8081 / spring-web-annotation / ping / tester2 http// localhost8081 / spring-web-annotation / ping / tester3 http// localhost8081 / spring-web-annotation / pings 编程编程 从这个简单的练习中您可以快速看到Spring MVC为您带来许多好处。 并在开发Web应用程序中带来很多乐趣。 根据设计原则Spring倾向于对开发人员友好可以提高生产力并且不会干扰您的环境。 这是我喜欢使用它的原因之一。 希望您喜欢本教程并自己进一步进行探索。 编程愉快 参考 A程序员杂志博客上的JCG合作伙伴 Zemian Deng在Web应用程序中使用Spring JDBC入门 。 翻译自: https://www.javacodegeeks.com/2013/10/getting-started-with-spring-jdbc-in-a-web-application.html