- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要做一些并非严格意义上的实体列表的报告。更多自由形式的查询,硬编码 SQL,以任意 JSON 形式返回。
我正在尝试为此使用 JdbcTemplate,并使用我在网上找到的代码(例如 here)来构建它。
这一切都在一个名为 ReportViewController 的类中。
我的代码(带有稍后相关的日志记录/调试问题):
private JdbcTemplate jdbcTemplate;
private DataSource dataSource;
private UUID uuid;
public ReportViewController() {
this.uuid = UUID.randomUUID();
}
public void setDataSource(DataSource dataSource) {
System.out.println("Setting data source");
this.dataSource = dataSource;
if (this.dataSource == null) {
System.out.println("failed to set my dataSource properly");
}
System.out.println("uuid: " + this.uuid);
}
@RequestMapping(value = "/report/{reportId}", method = RequestMethod.POST)
@ResponseBody
public String runNewUntypedSearch(@PathVariable Integer reportId, WebRequest request, HttpSession session) {
//View v = View.findView(reportId);
System.out.println("uuid: " + this.uuid);
if (this.dataSource == null) {
System.out.println("lost my dataSource somewhere along the way");
}
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
List<Map<String, Object>> l = null;
try {
l = this.jdbcTemplate.queryForList("select 1 as one");
JSONSerializer s = new JSONSerializer();
return s.serialize(l);
} catch (Exception e) {
System.out.println("querying failed -- " + e.toString());
return "";
}
}
我的问题是,尽管控制台指示它正在调用 setDataSource(),但当我进入 runNewUntypedSearch() 时,这些属性为空。
因此,我怀疑我正在与之交谈的对象存在犯规行为,我让这个 Controller 在其构造函数中创建一个 UUID,并将其作为其日志记录的一部分输出,如您在上文中所见。
控制台输出部分显示:
Setting data source
hash: bc679ef1-fbdc-4ef9-9457-dd79889f973e
...
hash: bbe2b03a-92ff-4517-add8-8d9ff6480cc8
lost my dataSource somewhere along the way
...然后 Spring 以“内部错误”和堆栈跟踪响应浏览器,该堆栈跟踪指示我正在尝试实例化我的 jdbcTemplate 的空指针。
这使我得出结论,无论对象被告知设置其数据源与作为 URL 映射方法挂接的实例不同。服务器运行的“真实”实例尚未调用 getDataSource()
。
可以吗?为什么这不起作用?
编辑:
web.xml(编辑删除我客户的名字):
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>myProjectName</display-name>
<description>Roo generated application</description>
<!-- Enable escaping of form submission contents -->
<context-param>
<param-name>defaultHtmlEscape</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:META-INF/spring/applicationContext*.xml</param-value>
</context-param>
<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>
<filter-name>HttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>HttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Handles Spring requests -->
<servlet>
<servlet-name>myProjectName</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/webmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myProjectName</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>90</session-timeout>
</session-config>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/uncaughtException</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/resourceNotFound</location>
</error-page>
</web-app>
applicationContext.xml(编辑以删除客户端名称和 Roo 生成的注释)
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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:jee="http://www.springframework.org/schema/jee" 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/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>
<context:spring-configured/>
<context:component-scan base-package="com.myProjectName">
<context:exclude-filter expression=".*_Roo_.*" type="regex"/>
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
<property name="driverClassName" value="${database.driverClassName}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="1800000"/>
<property name="numTestsPerEvictionRun" value="3"/>
<property name="minEvictableIdleTimeMillis" value="1800000"/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<bean class="org.springframework.mail.javamail.JavaMailSenderImpl" id="mailSender">
<property name="host" value="${email.host}"/>
</bean>
<bean class="org.springframework.mail.SimpleMailMessage" id="templateMessage">
<property name="from" value="${email.from}"/>
<property name="subject" value="${email.subject}"/>
</bean>
</beans>
webmvc-config.xml(编辑以删除我客户的名字):
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="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">
<!-- The controllers are autodetected POJOs labeled with the @Controller annotation. -->
<context:component-scan base-package="com.myProjectName" use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
<!-- Turns on support for mapping requests to Spring MVC @Controller methods
Also registers default Formatters and Validators for use across all @Controllers -->
<mvc:annotation-driven conversion-service="applicationConversionService"/>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources -->
<mvc:resources location="/, classpath:/META-INF/web-resources/" mapping="/resources/**"/>
<!-- Allows for mapping the DispatcherServlet to "/" by forwarding static resource requests to the container's default Servlet -->
<mvc:default-servlet-handler/>
<!-- register "global" interceptor beans to apply to all registered HandlerMappings -->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"/>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" p:paramName="lang"/>
</mvc:interceptors>
<!-- selects a static view for rendering without the need for an explicit controller -->
<mvc:view-controller path="/login"/>
<mvc:view-controller path="/admin" view-name="admin"/>
<mvc:view-controller path="/" view-name="index"/>
<mvc:view-controller path="/uncaughtException"/>
<mvc:view-controller path="/resourceNotFound"/>
<mvc:view-controller path="/dataAccessFailure"/>
<!-- Resolves localized messages*.properties and application.properties files in the application to allow for internationalization.
The messages*.properties files translate Roo generated messages which are part of the admin interface, the application.properties
resource bundle localizes all application specific messages such as entity names and menu items. -->
<bean class="org.springframework.context.support.ReloadableResourceBundleMessageSource" id="messageSource" p:basenames="WEB-INF/i18n/messages,WEB-INF/i18n/application" p:fallbackToSystemLocale="false"/>
<!-- store preferred language configuration in a cookie -->
<bean class="org.springframework.web.servlet.i18n.CookieLocaleResolver" id="localeResolver" p:cookieName="locale"/>
<!-- resolves localized <theme_name>.properties files in the classpath to allow for theme support -->
<bean class="org.springframework.ui.context.support.ResourceBundleThemeSource" id="themeSource"/>
<!-- store preferred theme configuration in a cookie -->
<bean class="org.springframework.web.servlet.theme.CookieThemeResolver" id="themeResolver" p:cookieName="theme" p:defaultThemeName="standard"/>
<!-- This bean resolves specific types of exceptions to corresponding logical - view names for error views.
The default behaviour of DispatcherServlet - is to propagate all exceptions to the servlet container:
this will happen - here with all other types of exceptions. -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" p:defaultErrorView="uncaughtException">
<property name="exceptionMappings">
<props>
<prop key=".DataAccessException">dataAccessFailure</prop>
<prop key=".NoSuchRequestHandlingMethodException">resourceNotFound</prop>
<prop key=".TypeMismatchException">resourceNotFound</prop>
<prop key=".MissingServletRequestParameterException">resourceNotFound</prop>
</props>
</property>
</bean>
<!-- allows for integration of file upload functionality -->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"/>
<bean class="com.mavenmanagement.web.ApplicationConversionServiceFactoryBean" id="applicationConversionService"/>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
</bean>
<bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer" id="tilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/layouts/layouts.xml</value>
<!-- Scan views directory for Tiles configurations -->
<value>/WEB-INF/views/**/views.xml</value>
</list>
</property>
</bean>
</beans>
我看到注释扫描上的过滤在 applicationContext 级别阻止了 @Controller
,并在 webmvc-config 级别启用了它们。所以我认为这并不能解释双重实例化。
最佳答案
@Tomasz Nurkiewicz 和@Inerdial 在问题评论中的提示让我想到了完全不同的方式,这更简单并且工作出色,但我还没有在任何地方看到它的记录。
在 applicationContext.xml 的底部,我正在实例化一个 JdbcTemplate 对象:
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
然后我只是将它@AutoWire 到我需要它的 Controller 中:
@Autowired
private JdbcTemplate jdbcTemplate;
Bob 的你叔叔,我现在可以与 this.jdbcTemplate 中的完全配置的模板对象对话。
为什么这个 Controller 类被实例化两次是因为我从 applicationContext.xml 启动它以尝试配置它的数据源。然后创建了由 @Controller
注释实例化的版本,但没有配置。这就是问题所在。
我还听从了评论中的其他建议,将此查询函数移动到模型类型类中,并从我的 View Controller 中调用它。是的,显然 View Controller 中的数据库交互是可憎的。
关于java - Spring Controller 中的 JDBCTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9036853/
应用程序上下文中的一些bean的依赖关系形成一个循环:当我使用时@Autowired私有(private) JdbcTemplate jdbcTemplate;不同类(class) 错误提示: ***
我做一个查询: jdbcTemplate.query(sqlQueryForGetNodes, new Object[]{treeId, versionId}, rs -> { NodeTy
关闭。这个问题需要多问focused 。目前不接受答案。 想要改进此问题吗?更新问题,使其仅关注一个问题 editing this post . 已关闭 3 年前。 Improve this ques
根据 Spring documentation ,Spring JdbcTemplate的使用步骤如下:
我做了这个简单的应用程序来连接到 MySQL 数据库,我收到了这个错误: org.springframework.jdbc.core.JdbcTemplate 在我的配置中 (com.kubamadr
我遵循了SpringBoot框架中的示例,该框架从这里开始,当我尝试添加Spring Bean时得到下一个错误。Pom.xml。我尝试插入到BD中,BD没有改变,应用程序本身可以工作,但没有连接数据库
我遵循了SpringBoot框架中的示例,该框架从这里开始,当我尝试添加Spring Bean时得到下一个错误。Pom.xml。我尝试插入到BD中,BD没有改变,应用程序本身可以工作,但没有连接数据库
我正在学习 Spring Boot 和 jdbcTemplate 的组合以进行一些基本的 crud 操作,并试图更好地理解我应该选择哪种更新方法。 我理解以下两种类方法(改编自 this post)将
如何使用行映射器向表中插入数据? 我正在尝试: Employee user1 = jtemplate.queryForObject("INSERT INTO employee(id, name,sal
我最近切换到 Spring Framework 而不是手动处理 JDBC,这主要是一个很好的过渡。但是,一个程序开始出现奇怪的问题:如果数据库速度很慢,则在调用 getJdbcTemplate().u
命令(Command)模式是指将请求封装成为一个对象,使发出请求和执行请求的责任分割开,方便将命令对象进行存储、传递、调用、增加与管理。 也就是将发送者、接收者和调用命令封装成独立的对象,来供客户端调
我有一个 spring 应用程序,它的主页会触发多个 ajax 调用,这些调用又从数据库中获取数据并返回。数据库已配置连接池,minPoolSize 为 50,maxPoolSize 为 100。 现
有人可以指出我以下 Spring Jdbc 模板代码中的任何错误吗? 当我点击删除时,记录没有被删除,也没有显示错误。 public void delete(String id) { logg
我正在使用 spring JDBCTemplate。 我有一个场景,其中需要传递到查询函数中的参数是条件/可选的。例如,我有以下代码: List result = jdbcTemplate.query
在项目中我在Hibernate和Spring jdbctemplate中是混合使用的。我添加了乐观锁定。 Hibernate 非常适合版本控制,但现在我必须转换所有这些 jdbctemplate 代码
我已经为我的INSERT查询建立了一个DAO。码: DAO public class EmployeeDao { JdbcTemplate template; public void
我有一个sql查询。 String sql = "SELECT ? FROM Users WHERE Lastname=?"; 我使用 JDBCTemplate 中的 queryForList 方法
我正在尝试将嵌套查询与 JdbcTemplate 一起使用,但发现了问题,在我看来,它不支持嵌套查询..我是对的吗?或者我需要改变什么? 所以,我调用 getJdbcTemplate().query
这个问题是几年前提出的,但答案对我来说不起作用。我已将建议的注释添加到配置和 dao 中。我确信模板实际上正在连接到数据库,因为当我的列太小时,我收到了适当的错误。更新调用正在执行单行插入,并且毫无异
JdbcTemplate 对象和 SimpleJdbcTemplate 之间有什么区别? 最佳答案 截至Spring 3.1 SimpleJdbcTemplate已弃用,SimpleJdbcTempl
我是一名优秀的程序员,十分优秀!