Exception : Cannot render a null template in Spring tiles - spring

I have created one simple DAO interface and DAOImpl class for implementation of DAO. Taking data from the jsp and storing it to database. On successful completion I am rendering to a tiles to xml. I am getting below exception while returning view for tiles. Is there any problem in defining tiles as mentioned in this post ? The data is getting stored in the database but on the frontend I am getting the below exception and also on console.
Aug 11, 2015 4:01:03 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [User] in context with path [/SpringUser] threw exception [Request processing failed; nested exception is org.apache.tiles.impl.InvalidTemplateException: Cannot render a null template] with root cause
org.apache.tiles.impl.InvalidTemplateException: Cannot render a null template
at org.apache.tiles.renderer.impl.TemplateAttributeRenderer.write(TemplateAttributeRenderer.java:51)
at org.apache.tiles.renderer.impl.AbstractBaseAttributeRenderer.render(AbstractBaseAttributeRenderer.java:106)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:670)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:690)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:644)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:627)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:321)
at org.springframework.web.servlet.view.tiles2.TilesView.renderMergedOutputModel(TilesView.java:124)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:262)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1180)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:950)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
The tiles file for the same is as below
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="user.reg" template="/jsp/template.jsp">
<put-attribute name="title" value="Sample App"/>
<put-attribute name="header" value=""/>
<put-attribute name="body" value=""/>
<put-attribute name="footer" value=""/>
</definition>
<definition name="user.registration" extends="user.reg">
<put-attribute name="body" value="/jsp/success.jsp" />
</definition>
<definition name="user.registrationUserSuccess" >
<put-attribute name="body" value="/jsp/login.jsp" />
</definition>
<definition name="user.home" >
<put-attribute name="body" value="/jsp/login.jsp" />
</definition>
<definition name="user.profile">
<put-attribute name="body" value="/jsp/profile.jsp" />
</definition>
<definition name="user.error">
<put-attribute name="body" value="/jsp/error.jsp" />
</definition>
</tiles-definitions>
The controller class for the same is as below -
package com.controller;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.dao.UserDAO;
import com.entity.UserDetails;
#Controller
public class UserController {
private static Logger logger = Logger.getLogger(UserController.class);
String errForward = "user.error", forward = null;
#Autowired
UserDAO userDAO;
UserDetails ud = new UserDetails();
#RequestMapping("/registerUser")
public String registerUser(HttpServletRequest request) {
logger.info("### Inside registeration controller ####");
System.out.println("registerUser");
int isSave=0;
Date creation_time=null,lastModTime=null;
SimpleDateFormat ft = new SimpleDateFormat ("dd/MM/yyyy 'at' hh:mm:ss a zzz");
Date date=new Date();
String input = ft.format(date);
try {
creation_time = ft.parse(input);
lastModTime = ft.parse(input);
} catch (ParseException e) {
logger.error("/* Unable to parse date ****["+ ft+"]*****/");
}
String fName=request.getParameter("fName");
fName=(fName.equals(""))?"":fName.trim();
String lName=request.getParameter("lName");
lName=(lName.equals(""))?"":lName.trim();
int age=Integer.parseInt(request.getParameter("age"));
age=(age==0)?0:age;
String email=request.getParameter("email");
email=(email.equals(""))?"":email.trim();
String pswd=request.getParameter("pswd");
pswd=(pswd.equals(""))?"":pswd.trim();
ud.setFirstName(fName);
ud.setLastName(lName);
ud.setAge(age);
ud.setPassword(pswd);
ud.setEmail(email);
ud.setCreationTime(creation_time);
ud.setLastModTime(lastModTime);
try{
isSave=userDAO.saveUserDetails(ud);
if (isSave==0){
forward="user.registrationUserSuccess";
logger.info("/******** Successfully saved the data :::["+isSave+"]::: *****/");
}
}catch(Exception e){
logger.error("##### Error while saving use details #####"+e);
return (forward);
}
return (forward);
}
}
Contents of servlet file are as -
?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-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
</bean> -->
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="com.controller"></context:component-scan>
<context:component-scan base-package="com.dao"></context:component-scan>
<context:component-scan base-package="com.entity"></context:component-scan>
<!-- title defining -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<!-- defining title file location -->
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<import resource="db-config.xml" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

