Cannot Install EventFilter on QComboBox - qt

I'm trying to install eventFilter on QComboBox but the function isn't getting triggered
Header:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
bool eventFilter(QObject *obj, QEvent *event);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
Source:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->comboBox->installEventFilter(ui->comboBox);
}
MainWindow::~MainWindow()
{
delete ui;
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
QComboBox* combo = qobject_cast<QComboBox*>(obj);
if(combo)
{
if(event->type() == QEvent::Wheel)
{
if(combo->focusPolicy() == Qt::WheelFocus)
{
event->accept();
return false;
}
else
{
event->ignore();
return true;
}
}
else if(event->type() == QEvent::FocusIn)
{
combo->setFocusPolicy(Qt::WheelFocus);
}
else if(event->type() == QEvent::FocusOut)
{
combo->setFocusPolicy(Qt::StrongFocus);
}
}
return QObject::eventFilter(obj, event);
}
UI:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QComboBox" name="comboBox">
<property name="geometry">
<rect>
<x>220</x>
<y>240</y>
<width>241</width>
<height>22</height>
</rect>
</property>
<item>
<property name="text">
<string>A</string>
</property>
</item>
<item>
<property name="text">
<string>B</string>
</property>
</item>
<item>
<property name="text">
<string>C</string>
</property>
</item>
<item>
<property name="text">
<string>D</string>
</property>
</item>
<item>
<property name="text">
<string>E</string>
</property>
</item>
<item>
<property name="text">
<string>F</string>
</property>
</item>
<item>
<property name="text">
<string>G</string>
</property>
</item>
<item>
<property name="text">
<string>H</string>
</property>
</item>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>21</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>

You need to pass this operator to installEventFilter
ui->comboBox->installEventFilter(this);
and use virtual and override keyword for eventFilter function
virtual bool eventFilter(...) override;

Related

How to configure the spring-servlet.xml to correct the Injection failure on the Spring-MVC 3.0 project?

I am working on a Spring MVC 3.0 project and have just used #Autowired in my code, but I got the below error message on the Console window:
严重: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.maskkk.service.UserService com.maskkk.controller.LoginController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.maskkk.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1238)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1151)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1038)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5027)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5337)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
The logincontroller is to check people to login into the website.
Below is its code:
package com.maskkk.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.maskkk.model.Login;
import com.maskkk.model.User;
import com.maskkk.service.UserService;
#Controller
public class LoginController {
#Autowired
UserService userService;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView showLogin(HttpServletRequest request,
HttpServletResponse response) {
ModelAndView mav = new ModelAndView("login");
mav.addObject("login", new Login());
return mav;
}
#RequestMapping(value = "/loginProcess", method = RequestMethod.POST)
public ModelAndView loginProcess(HttpServletRequest request,
HttpServletResponse response,
#ModelAttribute("login") Login login) {
ModelAndView mav = null;
User user = userService.validateUser(login);
if (null != user) {
mav = new ModelAndView("welcome");
mav.addObject("firstname", user.getFirstname());
} else {
mav = new ModelAndView("login");
mav.addObject("message", "Username or Password is wrong!!");
}
return mav;
}
}
Since:
#Autowired
UserService userService;
The userservice is below:
package com.maskkk.service;
import com.maskkk.model.Login;
import com.maskkk.model.User;
public interface UserService {
void register(User user);
User validateUser(Login login);
}
My project structure is like above:
And my spring-servlet.xml is below:
<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: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">
<!-- 下面是配置扫描包的位置,包名为com.maskkk,也就是说,我们的试图解析器应该放在
com.maskkk包下. -->
<!-- import resource="classpath:com/config/user-beans.xml" /> -->
<context:component-scan base-package="com.maskkk.*" />
<context:annotation-config />
<!-- <context:component-scan base-package="com.maskkk.*" /> -->
<!-- 自动扫描(自动注入) -->
<!-- <context:component-scan base-
package="com.maskkk.controller.LoginController" />
<context:component-scan base-package="com.maskkk.service.UserService" /> -->
<mvc:resources mapping="/image/**" location="/image/" />
<bean class="org.springframework.web.servlet.mvc.annotation
.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.annotation
.DefaultAnnotationHandlerMapping" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀,我们的视图文件应该放到/WEB-INF/view/目录下,这里我们需要在WEB-INF下面
创建view文件夹 -->
<property name="prefix" value="/" />
<!-- 设置后缀为.jsp -->
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<bean id="multipartResolver"class="org.springframework.web
.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="209715200" />
<property name="defaultEncoding" value="UTF-8" />
<property name="resolveLazily" value="true" />
</bean>
<bean class="org.springframework.beans.factory
.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean class="org.springframework.web.servlet.mvc
.method.annotation.RequestMappingHandlerMapping">
</bean>
<bean class="org.springframework.web.servlet.mvc
.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json
.MappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>
<!-- 加入json支持 -->
<mvc:annotation-driven />
<!-- 处理请求response返回值,如下配置能正确返回字符串型返回值,如返回值为对
象,则自动转为json -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter
.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json; charset=UTF-8</value>
<value>text/html; charset=UTF-8</value>
</list>
</property>
</bean>
<bean id="mappingStringHttpMessageConverter"
class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean id="handleAdapter"
class="org.springframework.web.servlet.mvc
.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器
-->
</list>
</property>
</bean>
<!-- 设置返回字符串编码 -->
<bean class="org.springframework.web
.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<!--json视图拦截器,读取到#ResponseBody的时候去配置它-->
<ref bean="mappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
</beans>
So, What is wrong with my spring-servlet.xml file?
Any sugestions would be very helpful!

