I am developing a spring boot application, I am trying to use XmlViewResolver to view the pdf from predefined template using itext. Successfully getting the jsp page when I access the "/welcome" and "/invoice", but failed when I try "/pdf".
Please let me know what's wrong. Why the pdf bean is not working as expected?
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
There was an unexpected error (type=Not Found, status=404).
/WEB-INF/jsp/pdf.jsp
Below are the codes
#Controller
public class MainController {
#RequestMapping("/welcome")
public String hello(Model model) {
model.addAttribute("msg", "XmlViewResolver Demo");
return "success";
}
#RequestMapping("/invoice")
public String getInvoiceInfo() {
return "invoice";
}
#RequestMapping("/pdf")
public String getPdfInfo() {
return "pdf";
}
}
JspConfig.java
#Component
public class JspConfig {
#Bean
public ViewResolver internalResourceViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/jsp/");
bean.setSuffix(".jsp");
bean.setOrder(2);
return bean;
}
}
XmlConfig.java
#Configuration
public class XmlConfig {
#Bean
public XmlViewResolver xmlViewResolver() {
XmlViewResolver resolver = new XmlViewResolver();
Resource resource = new ClassPathResource("xml/user-view.xml");
resolver.setLocation(resource);
resolver.setOrder(1);
return resolver;
}
}
user-view.xml
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="invoice" class="org.springframework.web.servlet.view.JstlView">
<property name="url" value="WEB-INF/template/invoice.jsp" />
</bean>
<bean id="pdf" class="com.example.config.PdfView">
<property name="url" value="WEB-INF/template/invoiceTemplate.pdf" />
</bean>
PdfView.java
import com.lowagie.text.pdf.PdfStamper;
public class PdfView extends AbstractPdfStamperView implements MessageSourceAware {
#Override
protected void mergePdfDocument(Map<String, Object> model, PdfStamper stamper, HttpServletRequest request, response) throws Exception {
stamper.setFormFlattening(true);
String customerName = (String) model.get("customerName");
stamper.getAcroFields().setField("name", customerName);
stamper.close();
}
}
Related
I have the following controller
#Controller
#RequestMapping("/room/{roomId:^(?!main.html$).*}")
public class Rooms {
#RequestMapping
public String index(#PathVariable(value = "roomId") String id) {
// do some stuff...
return "main.html";
}
}
I have a main.html file in my resource/static folder. I would like when a user goes to /room/{something} to do some processing, return the static main.html page I have.
Everything I try results in a page not found exception or
javax.servlet.ServletException: Circular view path [main.html]:
would dispatch back to the current handler URL
[/room/main.html] again
what am I missing to allow this to work?
Thanks for the help
If you are doing configuration in class for view resolver
#Bean
public UrlBasedViewResolver urlBasedViewResolver()
{
UrlBasedViewResolver res = new InternalResourceViewResolver();
res.setViewClass(JstlView.class);
res.setPrefix("/WEB-INF/");
res.setSuffix(".jsp");
return res;
}
If using xml
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/jsp/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
Also change your controller by below code
#RestController
#RequestMapping("/room/")
public class Rooms {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView index(#PathVariable(value = "roomId") String id) {
// do some stuff...
ModelAndView model = new ModelAndView();
model.setViewName("main");
return model;
}
}
When using Spring with Thymeleaf all my Cyrillic characters are shown as ????? on pages.
Using
#RequestMapping(value = "/login", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
as it was suggested here: https://stackoverflow.com/a/11866822/1479414 and here: https://stackoverflow.com/a/12023816/1479414 doesn't help.
How to solve this issue?
The answer can be found here:
Property characterEncoding should be explicitly set for templateResolver and ThymeleafViewResolver:
<bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
...
<property name="characterEncoding" value="UTF-8"/>
...
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
...
<property name="characterEncoding" value="UTF-8"/>
...
</bean>
working for me. java config
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.projectName.controller")
public class MVCConfig implements WebMvcConfigurer, ApplicationContextAware {
#Autowired
private ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws
BeansException {
this.applicationContext = applicationContext;
}
#Bean
public ViewResolver viewResolver(){
ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
thymeleafViewResolver.setTemplateEngine(templateEngine());
thymeleafViewResolver.setCharacterEncoding("UTF-8");
return thymeleafViewResolver;
}
#Bean
public TemplateEngine templateEngine(){
SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
springTemplateEngine.setEnableSpringELCompiler(true);
springTemplateEngine.setTemplateResolver(templateResolver());
return springTemplateEngine;
}
#Bean
public ITemplateResolver templateResolver(){
SpringResourceTemplateResolver springResourceTemplateResolver = new
SpringResourceTemplateResolver();
springResourceTemplateResolver.setApplicationContext(applicationContext);
springResourceTemplateResolver.setPrefix("/WEB-INF/views/");
springResourceTemplateResolver.setTemplateMode(TemplateMode.HTML);
springResourceTemplateResolver.setSuffix(".html");
springResourceTemplateResolver.setCharacterEncoding("UTF-8");
return springResourceTemplateResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
}
in Config
public class SpringConfig implements WebMvcConfigurer {
private final ApplicationContext applicationContext;
#Autowired
public SpringConfig(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
#Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setCharacterEncoding("UTF-8");
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
registry.viewResolver(resolver);
}
}
In ServletInitializer
public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
return new Filter[] { filter };
}
}
If you have added <property name="characterEncoding" value="UTF-8"/> in the bean configuration for view resolver and still text are not shown in correct format then the problem is in the properties/resource_bundle files.
Try encoding UTF-8 or non-English characters with native2ascii tool. (its included in the java_home/bin folder.
In my case, I put below 2 lines in application.properties file
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
(Korean)Reference: https://blog.thjang.net/33
With Spring WebFlux, I've restricted the view resolver to use text/html; charset=UTF-8 as the only supported content type. I've used a custom WebFluxConfigurer for that (in Kotlin):
class CustomWebFluxConfigurer(
private val viewResolver: ThymeleafReactiveViewResolver
) : WebFluxConfigurer {
override fun configureViewResolvers(registry: ViewResolverRegistry) {
viewResolver.supportedMediaTypes =
listOf(MediaType.parseMediaType("text/html; charset=UTF-8"))
registry.viewResolver(viewResolver)
}
}
I think in thymeleaf html page you are using th:text with html element, th:text it just display normal text,
if you want use special charter with your thymeleaf html page so just need to change for example
th:utext="${yourcontroller_var}"
or
th:utext="#{properties_var}"
For example
<div th:utext="${user.name}"> Test! </div> // for your controller variable
And
<div th:utext="#{message.username}"> UserName! </div> // for your properties variable
Nothing do other configuration for using special character with thymeleaf html page.
Hope you will fix your problem
I'm utilizing spring for about a year and everything was pretty obvious and simple until I faced spring integration. Ashamed, I can't create Outbound Gateway to send message to remote JMS (ActiveMQ) channel. Before integration I just used JmsTemplates and #JmsListeners directly, there were no problems at all.
What's the difference between request-destination and request-channel?
Here are my configs:
#Configuration
#EnableJms
public class JmsConfig {
...
#Value("${activemq.url}")
private String brokerUrl;
#Bean
public JmsTemplate jmsTemplate() {
JmsTemplate jmsTemplate = new JmsTemplate(queueConnectionFactory());
jmsTemplate.setDefaultDestinationName(bookingChannelName);
return jmsTemplate;
}
/*
#Bean(name = "bookingChannel")
public Queue activeMQQueue() {
return new ActiveMQQueue(bookingChannelName);
}
*/
#Bean
public JmsListenerContainerFactory jmsListenerContainerFactory() {
SimpleJmsListenerContainerFactory listenerFactory = new SimpleJmsListenerContainerFactory();
listenerFactory.setConnectionFactory(queueConnectionFactory());
return listenerFactory;
}
...
}
and an xml one, where all I've got in root beans element is:
<jms:outbound-gateway request-destination-name="reqDestination" request-channel="bookingChannel" />
Then, there is a gateway code:
#MessagingGateway
public interface BookingGateway<T> {
#Gateway
void bookTicket(T ticket);
}
And finally, here is how I use a gateway:
#Component
public class BookingGatewayImpl<T> {
#Autowired
private BookingGateway bookingGateway;
public <U> void bookTicket(T ticket, BiConsumer<T, U> onStatusReceived) {
bookingGateway.bookTicket(ticket); // second param is not utilized yet
}
}
And when ticket is about to be booked, I get:
send is not supported, because no request channel has been configured
Also, I am not able to uncomment ActiveMQQueue bean from the first listing because spring says it is not compatible with MessageChannel:
Bean named 'bookingChannel' must be of type [org.springframework.messaging.MessageChannel], but was actually of type [org.apache.activemq.command.ActiveMQQueue]
Why oh why should the destination be of MessageChannel type? What exactly am I doing wrong and how to get this ticket message to be sent?
bookingChannel is a MessageChannel between your MessagingGateway and the jms gateway. The destination is the AMQP Queue.
Use
#Gateway(requestChannel="bookingChannel")
#Bean(name = "bookingDestination")
public Queue activeMQQueue() {
return new ActiveMQQueue(bookingChannelName);
}
#Bean(name = "bookingChannel")
public MessageChannel bookingChannel() {
return new DirectChannel();
}
<jms:outbound-gateway request-destination-name="bookingDestination" request-channel="bookingChannel" />
Finally, came up with following configuration. Almost understood the way it's working now:
<?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:int="http://www.springframework.org/schema/integration"
xmlns:jms="http://www.springframework.org/schema/integration/jms"
xmlns:id="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd http://www.springframework.org/schema/integration/jms http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd">
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="nio://127.0.0.1:61616"/>
</bean>
<bean id="requestQueue" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="bookingChannel"/>
</bean>
<id:channel id="requestChannel"/>
<bean id="channelInterceptor" class="c.e.mentoring.integration.gateway.RequestChannelInterceptor"/>
<jms:outbound-channel-adapter channel="requestChannel" destination="requestQueue"/>
<int:channel-interceptor ref="channelInterceptor"/>
</beans>
I am using ReloadableResourceBundleMessageSource to store value list of my system. So i can use the i18N functionality
i am using multiple resources in the basenames of ReloadableResourceBundleMessageSource.
I want to pass all the localized labels of the web UI to the client (front-end) in order to be cached locally at the client.
Is there a way to load the entire keys of my resource bundles?
here is my ReloadableResourceBundleMessageSource bean definition:
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:resource1</value>
<value>classpath:resource2</value>
</list>
</property>
<property name="cacheSeconds" value="60"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="useCodeAsDefaultMessage" value="true"/>
</bean>
and this is my controller that pass all the keys:
#Component
#RequestMapping("/bundle")
public class ResourceBundleController {
#Autowired
private MessageSource messageSource;
#RequestMapping(value = "/locales.js")
public ModelAndView strings(HttpServletRequest request) {
// Call the string.jsp view
return new ModelAndView("/WEB-INF/includes/locales.jsp", "keys", ??? );// HERE IS MY PROBLEM. HOW SHOULD I GET ALL THE KEYS FROM MESSAGESOURCE
}
}
and here is my the resource bundle keys for the client:
<%#page contentType="text/javascript" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%#taglib prefix="spring" uri="http://www.springframework.org/tags"%>
var messages = {};
<c:forEach var="key" items="${keys}">
messages["<spring:message text='${key}' javaScriptEscape='true'/>"] = "<spring:message code='${key}' javaScriptEscape='true' />";
</c:forEach>
Any help will be appreciated.
Updated information about spring configuration regards cache of resource bundle
You could make something like this:
Your own implementation of ReloadableResourceBundleMessageSource:
public class ExposedResourceMessageBundleSource extends ReloadableResourceBundleMessageSource {
private static final Logger LOGGER = Logger.getLogger(ExposedResourceMessageBundleSource.class);
#Override
protected Properties loadProperties(Resource resource, String fileName) throws IOException {
LOGGER.info("Load " + fileName);
return super.loadProperties(resource, fileName);
}
/**
* Gets all messages for presented Locale.
* #param locale user request's locale
* #return all messages
*/
public Properties getMessages(Locale locale){
return getMergedProperties(locale).getProperties();
}
}
Service definition to handle reasource operations:
public interface MessageResolveService extends MessageSourceAware{
String getMessage(String key, Object[] argumentsForKey, Locale locale);
Map<String,String> getMessages(Locale locale);
}
And implementation:
#Service
public class MessageResolverServiceImpl implements MessageResolveService{
private static final Logger LOGGER = Logger.getLogger(MessageResolverServiceImpl.class);
private MessageSource messageSource;
#Override
public void setMessageSource(MessageSource messageSource) {
LOGGER.info("Messages i18n injected");
this.messageSource = messageSource;
}
public String getMessage(String key, Object[] arguments, Locale locale){
String message = "";
try{
message = messageSource.getMessage(key,arguments,locale);
} catch(NoSuchMessageException e){
message = key;
LOGGER.warn("No message found: "+key);
}
return message;
}
public Map<String,String> getMessages(Locale locale){
Properties properties = ((XmlWebApplicationContext)messageSource).getBean("messageSource",
ExposedResourceMessageBundleSource.class).getMessages(locale);
Map<String,String> messagesMap = new HashMap<String,String>();
for(Map.Entry<Object,Object> entry: properties.entrySet()){
if(entry.getKey() != null && entry.getValue() != null) {
messagesMap.put(entry.getKey().toString(), entry.getValue().toString());
}
}
return messagesMap;
}
}
Spring configuration:
<bean id="messageSource" class="your.package.ExposedResourceMessageBundleSource">
<property name="basenames">
<list>
<value>classpath:yourFileName</value>
<value>classpath:yourNextFileName</value>
</list>
</property>
<property name="defaultEncoding" value="UTF-8"/>
<property name="cacheSeconds" value="10"/> //If you want reload message every couple seconds. In this case every 10 seconds.
</bean>
And your #Controller(similar to this):
#Component
#RequestMapping("/bundle")
public class ResourceBundleController {
#Autowired
private MessageResolveService messageResolveService;
#RequestMapping(value = "/locales.js")
public ModelAndView strings(HttpServletRequest request) {
// Call the string.jsp view
return new ModelAndView("/WEB-INF/includes/locales.jsp", "keys", messageResolverService.getMessages(LocaleContextHolder.getLocale()));
}
I Moving from Spring MVC XML files to javaconfig. I am really at a lost with my database XML file. I don't know how to get Hibernate4 working and my JBoss JNDI Datasource working. Can someone please tell me how to make the javaconfig class work like this XML..
Here is my database.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:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
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-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
<context:property-placeholder location="classpath:app.properties" />
<context:component-scan base-package="org.uftwf" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<jee:jndi-lookup id="dataSource" jndi-name="java:jboss/datasources/mySQLDB"
expected-type="javax.sql.DataSource" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>org.uftwf.inquiry.model.MemberInquiryInformation</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop>
<prop key="format_sql">${format_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Here is my javaconfig class:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages= {"org.uftwf.inquiry"})
#ImportResource("/WEB-INF/spring/root-config.xml")
public class WebMVCConfig extends WebMvcConfigurerAdapter {
private static final String MESSAGE_SOURCE = "/WEB-INF/classes/messages";
private static final Logger logger = LoggerFactory.getLogger(WebMVCConfig.class);
#Value("${jdbc.driverClassName}")
private String driverClassName;
#Value("${jdbc.url}")
private String url;
#Value("${jdbc.username}")
private String username;
#Value("${jdbc.password}")
private String password;
#Value("${hibernate.dialect}")
private String hibernateDialect;
#Value("${hibernate.show_sql}")
private String hibernateShowSql;
#Value("${hibernate.hbm2ddl.auto}")
private String hibernateHbm2ddlAuto;
#Bean
public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer()
{
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setLocation(new ClassPathResource("application.properties"));
ppc.setIgnoreUnresolvablePlaceholders(true);
return ppc;
}
#Bean()
public DataSource getDataSource()
{
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(driverClassName);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
#Bean
public LocalSessionFactoryBean sessionFactory()
{
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setDataSource(getDataSource());
factoryBean.setHibernateProperties(getHibernateProperties());
factoryBean.setPackagesToScan("org.uftwf.inquiry.model");
return factoryBean;
}
#Bean
public Properties getHibernateProperties()
{
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", hibernateDialect);
//hibernateProperties.setProperty("hibernate.show_sql", "true");
//hibernateProperties.setProperty("hibernate.format_sql", "true");
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "update");
hibernateProperties.setProperty("javax.persistence.validation.mode", "none");
//Audit History flags
hibernateProperties.setProperty("org.hibernate.envers.store_data_at_delete", "true");
hibernateProperties.setProperty("org.hibernate.envers.global_with_modified_flag", "true");
return hibernateProperties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory)
{
HibernateTransactionManager htm = new HibernateTransactionManager();
htm.setSessionFactory(sessionFactory);
return htm;
}
#Bean
public ViewResolver resolver() {
UrlBasedViewResolver url = new UrlBasedViewResolver();
url.setPrefix("/WEB-INF/view/");
url.setViewClass(JstlView.class);
url.setSuffix(".jsp");
return url;
}
#Bean(name = "messageSource")
public MessageSource configureMessageSource() {
logger.debug("setting up message source");
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename(MESSAGE_SOURCE);
messageSource.setCacheSeconds(5);
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver lr = new SessionLocaleResolver();
lr.setDefaultLocale(Locale.ENGLISH);
return lr;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
logger.debug("setting up resource handlers");
registry.addResourceHandler("/resources/").addResourceLocations("/resources/**");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
logger.debug("configureDefaultServletHandling");
configurer.enable();
}
#Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
}
#Bean
public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
SimpleMappingExceptionResolver b = new SimpleMappingExceptionResolver();
Properties mappings = new Properties();
mappings.put("org.springframework.web.servlet.PageNotFound", "p404");
mappings.put("org.springframework.dao.DataAccessException", "dataAccessFailure");
mappings.put("org.springframework.transaction.TransactionException", "dataAccessFailure");
b.setExceptionMappings(mappings);
return b;
}
#Bean
public RequestTrackerConfig requestTrackerConfig()
{
RequestTrackerConfig tr = new RequestTrackerConfig();
tr.setPassword("Waiting#$");
tr.setUrl("https://uftwfrt01-dev.uftmasterad.org/REST/1.0");
tr.setUser("root");
return tr;
}
}
I think the parts I am missing are the following but please overcheck my class
<context:property-placeholder location="classpath:app.properties" />
<context:component-scan base-package="org.uftwf" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<jee:jndi-lookup id="dataSource" jndi-name="java:jboss/datasources/mySQLDB"
expected-type="javax.sql.DataSource" />
For
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
annotate your Configuration class, WebMVCConfig, with
#EnableTransactionManagement
For
<context:component-scan base-package="org.uftwf" />
Add the package String to your #ComponentScan field basePackages
For
<context:property-placeholder location="classpath:app.properties" />
annotate your Configuration class with
#PropertySource(value = "classpath:app.properties")
and make your PropertyPlaceholderConfigurer #Bean method static.
For
<jee:jndi-lookup id="dataSource" jndi-name="java:jboss/datasources/mySQLDB"
expected-type="javax.sql.DataSource" />
I think you can do
#Bean
public DataSource dataSource() throws Exception {
Context ctx = new InitialContext();
return (DataSource) ctx.lookup("java:jboss/datasources/mySQLDB");
}
Instead of autowiring your session factory, just call your #Bean method
#Bean
public HibernateTransactionManager transactionManager()
{
HibernateTransactionManager htm = new HibernateTransactionManager();
htm.setSessionFactory(sessionFactory());
return htm;
}