I checked the project from top to bottom. I did not find anything until I changed my directory structure. The jsp page path was inside WEB-INF folder, instead it should be outside WEB_INF and inside WEB CONTENT folder. After correcting the structure I got the required result.

Related

BeanDefinitionStoreException IOException while accessing the application context file

writing a simple spring program to read the bean from the filepathxmlapplication context, but getting the below exception.
but i am sure in can access the xml bean definition file.
public void testConnection() {
try{
List <LnkConnectionResponse> connResponse = new ArrayList <LnkConnectionResponse> ();
log.info ("before xml resource");
ApplicationContext context = new FileSystemXmlApplicationContext("M:/My Documents/workspace-sts-3.7.0.RELEASE/LDODashBoard/src/main/webapp/WEB-INF/mvc-database.xml");
log.info ("before get bean");
LnkConnectionWrapper linkConnectionArray = (LnkConnectionWrapper)context.getBean("linkConnectionArray");
xml bean file
<?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:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd">
<util:list id="dbnameList" list-class="java.util.ArrayList">
<value>LDMDB</value>
<value>GCMMDB</value>
<value>CVDBCHECKOUT</value>
<value>CVEMEADBCHECKOUT</value>
<value>LDMDB</value>
<value>OPUSDB</value>
<value>CDRDB</value>
<value>TLMDB</value>
</util:list>
<util:list id="urlList" list-class="java.util.ArrayList">
<value>ldmUnprocessedLink</value>
<value>gcmmLink2</value>
<value>dbCheckout</value>
<value>dbCheckoutEMEA</value>
<value>dbCheckout</value>
<value>dbCheckout</value>
<value>dbCheckout</value>
<value>dbCheckout</value>
</util:list>
<util:list id="QueryList" list-class="java.util.ArrayList">
<value>select count( * ) from futures.EXMAN_STAGING where REGION = 'LONDON' and process_time_stamp is null</value>
<value>select count( * ) from futures.EXMAN_STAGING where REGION = 'LONDON' and process_time_stamp is null</value>
<value>select name from v$database } select market from cv_welcome where rownum < 2</value>
<value>select market from cvision.cv_welcome where rownum < 2</value>
<value>select 'X' from dual</value>
<value>select 'X' from dual } select GET_PREV_BIZ_DATE from dual </value>
<value>select dummy from dual } Select PREV_BUSINESS_DATE From gmirpt.SD_GMI_PROCDATE Where REGION_IND = 'ATL'</value>
<value>select 'X' from dual</value>
</util:list>
<bean id="DBQueryBean" class="com.connection.impl.DBQueryImpl">
<property name="DBName">
<ref bean="dbnameList"/>
</property>
<property name="UrlName">
<ref bean="urlList"/>
</property>
<property name="QueryString">
<ref bean="QueryList"/>
</property>
</bean>
<bean id="LdmDatabaseBean" class="com.connection.impl.LDMConnectionImpl">
<property name="dbQuery" ref="DBQueryBean"/>
</bean>
<bean id="tlmWebConnectlink" class="com.implementation.LnkConnectionCheck">
<property name="urlIDDesc" value="TLMWebConnect" />
<property name="urlIDGroup" value="tlmlink" />
<property name="urlLink" value="https://tlmapp.csintra.net/WebConnect/login/login.jsp" />
<property name="urlDescription" value="TLM Web Connnect" />
</bean>
<bean id="linkConnectionArray" class="com.implementation.LnkConnectionWrapper">
<property name="lnkConnectionCheck">
<list>
<ref bean="tlmWebConnectlink" />
</list>
</property>
</bean>
</beans>
Exception logs
INFO TestLnkConnection - before xml resource INFO
FileSystemXmlApplicationContext - Refreshing
org.springframework.context.support.FileSystemXmlApplicationContext#61d83ac7:
startup date [Thu Dec 17 06:48:07 GMT+08:00 2015]; root of context
hierarchy INFO XmlBeanDefinitionReader - Loading XML bean definitions
from file [M:\My
Documents\workspace-sts-3.7.0.RELEASE\LDODashBoard\src\main\webapp\WEB-INF\mvc-database.xml]
ERROR TestLnkConnection - Exception Received here!!!
org.springframework.beans.factory.BeanDefinitionStoreException:
IOException parsing XML document from file [M:\My
Documents\workspace-sts-3.7.0.RELEASE\LDODashBoard\src\main\webapp\WEB-INF\mvc-database.xml]; nested exception is java.io.FileNotFoundException: M:\My
Documents\workspace-sts-3.7.0.RELEASE\LDODashBoard\src\main\webapp\WEB-INF\mvc-database.xml
(The system cannot find the path specified) at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:343)
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
at
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)
at
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
at
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:251)
at
org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
at
org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
at
org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at
org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454)
at
org.springframework.context.support.FileSystemXmlApplicationContext.(FileSystemXmlApplicationContext.java:140)
at
org.springframework.context.support.FileSystemXmlApplicationContext.(FileSystemXmlApplicationContext.java:84)
at
com.implementation.TestLnkConnection.testConnection(TestLnkConnection.java:47)
at
com.implementation.TestLnkConnection.main(TestLnkConnection.java:73)
Caused by: java.io.FileNotFoundException: M:\My
Documents\workspace-sts-3.7.0.RELEASE\LDODashBoard\src\main\webapp\WEB-INF\mvc-database.xml
(The system cannot find the path specified) at
java.io.FileInputStream.open(Native Method) at
java.io.FileInputStream.(FileInputStream.java:146) at
org.springframework.core.io.FileSystemResource.getInputStream(FileSystemResource.java:114)
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:329)
... 14 more
If you look at the log your problem is the FileNotFoundException.
java.io.FileNotFoundException: M:\My Documents\workspace-sts-3.7.0.RELEASE\LDODashBoard\src\main\webapp\WEB-INF\mvc-database.xml (The system cannot find the path specified)
You need to ensure you are properly referencing the file in your web application as well as making sure its is in the correct location.