I don't need shiro.ini on spring webmvc

I'm developing a web application based on spring webmvc and apache shiro.
I made JpaRealm class which extends AuthorizingRealm, and it is instantiated by Spring context in order to inject dependency (UserService).
I don't need shiro.ini file because all of configurations are overriden by spring-context.xml.
If I delete it, the default listener compains because the default IniWebEnvironment always tries to load shiro.ini.
I'd like to ask the custom listener which load the custom environment extends DefaultWebEnvironment.
I copied someone's code from the Internet, but I failed.
public class JpaRealm extends AuthorizingRealm {
private static final Logger logger = LoggerFactory.getLogger(JpaRealm.class);
#Autowired
private UserService userService;
public JpaRealm() {
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
credentialsMatcher.setHashAlgorithmName(Sha256Hash.ALGORITHM_NAME);
setCredentialsMatcher(credentialsMatcher);
}
#Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
SimpleAuthenticationInfo info = null;
UsernamePasswordToken userPassToken = (UsernamePasswordToken) token;
String username = userPassToken.getUsername();
if (username != null && !username.equals("")) {
User user = userService.findByUsername(username);
logger.debug("doGetAuthenticationInfo invoked");
logger.debug("username: " + username);
info = new SimpleAuthenticationInfo(username, user.getPassword(), getName());
}
return info;
}
#Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
AuthorizationInfo authorizationInfo = null;
if (principals != null) {
logger.debug("doGetAuthorizationInfo invoked");
String username = (String) getAvailablePrincipal(principals);
return userService.getAuthorizationInfoByUser(username);
}
return authorizationInfo;
}
}
security-context.xml
<bean id="jpaRealm" class="foo.bar.JpaRealm" />
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="jpaRealm" />
</bean>
<bean id="verboseFormAuthenticationFilter"
class="foo.bar.VerboseFormAuthenticationFilter">
<property name="loginUrl" value="/login.jsp" />
<property name="successUrl" value="/" />
<property name="usernameParam" value="username" />
<property name="passwordParam" value="password" />
<property name="rememberMeParam" value="rememberMe" />
<property name="failureKeyAttribute" value="yamShiroLoginFailure" />
</bean>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="unauthorizedUrl" value="/unauthorized.jsp" />
<property name="filters">
<map>
<entry key="authc" value-ref="verboseFormAuthenticationFilter" />
</map>
</property>
<property name="filterChainDefinitions">
<value>
/**=authc
</value>
</property>
</bean>
I found my answer from the manual, and it works fine.
shiroEnvironmentClass can be replaced as a context-param as follows:
web.xml
<listener>
<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>
<!-- IniWebEnvironment is not requied because shiro.ini is not necessary. -->
<context-param>
<param-name>shiroEnvironmentClass</param-name>
<param-value>org.apache.shiro.web.env.DefaultWebEnvironment</param-value>
</context-param>

Who implemente the spring BindingResult?

I'm new to Spring MVC and I'm trying to understand the following code
package com.companyname.springapp.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.companyname.springapp.service.PriceIncrease;
import com.companyname.springapp.service.ProductManager;
#Controller
#RequestMapping(value="/priceincrease.htm")
public class PriceIncreaseFormController {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
#Autowired
private ProductManager productManager;
#RequestMapping(method = RequestMethod.POST)
public String onSubmit(#Valid PriceIncrease priceIncrease, BindingResult result)
{
if (result.hasErrors()) {
return "priceincrease";
}
int increase = priceIncrease.getPercentage();
logger.info("Increasing prices by " + increase + "%.");
productManager.increasePrice(increase);
return "redirect:/hello.htm";
}
#RequestMapping(method = RequestMethod.GET)
protected PriceIncrease formBackingObject(HttpServletRequest request) throws ServletException {
PriceIncrease priceIncrease = new PriceIncrease();
priceIncrease.setPercentage(15);
return priceIncrease;
}
public void setProductManager(ProductManager productManager) {
this.productManager = productManager;
}
public ProductManager getProductManager() {
return productManager;
}
}
As far as I know the BindingResult is an interface and the onSubmit method receives a BindingResult object. What I don't understand is: Who implemented this interface to create the object and where is that implementation?
Here is the servlet xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean id="productManager" class="com.companyname.springapp.service.SimpleProductManager">
<property name="products">
<list>
<ref bean="product1"/>
<ref bean="product2"/>
<ref bean="product3"/>
</list>
</property>
</bean>
<bean id="product1" class="com.companyname.springapp.domain.Product">
<property name="description" value="Lamp"/>
<property name="price" value="5.75"/>
</bean>
<bean id="product2" class="com.companyname.springapp.domain.Product">
<property name="description" value="Table"/>
<property name="price" value="75.25"/>
</bean>
<bean id="product3" class="com.companyname.springapp.domain.Product">
<property name="description" value="Chair"/>
<property name="price" value="22.79"/>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="com.companyname.springapp.web" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
I don't if this helps but I'm using Tomcat 7.0 and whole code is in here: http://docs.spring.io/docs/Spring-MVC-step-by-step/
Who implemented this interface to create the object and where is that implementation?
Implemented in the Spring framework and instantiated by your context.
In the above example BeanPropertyBindingResult.class is exact implementation of BindingResult instantiated
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/BeanPropertyBindingResult.html

Bootstrap with Spring MVC

I am trying to use bootstrap to style my app but I won't apply the styles. This is what is in my JSP
<c:url value="css/bootstrap.min.css" var="cssBoostrap" />
<link href="${cssBootstrap}" rel="stylesheet">
This css folder is on the same level as WEB-INF not inside of it but it won't work if it is inside of it or even if the files are inside of the view dir. What could the problem possibly be? I no longer get the no mapping error when adding the mapping to my servlet.xml but yet it still doesn't see the file or I can assume it doesn't because no styling is applied, then I change it to link to the online hosted version and all my styles are applied correctly.
Servlet XML
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- Scans for annotated #Controllers in the classpath -->
<context:component-scan base-package="com.eaglecrk.recognition" />
<mvc:annotation-driven />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/system.properties</value>
</list>
</property>
</bean>
<!-- messageSource -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>file:${external.property.directory}PMS.EOTM.SendEmail</value>
</list>
</property>
</bean>
<!-- dataSource -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>
</props>
</property>
<property name="packagesToScan" value="com.eaglecrk.recognition.persistence" />
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value = "${email.host}" />
<property name="port" value="${email.port}" />
<property name="username" value="${email.username}" />
<property name="password" value="${email.password}" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.ssl.trust">${email.mail.smtp.ssl.trust}</prop>
<prop key="mail.smtp.starttls.enable">${email.mail.smtp.starttls.enable}</prop>
<prop key="mail.smtp.auth">${email.mail.smtp.auth}</prop>
</props>
</property>
</bean>
</beans>
Controller
package com.eaglecrk.recognition.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.eaglecrk.recognition.dao.award.AwardDao;
import com.eaglecrk.recognition.dao.award.AwardDaoInterface;
import com.eaglecrk.recognition.dao.employee.EmployeeDaoInterface;
import com.eaglecrk.recognition.model.AwardTypeModel;
import com.eaglecrk.recognition.model.EmployeeModel;
import com.eaglecrk.recognition.persistence.AwardNomination;
import com.eaglecrk.recognition.persistence.AwardType;
import com.eaglecrk.recognition.persistence.Employee;
import com.eaglecrk.recognition.util.Functions;
import com.eaglecrk.recognition.util.SpringMailSender;
#Controller
public class TestController extends BaseController implements MessageSourceAware {
private static final Logger LOG = LogManager
.getLogger(TestController.class);
#Autowired
private EmployeeDaoInterface employeeDao;
#Autowired
private AwardDaoInterface awardDao;
#Autowired
private SpringMailSender springMailSender;
/**
* #param request
* #return (ModelAndView) object
*/
#RequestMapping(value = "/test", method = RequestMethod.GET)
public ModelAndView test() {
try {
LOG.info("Entered the controller");
springMailSender.sendMail();
} catch (Exception e) {
e.printStackTrace();
}
ModelAndView mav = new ModelAndView();
ArrayList<String> names = new ArrayList<String>();
List<Employee> employees = employeeDao.findAll();
Collections.sort(employees, Functions.lastNameOrder);
for (Employee employee : employees) {
EmployeeModel model = new EmployeeModel(employee);
names.add(model.getLocation().getLocationId() + " " +
model.getFirstName() + " " + model.getLastName());
}
mav.addObject("names", names);
mav.setViewName("test");
return mav;
}
#RequestMapping(value = "/test", method = RequestMethod.POST)
public void addNomination(
#ModelAttribute("SpringWeb") AwardNomination nomination,
ModelMap model) {
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login() {
ModelAndView mav = new ModelAndView();
mav.setViewName("login");
return mav;
}
#RequestMapping(value="/newAwardType", method=RequestMethod.GET)
public ModelAndView addAward() {
ModelAndView mav = new ModelAndView();
ArrayList<AwardTypeModel> models = new ArrayList<AwardTypeModel>();
try{
AwardTypeModel newAwardTypeModel = new AwardTypeModel();
newAwardTypeModel.setActive(false);
newAwardTypeModel.setName("AwardTypeModel.name");
newAwardTypeModel.setDescription("AwardTypeModel.description");
// newAwardTypeModel.setId(123456);
newAwardTypeModel.setCreated(new Date());
newAwardTypeModel.setModified(new Date());
models.add(newAwardTypeModel);
} catch (Exception e){
e.printStackTrace();
}
mav.addObject("awardTypes", models);
mav.addObject("model", new AwardTypeModel());
mav.setViewName("addAward");
return mav;
}
#RequestMapping(value="/addAward", method=RequestMethod.POST)
public String addAwardForm(#ModelAttribute("model") AwardTypeModel model, BindingResult result){
model.setCreated(new Date());
model.setModified(new Date());
AwardType dbo = (AwardType) model.convertToDb();
awardDao.save(dbo);
return "redirect:/test";
}
#Override
public void setMessageSource(MessageSource messageSource) {
// TODO Auto-generated method stub
}
}
Create one folder by name resources at same level as WEB-INF as shown below:
WebApp-|
| - resources -|
| |-styles-|
| | |-bootstrap.min.css
| |
| |-javascript-|
| |-example.js
|
| - WEB-INF
Include the following line in your servlet xml:
<mvc:resources mapping="/resources/**" location="/resources/"/>
Access these resources in your jsp as:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<link href="<c:url value="/resources/styles/bootstrap.min.css" />" rel="stylesheet">
<script src="<c:url value="/resources/javascript/example.js" />"></script>
....
You should declare in your dispatcher servlet config the location of you resources (e.g js, css, img etc.) :
<mvc:resources mapping="/public/**" location="/public/" />
location contains the path to your resources folder. mapping is how you call your resources in your jsp.
Don't forget to declare your mvc namespace in dispatcher config.
Following Prasads Answer above if you need Java based configuration for the same use -
#Configuration
#ComponentScan("com.eaglecrk.recognition")
#EnableWebMvc
public class SpringConfig extends WebMvcConfigurerAdapter {
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Also if you are using xml based configuration don't forget <mvc:default-servlet-handler/>

Spring 3, Hibernate 4 AutoWired sessionFactory with Generic DAO

Using Spring MVC 3 & Hibernate 4 I'm getting:
java.lang.NullPointerException
com.daniel.rr.dao.common.DAOImpl.getSession(DAOImpl.java:22)
com.daniel.rr.dao.common.DAOImpl.save(DAOImpl.java:27)
com.daniel.rr.controller.HelloController.printWelcome(HelloController.java:30)
This is the relevant spring configuration:
<context:annotation-config />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan">
<list>
<value>com.daniel.rr.model</value>
<value>com.daniel.rr.dao</value>
<value>com.daniel.rr.dao.common</value>
<value>com.daniel.rr.controller</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/rr" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Generic DAO:
public interface DAO<T> {
T save(T t);
void delete(T t);
}
#Transactional
public abstract class DAOImpl<T> implements DAO<T> {
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession() {
return sessionFactory.getCurrentSession();
}
#Override
public T save(T t) {
getSession().persist(t);
return t;
}
#Override
public void delete(T t) {
getSession().delete(t);
}
}
AccountDAO:
public class AccountDAO extends DAOImpl<Account> implements DAO<Account> {
}
MVC Controller:
public class HelloController {
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
//System.out.println("is null? " + sessionFactory);
AccountDAO dao = new AccountDAO();
Account account = new Account();
account.setUsername("hello");
account.setPassword("test");
dao.save(account);
model.addAttribute("message", "Hello world!");
return "hello";
}
}
I've searched thru StackOverflow and Google but I cannot find anything that helps.
I've tried using a Transaction on DAOImpl.save(T t) but it still has the same issue.
public T save(T t) {
Transaction tr = getSession().getTransaction();
tr.begin();
getSession().persist(t);
tr.commit();
return t;
}
Annotations are not inherited.
Add the transactional annotation to the concrete dao, not the abstract class.
You might like this too

Resources