Hibernate Search Error With Spring MVC - spring-mvc

I am trying to learn Hibernate Search.
I have an existing SpringMVC+Hibernate CRUD project with Form Validations.
The project works perfectly, but after I add Hibernate Search functionality,
The following error is shown
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.config.SpringConfig: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
My code :
/////////////////////////////SpringConfig.java///////////////////////////
package com.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.model.Person;
import com.service.PersonService;
#Configuration
#EnableWebMvc
#ComponentScan({ "com.*" })
#EnableTransactionManagement
public class SpringConfig extends WebMvcConfigurerAdapter {
#Autowired
private Environment environment;
#Autowired
private PersonService ps;
#Bean #Autowired
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setAnnotatedClasses(Person.class);
sessionFactory.setPackagesToScan(new String[] { "com.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean #Autowired
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/myschema");
dataSource.setUsername("root");
dataSource.setPassword("admin123");
return dataSource;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
registry.addResourceHandler("/resources/**").addResourceLocations(
"/resources/*");
}
#Bean #Autowired
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver res = new InternalResourceViewResolver();
res.setPrefix("/WEB-INF/view/");
res.setSuffix(".jsp");
return res;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect",
"org.hibernate.dialect.MySQL5Dialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.search.default.directory_provider", "org.hibernate.search.store.impl.FSDirectoryProvider");
properties.put("hibernate.search.default.indexBase", "H:/MyWorkspace/MainAssignment3/indexes");
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
//////////////////////////////Controller/////////////////////////////
package com.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
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.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.model.Person;
import com.service.PersonService;
#Controller
public class MainController {
#Autowired
private PersonService ps;
#RequestMapping("/")
public ModelAndView listPersons(ModelAndView model) throws Exception {
ps.indexPersons();
List<Person> listper = ps.list();
model.addObject("personsList", listper);
model.setViewName("index");
return model;
}
#RequestMapping(value = "/newPerson", method = RequestMethod.GET)
public ModelAndView newPerson(ModelAndView model) throws IOException {
#SuppressWarnings("unused")
Person p = new Person();
model.addObject("person", new Person());
model.setViewName("AddPerson");
return new ModelAndView("AddPerson", "person", new Person());
}
#RequestMapping(value="/save")
public String save(/*#ModelAttribute*/ #Valid Person p, BindingResult result) {
if(result.hasErrors())
{
return "AddPerson";
}
else
{
ps.save(p);
return "redirect:http://localhost:8080/MainAssignment3/";
}
}
#RequestMapping("/removePerson")
public String remove(HttpServletRequest req) {
int id = Integer.parseInt(req.getParameter("id"));
ps.removePerson(id);
return "redirect:http://localhost:8080/MainAssignment3/";
}
#RequestMapping("/update")
public String update(/*#ModelAttribute*/ #Valid Person p1,BindingResult result,Model p) {
System.out.println(p1.getName());
int id=p1.getId();
// ps.getPersonById(p.getId());
p.addAttribute("p1", p1);
p.addAttribute("id", id);
p.addAttribute("name", p1.getName());
p.addAttribute("gender", p1.getGender());
p.addAttribute("address", p1.getAddress());
p.addAttribute("salary", p1.getSalary());
if(result.hasErrors())
{
return "redirect:http://localhost:8080/MainAssignment3/updatePerson";
}
else{
ps.save(p1);
return "redirect:http://localhost:8080/MainAssignment3/";
}
}
#RequestMapping("/updatePerson")
public ModelAndView updatePerson(HttpServletRequest req, ModelMap p1,#ModelAttribute Person p) {
p1.addAttribute("person",new Person());
int id = Integer.parseInt(req.getParameter("id"));
String name = req.getParameter("name");
String address = req.getParameter("address");
String gender = req.getParameter("gender");
String salary = req.getParameter("salary");
p1.addAttribute("id", id);
p1.addAttribute("name", name);
p1.addAttribute("gender", gender);
p1.addAttribute("address", address);
p1.addAttribute("salary", salary);
p1.addAttribute("p1",new Person());
return new ModelAndView("updatePerson", "person", new Person());
}
#RequestMapping(value = "/search", method = RequestMethod.GET)
public ModelAndView searchPage()
{
ModelAndView mav = new ModelAndView("search");
return mav;
}
#RequestMapping(value = "/doSearch", method = RequestMethod.POST)
public ModelAndView search(#RequestParam("searchText")String searchText) throws Exception
{
List<Person> allFound = ps.searchForPerson(searchText);
List<Person> bookModels = new ArrayList<Person>();
for (Person p : allFound)
{
Person pm = new Person();
pm.setName(p.getName());
pm.setAddress(p.getAddress());
pm.setGender(p.getGender());
pm.setSalary(p.getSalary());
bookModels.add(pm);
}
ModelAndView mav = new ModelAndView("foundPersons");
mav.addObject("foundPersons", bookModels);
return mav;
}
}
////////////////////////////////Repository////////////////////////
package com.dao;
import java.util.List;
import com.model.Person;
public interface PersonDAO {
public void save(Person p);
public List<Person> list();
public void updatePerson(Integer id);
public Person getPersonById(int id);
public void removePerson(Integer id);
public void indexPersons() throws Exception;
public List<Person> searchForPerson(String searchText) throws Exception;
}
////////////////////////////////Implementation////////////////////////
package com.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.model.Person;
#Transactional
#Repository
public class PersonDAOImpl implements PersonDAO, java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger logger = (Logger) LoggerFactory
.getLogger(PersonDAOImpl.class);
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
public void save(Person p) {
// TODO Auto-generated method stub
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
s.saveOrUpdate(p);
tx.commit();
s.close();
System.out.println("Record successfully inserted");
}
#SuppressWarnings("deprecation")
public List<Person> list() {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
#SuppressWarnings("unchecked")
List<Person> personsList = session.createQuery("from Person").list();
for (Person p : personsList) {
logger.info("Person List::" + p);
}
return personsList;
}
public void updatePerson(Integer id) {
Session session = new Configuration().configure().buildSessionFactory()
.openSession();
Person p = new Person();
Person person = session.get(Person.class, p.getId());
//Transaction t = session.beginTransaction();
Query query = session.createQuery("from Person");
person.setName(p.getName()); // modify the loaded object somehow
session.update(person);
//t.commit();
session.close();
}
public Person getPersonById(int id) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
Person p = (Person) session.load(Person.class, new Integer(id));
logger.info("Person loaded successfully, Person details=" + p);
return p;
}
public void removePerson(Integer id) {
Session session = sessionFactory.getCurrentSession();
// Transaction t = session.beginTransaction();
Person p = (Person) session.load(Person.class, new Integer(id));
session.delete(p);
// t.commit();
logger.info("Person deleted successfully, person details=");
}
#Transactional
public void indexPersons() throws Exception{
// TODO Auto-generated method stub
try
{
Session session = sessionFactory.getCurrentSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
fullTextSession.createIndexer().startAndWait();
}
catch(Exception e)
{
throw e;
}
}
public List<Person> searchForPerson(String searchText) throws Exception{
// TODO Auto-generated method stub
try
{
Session session = sessionFactory.getCurrentSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
QueryBuilder qb = fullTextSession.getSearchFactory()
.buildQueryBuilder().forEntity(Person.class).get();
org.apache.lucene.search.Query query = qb
.keyword().onFields("name", "address", "salary","gender")
.matching(searchText)
.createQuery();
org.hibernate.Query hibQuery =
fullTextSession.createFullTextQuery(query, Person.class);
List<Person> results = hibQuery.list();
return results;
}
catch(Exception e)
{
throw e;
}
}
}
//////////////////////////MODEL////////////////////////////
package com.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Store;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;
#Entity
public class Person {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#NotEmpty #NotNull(message="Name is required!")
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String name;
#Size(min=5, max=10, message="Your address should be between 5 - 10 characters.")
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String address;
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private Integer salary;
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String gender;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
////////////////////////////////Service/////////////////////////////////
package com.service;
import java.util.List;
import com.model.Person;
public interface PersonService {
public void save(Person p);
public List<Person> list();
public void updatePerson(Integer id);
public Person getPersonById(int id);
public void removePerson(Integer id);
public void indexPersons() throws Exception;
public List<Person> searchForPerson(String searchText) throws Exception;
}
//////////////////////////////////////Service Implementation/////////////
package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dao.PersonDAO;
import com.model.Person;
#Service("PersonService")
public class PersonServiceImpl implements PersonService {
#Autowired
private PersonDAO pdao;
#Transactional
public void save(Person p) {
// TODO Auto-generated method stub
pdao.save(p);
}
public List<Person> list() {
// TODO Auto-generated method stub
return pdao.list();
}
public void updatePerson(Integer id) {
// TODO Auto-generated method stub
pdao.updatePerson(id);
}
public Person getPersonById(int id) {
// TODO Auto-generated method stub
return this.pdao.getPersonById(id);
}
public void removePerson(Integer id) {
// TODO Auto-generated method stub
pdao.removePerson(id);
}
public void indexPersons() throws Exception {
// TODO Auto-generated method stub
pdao.indexPersons();
}
public List<Person> searchForPerson(String searchText) throws Exception {
// TODO Auto-generated method stub
return null;
}
}
//////////////////////////////index.jsp/////////////////////
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://www.springframework.org/tags/form"
prefix="springForm"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<meta charset="utf-8">
<title>Welcome</title>
</head>
<body>
<h2>Hello World!</h2>
<h3>Add Person</h3>
<table border="1">
<tr>
<th>id</th>
<td>name<springForm:errors path='${p.name}' /></td>
<td>address<springForm:errors path='${p.address}' /></td>
<td>gender<springForm:errors path='${p.gender}' /></td>
<td>salary<springForm:errors path='${p.salary}' /></td></tr>
<c:forEach var="p" items='${personsList}' varStatus="status">
<tr>
<td>${p.id}</td>
<td>${p.name}</td>
<td>${p.address}</td>
<td>${p.gender}</td>
<td>${p.salary}</td>
<td>
Edit
Delete
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
///////////////////////////////////search.jsp//////////////////
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://www.springframework.org/tags/form"
prefix="springForm"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!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>Search Page</title>
</head>
<body>
<springForm:form action="/MainAssignment3/doSearch" method="POST" commandName="p">
<c:forEach var="p" items='${foundPersons}' varStatus="status">
<td>${p.name}</td>
<td>${p.address}</td>
<td>${p.gender}</td>
<td>${p.salary}</td>
</c:forEach>
</springForm:form>
</body>
</html>
//////////////////////////////AddPerson.jsp/////////////////////////////
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://www.springframework.org/tags/form"
prefix="springForm"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!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>Add Person</title>
</head>
<body>
<h1>Employee Registration Form</h1>
<springForm:form action="/MainAssignment3/save" method="POST"
commandName="person">
<table style="border: thin; border: ridge;">
<tr>
<td>Enter Name:</td>
<td bordercolor="#FF0000" ><springForm:input path="name"
placeholder="Enter Name" /></td>
<td><springForm:errors path="name" /></td>
</tr>
<tr>
<td>Enter address:</td>
<td><input type="text" name="address" placeholder="Enter Address" ></td>
<td><springForm:errors path="address" /></td>
</tr>
<tr>
<td>Enter gender:</td>
<td><springForm:input path="gender" id="gender" placeholder="Enter Gender" /></td>
<%-- <td><springForm:errors path="gender" /></td> --%>
</tr>
<tr>
<td>Enter salary:</td>
<td><input type="text" name="salary" placeholder="Enter Salary" ></td>
<td><springForm:errors path="salary" /></td>
<td style="padding-left: 110px;"></td>
</tr>
<tr>
<td><input type="submit"value="submit"></td>
</tr>
</table>
</springForm:form>
</body>
</html>
/////////////////////////////////////updatePerson.jsp/////////////////////
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://www.springframework.org/tags/form"
prefix="springForm"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!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>Update Person</title>
</head>
<body>
<springForm:form action="/MainAssignment3/update" method="POST" commandName="person">
<table style="border: thin; border: ridge;">
<tr>
<td><input type="hidden" name="id" value="${id}"></td>
</tr>
<tr>
<td>Enter Name:</td>
<td bordercolor="#FF0000" >
<springForm:input path="name" placeholder="Enter Name" value='${name}'/></td>
<%-- <td><springForm:errors path="name" /></td> --%>
</tr>
<tr>
<td>Enter address:</td>
<td><springForm:input path="address" id="address" placeholder="Enter Address" value='${address}'/></td>
<%-- <td><springForm:errors path='${p1.address}'/></td> --%>
</tr>
<tr>
<td>Enter gender:</td>
<td><springForm:input path="gender" id="gender" placeholder="Enter Gender" value='${gender}' /></td>
<%-- <td><springForm:errors path='${p1.gender}'/></td> --%>
</tr>
<tr>
<td>Enter salary:</td>
<td><springForm:input path="salary" id="salary" placeholder="Enter Salary" value='${salary}'/></td>
<%-- <td><springForm:errors path='${p1.salary}' /></td> --%>
<td style="padding-left: 110px;"></td>
</tr>
<tr>
<td><input type="submit"value="submit"></td>
</tr>
</table>
</springForm:form>
</body>
</html>

Related

Servlet in Eclipse: The requested resource [/Register/] is not available [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 2 years ago.
Exact error: The requested resource [/Register/] is not available. Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
I am using tomcat and Eclipse.
Here is the code:
RegisterDao.java
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class RegisterDao {
private String dbUrl = "jdbc:mysql://localhost:3306/explorecalifornia";
private String dbUname = "dbuser";
private String dbPassword = "dbpassword";
private String dbDriver = "com.mysql.cj.jdbc.Driver";
public void loadDriver(String dbDriver)
{
try {
Class.forName(dbDriver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Connection getConnection()
{
Connection con = null;
try {
con = DriverManager.getConnection(dbUrl, dbUname, dbPassword);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public String insert(Member member)
{
loadDriver(dbDriver);
Connection con = getConnection();
String result = "Data entered successfully";
String sql = "insert into member values(?,?,?,?)";
PreparedStatement ps;
try {
ps = con.prepareStatement(sql);
ps.setString(1, member.getUname());
ps.setString(2, member.getPassword());
ps.setString(3, member.getEmail());
ps.setString(4, member.getPhone());
ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = "Data not entered";
}
return result;
}
}
Register.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Register")
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Register() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uname = request.getParameter("uname");
String password = request.getParameter("password");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
Member member = new Member(uname, password, email, phone);
RegisterDao rDao = new RegisterDao();
String result = rDao.insert(member);
response.getWriter().print(result);
}
}
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Registration</display-name>
<welcome-file-list>
<welcome-file>memberRegistration.jsp</welcome-file>
</welcome-file-list>
</web-app>
and memberRegistration.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="memberRegistration" method="post">
<table>
<tr><td>User Name: </td><td><input type="text" name="uname"></td></tr>
<tr><td>Password: </td><td><input type="password" name="password"></td></tr>
<tr><td>Email: </td><td><input type="text" name="email"></td></tr>
<tr><td>phone: </td><td><input type="text" name="phone"></td></tr>
<tr><td></td><td><input type="submit" value="register"></td></tr>
</table>
</form>
</body>
</html>
Need to place the servlet class in a java package. You should always put publicly reusable Java classes in a package, otherwise they are invisible to classes which are in a package, such as the server itself.

spring mvc view resolution configuration fail to display jsp page

I am new to spring mvc.
When I run this url:http://localhost:8080/spring-mvc-foundation/main/
I get "hello". I was expecting to execute the hello.jsp page and get output:Hello World TEST123
DispatcherInitializer.java:
package com.oreilly.mvc;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class DispatcherInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {RootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {WebConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
RootConfig.java:
package com.oreilly.mvc;
import org.springframework.context.annotation.ComponentScan;
#ComponentScan("com.oreilly.mvc.services")
public class RootConfig {
}
WebConfig.java:
package com.oreilly.mvc;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#EnableWebMvc
#ComponentScan("com.oreilly.mvc.controllers")
public class WebConfig {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolverBean = new InternalResourceViewResolver();
viewResolverBean.setPrefix("/WEB-INF/views/");
viewResolverBean.setSuffix(".jsp");
return viewResolverBean;
}
}
MainController.java:
package com.oreilly.mvc.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.oreilly.mvc.services.GreetingService;
#Controller
#RequestMapping("/main")
public class MainController {
#Autowired
public GreetingService greetingService;
#ResponseBody
#RequestMapping("/")
public String message(Model model) {
model.addAttribute("message",this.greetingService.greet());
return "hello";
}
}
hello.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Hello World Application</title>
</head>
<body>
<h1>${message} TEST123</h1>
</body>
</html>
location of jsp page hello.jsp:
browser output:
Remove #ResponseBody annotation.
#ResponseBody is a Spring annotation which binds a method return value to the web response body. It is not interpreted as a view name. It uses HTTP Message converters to convert the return value to HTTP response body, based on the content-type in the request HTTP header.

Spring: #Valid always returns False

I'm new to Spring Framework. I'm trying to get #Valid to work. Data Binding is happening properly but not the validation. hasErrors() is always returning False in the Controller class. Please see below code.
I'm utilizing Spring 4.1.3 and Hibernate validator 6.0.16.
Context xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<context:property-placeholder location="classpath:/config.properties"/>
<context:annotation-config />
<mvc:annotation-driven />
<context:component-scan base-package="com.personal, com.documentum" />
</beans>
Controller:
package com.personal.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.personal.search.model.SearchForm;
import com.personal.search.service.SearchService;
#Controller
public class SearchController {
private SearchService service;
#Autowired
public SearchController(SearchService service) {
this.service = service;
}
#RequestMapping(value="/", method=RequestMethod.GET)
public String searchHome(Model model) {
model.addAttribute(new SearchForm());
return "search/search";
}
#RequestMapping(value="/", method=RequestMethod.POST)
public String searchResults(#Valid SearchForm searchForm, BindingResult errors, Model model) {
if (!errors.hasErrors()) {
System.out.println(searchForm.getObjectName());
model.addAttribute(service.getResults(searchForm));
}
return "search/search";
}
}
View:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<%# page session="false" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<sf:form method="POST" commandName="searchForm">
<sf:errors path="*" />
<label>Enter Object Name:</label>
<sf:input path="objectName"/><sf:errors path="objectName" /><br>
<button type="submit" value="Submit">Submit</button>
</sf:form>
<h3>For your search term "${searchForm.objectName}" below are the results: </h3>
<c:forEach items="${searchResultList}" var="searchResult" >
<li>
<div>
<span>
(<c:out value="${searchResult.objectName}" />,
<c:out value="${searchResult.title}" />)</span>
</div>
</li>
</c:forEach>
</body>
</html>
Model:
SearchForm Model:
package com.personal.search.model;
import javax.validation.constraints.NotBlank;
public class SearchForm {
#NotBlank
private String objectName;
public SearchForm() {
}
public SearchForm(String objectName) {
this.objectName = objectName;
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
}
SearchResult Model:
package com.personal.search.model;
public class SearchResult {
private String objectName;
private String title;
public SearchResult() {
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String name) {
this.objectName = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Service:
package com.personal.search.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.personal.search.dao.SearchDAO;
import com.personal.search.model.SearchForm;
import com.personal.search.model.SearchResult;
#Service
public class SearchService implements ISearchService {
private SearchDAO dao;
public SearchService() {
}
#Autowired
public SearchService(SearchDAO dao) {
this.dao = dao;
}
#Override
public List<SearchResult> getResults(SearchForm searchform) {
return dao.getSearchObjects(searchform);
}
}
DAO:
package com.personal.search.dao;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import com.documentum.com.DfClientX;
import com.documentum.fc.client.DfServiceException;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfCollection;
import com.documentum.fc.client.IDfQuery;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.IDfLoginInfo;
import com.personal.search.model.SearchForm;
import com.personal.search.model.SearchResult;
#Repository
public class SearchDAO {
private String repository;
private String userName;
private String password;
private IDfSessionManager sessionMgr = null;
public SearchDAO() {
}
#Autowired
public SearchDAO(
#Value("${docbase.repository}") String repository,
#Value("${docbase.user}") String userName,
#Value("${docbase.password}") String password)
{
this.repository = repository;
this.userName = userName;
this.password = password;
System.out.println(repository + " " + userName + " " + password);
}
/**
* Creates a IDfSessionManager
*/
private IDfSessionManager getSessionManager()
{
// create a client object using a factory method in DfClientX
DfClientX clientx = new DfClientX();
IDfClient client;
IDfSessionManager sessionMgr = null;
try {
client = clientx.getLocalClient();
// call a factory method to create the session manager
sessionMgr = client.newSessionManager();
addIdentity(clientx, sessionMgr);
} catch (DfException e) {
e.printStackTrace();
}
return sessionMgr;
}
private void addIdentity(DfClientX clientx, IDfSessionManager sessionMgr)
{
// create an IDfLoginInfo object and set its fields
IDfLoginInfo loginInfo = clientx.getLoginInfo();
loginInfo.setUser(userName);
loginInfo.setPassword(password);
if (sessionMgr != null) {
if (sessionMgr.hasIdentity(repository))
{
sessionMgr.clearIdentity(repository);
}
}
try {
sessionMgr.setIdentity(repository, loginInfo);
} catch (DfServiceException e) {
e.printStackTrace();
}
}
public IDfSession getDBSession() {
IDfSession sess = null;
// Get a session using a factory method of session manager.
try {
sess = sessionMgr.getSession(repository);
} catch (DfServiceException e) {
System.out.println(e.getStackTraceAsString());
}
return sess;
}
public void releaseDBSession(IDfSession sess) {
sessionMgr.release(sess);
}
public List<SearchResult> getSearchObjects(SearchForm searchform) {
List<SearchResult> lst = new ArrayList<SearchResult>();
this.sessionMgr = getSessionManager();
IDfSession sess = null;
try
{
sess = getDBSession();
if (sess != null) {
IDfQuery query = new DfClientX().getQuery();
String dqlStr = "select object_name, title from dm_sysobject where object_name like '%" + searchform.getObjectName() + "%'";
System.out.println(dqlStr);
query.setDQL(dqlStr);
IDfCollection co = query.execute(sess, IDfQuery.DF_READ_QUERY);
while (co.next()) {
SearchResult searchresult = new SearchResult();
searchresult.setObjectName(co.getString("object_name"));
searchresult.setTitle(co.getString("title"));
lst.add(searchresult);
}
if (co != null)
co.close();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (sess != null)
releaseDBSession(sess);
}
return lst;
}
}
I expect the hasErrors() output to be True.
This could be because you have defined the validation as,
#Null
#Size(min=1, max=30)
private String objectName;
Check if when you submit the request to controller the objectName has NULL value or empty string?
For String you must use #NotBlank and not #Null

Not able to convert date into desired format using initbinder spring

I am unable to convert date format using initbinder.
Here is my code of jsp.
<!DOCTYPE html>
<html>
<head>
</head>
<form action="postdata" method="post">
fname <input type="text" name="fname"/> </br>
lname <input type="text" name="lname"/> </br>
Date <input type="text" name="myDate"/> </br>
<input type="submit"/>
</form>
</body>
</html>
My Model Class Employee.java
package com.model;
import java.util.Date;
public class Employee
{
private String fname;
private String lname;
private Date myDate;
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public Date getMyDate() {
return myDate;
}
public void setMyDate(Date myDate) {
this.myDate = myDate;
}
#Override
public String toString() {
return "Employee [fname=" + fname + ", lname=" + lname + ", myDate=" +
myDate + "]";
}
}
My Controller is as below
package com.mkyong;
import java.io.IOException;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
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.model.Employee;
#Controller
public class WelcomeController {
#InitBinder
public void dataBinding(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, "myDate", new
CustomDateEditor(dateFormat, false));
}
#RequestMapping(value="/postdata",method=RequestMethod.POST)
public ModelAndView welcome(HttpServletRequest request, HttpServletResponse
response,#ModelAttribute("employee") Employee employee,BindingResult
bresult)
{
System.out.println("In Welcomeontroller");
System.out.println(employee);
return new ModelAndView("myajax");
}
}
When i checked in debug mode , In dataBinding method i am getting null values for Employee model. In welcome method i am getting the date format as Mon Jan 01 00:00:00 IST 1990. I want it in dd/MM/yyyy format. Please help me out i need to apply same in project for JQGrid.
Change
binder.registerCustomEditor(Date.class, "myDate", new CustomDateEditor(dateFormat, false));
to
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
If you want to use easier approach than above one then try annotating the date field like below.
#DateTimeFormat(pattern = "dd/MM/yyyy")
#ModelAttribute
#Temporal(TemporalType.DATE)
#Column(name = "date")
private Date date;

Unable to print from ArrayList of Objects using JSTL [duplicate]

This question already has answers here:
javax.servlet.ServletException: javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in <forEach>
(3 answers)
Closed 6 years ago.
MainServ.java
package servs.com;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import serv.com.Users;
#WebServlet(name="mainServ",urlPatterns={"/mainServ"})
public class haha extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// JDBC driver name and database URL
final String DB_URL="jdbc:mysql://localhost/test";
// Database credentials
final String USER = "root";
final String PASS = "root";
Connection conn = null;
Statement stmt = null;
ArrayList<Users> usersArr = new ArrayList<Users>();
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n");
try{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
Users u = new Users();
u.setAge(age);
u.setId(id);
u.setFirst(first);
u.setLast(last);
usersArr.add(u);
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
} //end try
request.setAttribute("users", usersArr);
request.getRequestDispatcher("NewFile.jsp").forward(request,response);
System.out.println(usersArr.size());
}
}
NewFile.JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>Insert title here</title>
</head>
<body>
<c:forEach items="${users}" var="rowss">
<c:forEach items="${rowss}" var="item">
<c:out value="${item}"/>
</c:forEach>
</c:forEach>
<!--
<c:forEach var="user" items="${users}">
<c:out value="${users.first}"/>
<c:out value="${users.last}"/>
<c:out value="${users.ageIp}"/>
<c:out value="${users.id}"/>
</c:forEach>
-->
</body>
</html>
Users.java
package servs.com;
final public class Users {
private int id;
private int age;
private String first;
private String last;
public void setId(int i){
this.id=i;
}
public void setAge(int i){
this.age=i;
}
public void setFirst(String i){
this.first=i;
}
public void setLast(String i){
this.last=i;
}
}
When I am trying to print in NewFile.jsp I am getting following error.
javax.servlet.jsp.JspTagException: Don't know how to iterate over
supplied "items" in <forEach>
I don't know the error is in printing or I am doing something wrong while putting the objects into the Arraylist (userArr). I am getting the data successfully out of the database as I did print it first.
Could you please let me know what I can modify in order to print the data. I would be open If there is any different approach for the same.
After adding Getter methods in class Users the issue was resolved. But I still Havea doubt I never used getter methods anywhere. How come getter methods played any role.??
public String getFirst(){
return this.first;
}
public String getLast(){
return this.last;
}
public int getId(){
return this.id;
}
public int getAge(){
return this.age;
}
This is what I appended at the end of Users.java

Resources