Request processing failed; nested exception is java.lang.NullPointerException

i created a form and on post i want to save those values to the database and show the saved values on the page.
i am new to spring mvc and hence i am not understanding where i am going wrong.
Here is the StackTrace -
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.NullPointerException
com.projects.data.HomeController.addCustomer(HomeController.java:36)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the VMware vFabric tc Runtime 2.7.2.RELEASE/7.0.30.A.RELEASE logs.
Model class
package com.projects.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="customer")
public class Customer {
#Id
int custid;
String name;
int age;
public Customer()
{}
public Customer(int custid,String name,int age)
{
this.custid=custid;
this.name=name;
this.age=age;
}
//Getters And Setters
public int getCustid() {
return custid;
}
public void setCustid(int custid) {
this.custid = custid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Dao Class
package com.projects.model;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.projects.model.Customer;
#Repository
public class CustomerDao {
#Autowired
private SessionFactory sessionfactory;
public SessionFactory getSessionfactory() {
return sessionfactory;
}
public void setSessionfactory(SessionFactory sessionfactory) {
this.sessionfactory = sessionfactory;
}
public int save(Customer customer)
{
return (Integer) sessionfactory.getCurrentSession().save(customer);
}
}
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.projects.model" />
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/customerdb" />
<beans:property name="username" value="root" />
<beans:property name="password" value="root" />
</beans:bean>
<beans:bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="packagesToScan" value="com.projects.model" />
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="sessionFactory" />
</beans:bean>
</beans:beans>
Controller class
package com.projects.model;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 com.projects.model.CustomerDao;
import com.projects.model.Customer;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
private CustomerDao dao;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String customer(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Customer customer=new Customer();
model.addAttribute(customer);
return "home";
}
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute("customer") Customer customer, ModelMap model) {
model.addAttribute("custid", customer.getCustid());
model.addAttribute("name",customer.getName());
model.addAttribute("age", customer.getAge());
dao.save(customer);
return "customer/customer";
}
}
View Files
//home.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<form:form action="${customer}" method="post" modelAttribute="customer">
<form:label path="custid">Id:</form:label>
<form:input path="custId"/> <br>
<form:label path="name">Name:</form:label>
<form:input path="name"/> <br>
<form:label path="age">Age:</form:label>
<form:input path="age"/> <br>
<input type="submit" value="Save"/>
//customer.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Submitted Information</title>
</head>
<body>
<h2>Submitted Information</h2>
<table>
<tr>
<td>Cust id</td>
<td>${custid}</td>
</tr>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
</table>
</body>
</html>
After i click the save button i get the above mentioned error.Please help me resolve this.
Seems to be a problem in your form. At least, the inputs must be given the name attributes:
<form method="post" action="<c:url value='/customer/'/>">
Cust_Id :
<input type="text" name="custid">
<br>
Name :
<input type="text" name="name">
<br>
Age :
<input type="text" name="age">
<input type="submit" value="Save">
</form>
But since you are using Spring, it is preferable to use the Spring forms (and spring url's also):
<spring:url var="customer" value="/customer"/>
<form:form action="${customer}" method="post" modelAttribute="customer">
<form:label path="custid">Id:</form:label>
<form:input path="custId"/> <br>
<form:label path="name">Name:</form:label>
<form:input path="name"/> <br>
<form:label path="age">Age:</form:label>
<form:input path="age"/> <br>
<input type="submit" value="Save"/>
</form:form>
Edit
And you should initialize dao!
#Autowired
private CustomerDao dao;
The attribute of your model has annotated with #ModelAttribute to be nulleable. This is so that when an exception occurs in times of bind there is something to return.
Note the difference between the model attribute and the model attribute parameter.
An exception during bind and validation times could be passing text in an integer field.
Exception:
org.springframework.web.util.NestedServletException:
Request processing failed; nested exception is java.lang.NullPointerException:
Parameter specified as non-null is null: method yourMethod, parameter yourParam
In Kotlin
Going from student: Student to student: Student? exception is avoided.
#RequestMapping("/processFormRegister")
fun processFormRegister(
#Valid #ModelAttribute("firstStudent") student: Student?,
validationResult: BindingResult
): String {
return if (validationResult.hasErrors()) {
"StudentFormRegister"
} else {
"ResultFormRegister"
}
}
And also to see the exception transformed into a validation you could use #Valid and Binding Result of Hibernate Validator obtaining:
failed to convert value of type java.lang.string[] to required type java.lang.integer; nested exception is java.lang.numberformatexception: for input string: "a"
GL

Spring and JSF - Dependency Injection fails ServiceBean can not be loaded

i currently hang up in the Spring and JSF Integration. I think i misconfigured something and i can not see what exactly. I get a NULL Pointer Exception because of the Service Tier is not going to be loaded by the JSF Bean. My configuration is the following:
Stacktrace
java.lang.NullPointerException
at com.speterit.auftragssystem.beans.MitarbeiterBean.getMitarbeiterList(MitarbeiterBean.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:484)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:161)
at org.apache.el.parser.AstValue.getValue(AstValue.java:159)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:106)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:178)
at javax.faces.component.UIData.getValue(UIData.java:553)
at javax.faces.component.UIData.getDataModel(UIData.java:1293)
at javax.faces.component.UIData.setRowIndex(UIData.java:446)
at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:77)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:824)
at javax.faces.component.UIData.encodeBegin(UIData.java:936)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1661)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1666)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1666)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:389)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:127)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:117)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:135)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:335)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:679)
default.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<h:head>
</h:head>
</head>
<h:body>
#{mitarbeiterBean.getServiceMitarbeiter() ne null ? "true" : "false"}<br />
<h:dataTable value="#{mitarbeiterBean.getMitarbeiterList()}" var="m">
<h:column>
<f:facet name="header">Vorname</f:facet>
#{m.vorname}
</h:column>
<h:column>
<f:facet name="header">Nachname</f:facet>
#{m.nachname}
</h:column>
<h:column>
<f:facet name="header">Geburtsdatum</f:facet>
#{m.geburtsdatum}
</h:column>
</h:dataTable>
</h:body>
The evaluation #{mitarbeiterBean.getServiceMitarbeiter() ne null ? "true" : "false"}<br /> is giving false when I execute the code without the datatable part.
MitarbeiterBean.java
package com.speterit.auftragssystem.beans;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import com.speterit.auftragssystem.data.model.Mitarbeiter;
import com.speterit.auftragssystem.data.service.IServiceMitarbeiter;
#ManagedBean(name = "mitarbeiterBean")
#RequestScoped
public class MitarbeiterBean implements Serializable
{
private static final long serialVersionUID = 1L;
public IServiceMitarbeiter serviceMitarbeiter;
public String vorname;
public String nachname;
public Date geburtsdatum;
public List<Mitarbeiter> getMitarbeiterList()
{
return getServiceMitarbeiter().retrieveAllMitarbeiter();
}
public void addMitarbeiter()
{
Mitarbeiter mitarbeiter = new Mitarbeiter(getVorname(), getNachname(),
getGeburtsdatum());
getServiceMitarbeiter().createMitarbeiter(mitarbeiter);
clearForm();
}
public void clearForm()
{
setVorname("");
setNachname("");
setGeburtsdatum(null);
}
public String getVorname()
{
return vorname;
}
public void setVorname(String vorname)
{
this.vorname = vorname;
}
public String getNachname()
{
return nachname;
}
public void setNachname(String nachname)
{
this.nachname = nachname;
}
public Date getGeburtsdatum()
{
return geburtsdatum;
}
public void setGeburtsdatum(Date geburtsdatum)
{
this.geburtsdatum = geburtsdatum;
}
public IServiceMitarbeiter getServiceMitarbeiter()
{
return serviceMitarbeiter;
}
public void setServiceMitarbeiter(IServiceMitarbeiter serviceMitarbeiter)
{
this.serviceMitarbeiter = serviceMitarbeiter;
}
}
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Hibernate -->
<beans:bean id="hibernateSessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<beans:property name="configLocation" value="classpath:hibernate.cfg.xml" />
<beans:property name="configurationClass"
value="org.hibernate.cfg.AnnotationConfiguration" />
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect
</beans:prop>
<beans:prop key="hibernate.c3p0.min_size">5</beans:prop>
<beans:prop key="hibernate.c3p0.max_size">20</beans:prop>
<beans:prop key="hibernate.c3p0.timeout">1800</beans:prop>
<beans:prop key="hibernate.c3p0.max_statements">50</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernateSessionFactory" />
</beans:bean>
<!-- Model Declaration -->
<beans:bean id="Mitarbeiter" class="com.speterit.auftragssystem.data.model.Mitarbeiter"/>
<!-- DAO Declaration -->
<beans:bean id="DaoMitarbeiter" class="com.speterit.auftragssystem.data.dao.DaoMitarbeiter">
<beans:property name="sessionFactory" ref="SessionFactory" />
</beans:bean>
<!-- Service Declaration -->
<beans:bean id="ServiceMitarbeiter" class="com.speterit.auftragssystem.data.service.ServiceMitarbeiter">
<beans:property name="daoMitarbeiter" ref="DaoMitarbeiter" />
</beans:bean>
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
</application>
<managed-bean>
<managed-bean-name>mitarbeiterBean</managed-bean-name>
<managed-bean-class>com.speterit.auftragssystem.beans.MitarbeiterBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>serviceMitarbeiter</property-name>
<value>#{ServiceMitarbeiter}</value>
</managed-property>
</managed-bean>
</faces-config>
IServiceMitarbeiter.java
package com.speterit.auftragssystem.data.service;
import java.util.List;
import com.speterit.auftragssystem.data.dao.IDaoMitarbeiter;
import com.speterit.auftragssystem.data.model.Mitarbeiter;
public interface IServiceMitarbeiter
{
public List<Mitarbeiter> retrieveAllMitarbeiter();
public Mitarbeiter retrieveMitarbeiter(long personalnummer);
public Mitarbeiter createMitarbeiter(Mitarbeiter mitarbeiter);
public Mitarbeiter updateMitarbeiter(Mitarbeiter mitarbeiter);
public IDaoMitarbeiter getDaoMitarbeiter();
public void setDaoMitarbeiter(IDaoMitarbeiter daoMitarbeiter);
}
ServiceMitarbeiter.java
package com.speterit.auftragssystem.data.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.speterit.auftragssystem.data.dao.IDaoMitarbeiter;
import com.speterit.auftragssystem.data.model.Mitarbeiter;
#Transactional(readOnly = true)
public class ServiceMitarbeiter implements IServiceMitarbeiter
{
IDaoMitarbeiter daoMitarbeiter;
#Transactional(readOnly = true)
public List<Mitarbeiter> retrieveAllMitarbeiter()
{
return daoMitarbeiter.getAll();
}
#Transactional(readOnly = true)
public Mitarbeiter retrieveMitarbeiter(long personalnummer)
{
return daoMitarbeiter.getByPersonalnummer(personalnummer);
}
#Transactional(readOnly = false)
public Mitarbeiter createMitarbeiter(Mitarbeiter mitarbeiter)
{
return daoMitarbeiter.create(mitarbeiter);
}
#Transactional(readOnly = false)
public Mitarbeiter updateMitarbeiter(Mitarbeiter mitarbeiter)
{
return daoMitarbeiter.persistOrMerge(mitarbeiter);
}
public IDaoMitarbeiter getDaoMitarbeiter()
{
return daoMitarbeiter;
}
public void setDaoMitarbeiter(IDaoMitarbeiter daoMitarbeiter)
{
this.daoMitarbeiter = daoMitarbeiter;
}
}
I'm happy for every fast clue :) Because i got no idea anymore
With org.springframework.web.jsf.el.SpringBeanFacesELResolver your class needs to be a
simple Spring component. Remove #ManagedBean and add #Component annotations.
You've created another instance of MitarbeiterBean managed by JSF via #ManagedBean annotation and it is not the same bean that is managed by Spring so the serviceMitarbeiter field is not injected. Just forget about JSF managed beans and use Spring components in JSF.
Also replace javax.faces.bean sope annotations with Spring #Scope.
e.g. #RequestScoped -> #Scope("request")

How to start myBatis implemention with spring?

I want to work with myBatis. I have read MyBatis-3-user-guide. Now i am trying to implement it. Recently i have learned spring. So it is difficult for me to implement it. So i need some helpful resource by which i can implement it step by step.
Add the MyBatis-Spring jar in your class path at first
Start with your spring context file.In your context file add following lines
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="yourDriverClassName"
p:url="yourUrl"
p:username="yourUsername"
p:password="yourPassword" />
<beans:bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="configLocation" value="/WEB-INF/mybatis-config.xml" />
</beans:bean>
<beans:bean id="userDao" class="com.yourcomp.dao.Userdao">
<beans:property name="sqlSessionFactory" ref="sqlSessionFactory" />
</beans:bean>
your mybatis-config.xml should be something like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
</settings>
<typeAliases>
<typeAlias alias="User" type ="com.yourcomp.domain.User" />
</typeAliases>
<mappers>
<mapper resource="com/yourcomp/domain/UserMapper.xml"/>
<mapper resource="com/yourcomp/domain/AnotherDomainObjectMapper.xml"/>
</mappers>
</configuration>
and your userMapper.xml in src/com/yourcomp/domain/ might be something like this
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--<mapper namespace="org.pbl.rms.RMSUserDao">-->
<mapper namespace="com.yourcomp.domain.User">
<resultMap id="userMap" type="User">
<id property="userId" column="USER_ID" javaType="int" jdbcType="NUMERIC"/>
<result property="userName" column="USER_NAME" javaType="String" jdbcType="VARCHAR"/>
<result property="userFullName" column="USER_FULL_NAME" javaType="String" jdbcType="VARCHAR"/>
<result property="password" column="PASSWORD" javaType="String" jdbcType="VARCHAR"/>
<result property="passwordExpiryDate" column="PASWRD_EXPIRY_DATE" javaType="java.util.Date" jdbcType="DATE"/>
<result property="status" column="STATUS" javaType="_integer" jdbcType="DECIMAL"/>
</resultMap>
<select id="getUserById" parameterType="map" resultMap="userMap">
select * from user where USER_ID=#{userId}
</select>
</mapper>
now in your DAO layer you might have class like follows:
public class UserDAO{
private SqlSessionFactory sqlSessionFactory;
public UserDAO() {
}
public UserDAO(SqlSessionFactory sqlSessionFactory ) {
this.sqlSessionFactory = sqlSessionFactory;
}
public String getUserById(Integer userId) {
SqlSession session = sqlSessionFactory.openSession();
String name=null;
try {
name = (String)session.selectOne("com.yourcomp.domain.User.getUserById",userId);
}catch(Exception e){
}finally {
session.close();
}
return name;
}
}
You need MyBatis-Spring for this . See the reference here and here These provide you the step by step configs . If you need any specific details , you need to re frame your query .
Also check the spring reference for IBatis support.

UrlBasedViewResolver and Apache Tiles2 in Spring 3

I've got the following exception while trying to open the URL http://localhost:8080/app/clientes/agregar:
javax.servlet.ServletException: Could not resolve view with name 'clientes/agregar' in servlet with name 'Spring MVC Dispatcher Servlet'
My mvc-config.xml is the following:
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions" value="/WEB-INF/tiles/tiles.xml" />
</bean>
My simple tiles.xml:
<definition name="mainTemplate" template="/WEB-INF/template/template.jsp">
<put-attribute name="titulo" value="Simple Tiles 2 Example" type="string" />
<put-attribute name="header" value="/WEB-INF/template/header.jsp" />
<put-attribute name="footer" value="/WEB-INF/template/footer.jsp" />
</definition>
<definition name="*" extends="mainTemplate">
<put-attribute name="content" value="/WEB-INF/views/{1}.jsp" />
</definition>
When I try to open locations under /app it works fine, like /app/welcome or /app/clientes, but this error appears when trying to open /app/clientes/something. I guess it has something to do with the URL Resolver, but I can't find what...
My ClientesController class, annotated with #Controller has a method like the following:
#RequestMapping(method = RequestMethod.GET, value = "agregar")
public void agregar() { ... }
My JSP view files are located under /WEB-INF/views like:
/WEB-INF/views
-- /clientes
---- agregar.jsp
-- welcome.jsp
-- clientes.jsp
Thanks!
Added the following in my tiles.xml and works fine:
<definition name="*/*" extends="mainTemplate">
<put-attribute name="content" value="/WEB-INF/views/{1}/{2}.jsp" />
</definition>
Any better (more flexible) solution?
<definition name="/**" extends="page">
<put-attribute name="content" value="/WEB-INF/jsp/{1}.jsp"/>
</definition>
If you'll get StackOverFlow you should do like this (type="template"):
<put-attribute name="some_name" value="some_page.jsp" type="template"/>
I haven't tested it, but as the documentation says here: tiles wildcards
one asterisk (*) for a single placeholder;
two asterisks (**) to say "in every directory under the specified one";
So try with two asterisks
<definition name="**" extends="mainTemplate">
<put-attribute name="content" value="/WEB-INF/views/{1}.jsp" />
</definition>

Resources