I have a task that must keep data in MS SQL server. That is like simple registration form. I have to enter name, last name, address, and birthday and press submit button. After that the inputting data should be save in database. I don't know how to make it. Here is my code:
JSP PAGE:
<%#page contentType="text/html" 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>Welcome to Test Project</title>
</head>
<body>
Customer List
<h:form>
<h1>Add person</h1>
<p>Please fill in all fields and click Submit</p>
<label id="firstNameLabel">First name</label>
<input id="inputFirstName" value="${customerBean.firstName}"/>
<label id="lastNameLabel">Last name</label>
<input id="inputLastName" value="${customerBean.lastName}"/>
<label id="nirthdayLabel">Birthday name</label>
<input id="inputBirthday" value="${customerBean.birthday}"/>
<label id="addressLabel">Address name</label>
<input id="inputAddress" value="${customerBean.address}"/>
<button id="addAddPerson" value="#{customerBean., hsr1)">Add new person</button>
</h:panelGrid>
</h:form>
</body>
</html>
Another JSP page:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Customer List</title>
</head>
<body>
<h1>Customer List</h1>
<table border="1">
<th>First Name</th><th>Last Name</th><th>Birthday</th><th>Address</th>
<c:forEach items="${customerList}" var="customer">
<tr>
<td>${customer.firstName}</td><td>${customer.lastName}</td>
<td>${customer.birthday}</td><td>${customer.address}</td>
</tr>
</c:forEach>
</table>
Add new person
Home
</body>
</html>
Spring bean 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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!--bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" /-->
<!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
</beans>
More 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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
<bean name="customerController"
class="Controller.CustomerController"/>
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
Hibernate configuration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost\TARAS-PC\SQLEXPRESS:1433;databaseName=Test</property>
<property name="hibernate.connection.username">test</property>
<property name="hibernate.connection.password">test</property>
<!--Add by myself-->
<property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>
<mapping resource="Model/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Java controller:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import Model.Customer;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
/**
*
* #author Taras
*/
public class CustomerController implements Controller{
#Override
public ModelAndView handleRequest(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
ModelAndView mv = new ModelAndView("customerList");
List<Customer> customerList;
try{
//import from package Util
Session session = Util.HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
customerList = session.createQuery("from Customer").list();
// customerList.add(new Customer(new Customer().getFirstName(), new Customer().getLastName(),
// new Customer().getAddress(), new Customer().getBirthday()));
mv.addObject("customerList", customerList);
session.getTransaction().commit();
}
catch (Exception e){
e.printStackTrace();
}
//customerList.add(new Customer("ds", "sf", "sfs", "sf"));
return mv;
}
}
Generated java class:
package Model;
// Generated Mar 4, 2014 11:21:14 PM by Hibernate Tools 3.2.1.GA
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Test generated by hbm2java
*/
#Entity
#ManagedBean (name = "customerBean")
#Table(name="Test"
,schema="dbo"
,catalog="Test"
)
public class Customer implements java.io.Serializable {
private int id;
private String firstName;
private String lastName;
private String address;
private String birthday;
public Customer() {
}
public Customer(String firstName, String lastName, String address, String birthday) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.birthday = birthday;
}
#Id
#Column(name="ID", unique=true, nullable=false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="FirstName")
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name="LastName")
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name="Address")
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name="Birthday")
public String getBirthday() {
return this.birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
// public String addEntry(){
// if (firstName != null && lastName != null && birthday != null && address != null)
// return "";
// else
// return "";
// }
}
Related
I am trying to make a spring-hibernate application but I am getting this error
Request processing failed; nested exception is org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
I know this error comes when it tries to find getters and setters and couldn't get them. But i checked my getters and setters properly they are correct.
Please help me with this.
My Structure is like this
And code is
Employee.java
package com.wipro.config;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="empdata")
public class Employee {
#Id
private String empname;
#Column(name="designation",length=15)
private String designation;
#Column(name="email",length=25)
private String email;
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
EmployeeDao.java
package com.wipro.config;
import java.io.File;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class EmployeeDao {
private SessionFactory factory;
private Session session;
private Transaction t;
public EmployeeDao() {
}
public void saveData(Employee e) {
factory =new Configuration().configure(new File("F:/Wipro teachings/springg/crud/src/main/java/com/wipro/config/hibernate.cfg.xml")).buildSessionFactory();
session=factory.openSession();
t=session.beginTransaction();
session.save(e);
t.commit();
}
}
ControllerDemo.java
package com.wipro.controller;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.wipro.config.Employee;
import com.wipro.config.EmployeeDao;
#Controller
public class ControllerDemo {
private ApplicationContext conn;
public ControllerDemo() {
}
#RequestMapping("/home")
public String view1() {
return "home";
}
#RequestMapping("/register")
public String view2(Model m) {
conn=new ClassPathXmlApplicationContext("ApplicationContext.xml");
Employee emp=conn.getBean("info",Employee.class);
m.addAttribute("bean",emp);
return "register";
}
#RequestMapping("/store")
public String view3(#ModelAttribute("bean") Employee e,Model m) {
conn=new ClassPathXmlApplicationContext("ApplicationContext.xml");
EmployeeDao obj=conn.getBean("dao",EmployeeDao.class);
obj.saveData(e);
m.addAttribute("msg","Record Inserted Successfully");
return "register";
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">Musu</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#Localhost:1521:orcl</property>
<property name="hibernate.connection.username">sys as sysdba</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle8iDialect</property>
<property name="dialect">org.hibernate.dialect.Oracle8iDialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<mapping class="com.wipro.config.Employee"/>
</session-factory>
</hibernate-configuration>
ApplicationContext.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="info" class="com.wipro.config.Employee"></bean>
<bean id="dao" class="com.wipro.config.EmployeeDao"></bean>
</beans>
home.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>Insert title here</title>
</head>
<body>
Register
</body>
</html>
register.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%#page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Register Page</h1>
<form:form action="store" method="post" modelAttribute="bean">
Enter name=<form:input path="empname"/><br><br>
Enter designation=<form:input path="designation"/><br><br>
Enter email=<form:input path="email"/><br><br>
<input type="submit" value="register">
</form:form>
<br>
<h2>${msg}</h2>
</body>
</html>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.wipro"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<bean id="vr" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
<html>
<body>
<h2>Hello World!</h2>
Home
</body>
</html>
I solved this issue by adding a no argument constractor. If you are using Lombok, you only need to add #NoArgsConstructor annotation:
#AllArgsConstructor
#NoArgsConstructor
#Getter
#ToString
#EqualsAndHashCode
public class User {
private Long userId;
private String shortName;
}
I am trying to make simple validation form using Hibernate Validator. I have two fields in my Customer class, and i want one of them to be required (lastName).
The point is that even when im not filling this field I am not getting error message and BindingResult does not contain any errors. Is there anything im missing in my code?
Here is my Customer class snippet.
public class Customer {
private String firstName;
#NotNull(message = "is required")
#Size(min = 1, message = "is required")
private String lastName;
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Here is Controller
#Controller
#RequestMapping("/customer")
public class CustomerController {
//adding new customer to model
#RequestMapping("/showForm")
public String showForm(Model theModel){
theModel.addAttribute("customer", new Customer());
return "customer-form";
}
//Validating passed customer attribute/object
//Biding result object holds validation results
#RequestMapping("/processForm")
public String processForm(
#Valid #ModelAttribute("customer") Customer theCustomer, BindingResult theBindingResult) {
if (theBindingResult.hasErrors()){
return "customer-form";
}
return "customer-confirmation";
}
}
EDIT: form code:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Customer Registration Form</title>
</head>
<body>
<style>
.error{color: red}
</style>
<i> Fill out the form. Asteriks (*) means required. </i>
<br><br>
<form:form action="processForm" modelAttribute="customer">
First name: <form:input path="firstName" />
<br><br>
Last name (*): <form:input path="lastName"/>
<form:errors path="lastName" cssClass="error" />
<input type="submit" value="Submit"/>
</form:form>
</body>
</html>
EDIT 2:
I added to classpath validation-api.jar (contains the abstract API and the annotation scanner).
Also inserted #InitBinnder just to make sure that empty form field will always be null not empty String.
#InitBinder
public void initBinder(WebDataBinder dataBinder) {
StringTrimmerEditor stringTrimmerEditor = new StringTrimmerEditor(true);
dataBinder.registerCustomEditor(String.class, stringTrimmerEditor);
}
But it still seems that those annotations never get triggered at all
EDIT 3: After calling validator on Entity I am getting error:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.NoProviderFoundException: Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
although i have added it to classpath
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
validator.validate(theCustomer);
EDIT 4: Adding Spring Configuration files:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>mvc-validation-demo</display-name>
<!-- Spring MVC Configs -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-validation-demo.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
mvc-validation-demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/">
<context:component-scan base-package="com.lobo.mvc" />
<mvc:annotation-driven/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
EDIT 5: According to what #eis said i added to my mvc-validation-demo.xml:
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
And i also have Hibernate Validator in my classpath:
Classpath
but the error still remains
Deleteing .idea , clearing cache and new configuration did the job for me. It seems that somehow it didn't saw hibernate-validator.jar.
Thank you to everyone who contributed.
I am novice user to spring. I have tried to code the below program however it is giving 404 error. I am unable to track where the exact error is
throwing HTTP Status 404 - /submitAdmissionForm.html.
HTTP Status 404 - /submitAdmissionForm.html
type Status report
message /submitAdmissionForm.html
description The requested resource is not available.
Apache Tomcat/8.0.28
my files:
welcome page - index.jsp
<html>
<body>
<h3> STUDENT ADMISSION FORM FOR ENGINEERING COURSES</h3>
<form action="/submitAdmissionForm.html" method="post">
Student's Name : <input type="text" name="studentName" />
Student's Hobby :<input type="text" name="studentHobby" />
Student's Mobile :<input type="text" name="studentMobile" />
Student's DOB :<input type="text" name="studentDOB" />
Student's Skills set
<select name="studentSkills" >
<option value="Java Core">Java Core</option>
<option value="Spring Core">Spring Core</option>
<option value="Spring MVC">Spring MVC</option>
</select>
Student's Address :
country: <input type="text" name="studentAddress.country"/>
city: <input type="text" name="studentAddress.city" />
street: <input type="text" name="studentAddress.street" />
pincode:<input type="text" name="studentAddress.pincode" />
<input type="submit" value="Submit this form by clicking here" />
</form>
</body>
</html>
descriptor
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>praygod</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>student</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>student</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
student-servlet.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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.gappu.student" />
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
Controller.java
package com.gappu.student;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class studentcontroller {
#RequestMapping(value="/submitAdmissionForm.html", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm() {
ModelAndView model1 = new ModelAndView();
model1.setViewName("AdmissionSuccess");
return model1;
}
}
here is my success page
AdmissionSuccess.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>Insert title here</title>
</head>
<body>
Hello there
</body>
</html>
when I try running this program it gives me error as 404 suggested URL is not present.
I think that the problem is that your project doesn't include all the libraries. so If you'are using Eclipse and Maven go to
Project Properties -> Deployment Assembly -> Add -> Java Build Path Entries -> Maven Dependencies.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>HelloWorldWebApp</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
messages.properties
NotEmpty.student.studentName={0} can't be empty
Pattern.student.studentName=Number is not allowed for {0}
Size.student.studentName={0} field is between {2} and {1}
NotEmpty.student.gender=Please select gender {0}
NotNull.student.technology=Select at least one technology
Size.student.technology=Select at least one {0}
NotEmpty.student.city=Please select {0}
NotEmpty.student.email={0} can't be empty
Email.student.email=Please enter valid {0}
NotEmpty.student.password={0} can't be empty
NotNull.student.phone={0} no can't be empty
Min.student.phone=Please enter valid {0}
NotEmpty.studentCredential.email={0} can't be empty
Email.studentCredential.email=Please enter valid {0}
NotEmpty.studentCredential.password={0} can't be empty
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.infotech.controller"></context:component-scan>
<context:component-scan base-package="com.infotech.service.impl"></context:component-scan>
<context:component-scan base-package="com.infotech.dao.impl"></context:component-scan>
<context:component-scan base-package="com.infotech.util"></context:component-scan>
<mvc:resources mapping="/image/**" location="/image/" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver.class.name}"></property>
<property name="url" value="${db.url}"></property>
<property name="username" value="${db.username}"></property>
<property name="password" value="${db.password}"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<array>
<value>com.infotech.model.Student</value>
</array>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<array>
<value>/WEB-INF/database.properties</value>
</array>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages"></property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="20848820" />
</bean>
</beans>
database.properties
driver.class.name=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/da
db.username=root
db.password=root
view folder
home.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee Management Screen</title>
</head>
<body>
<div align="center">
<h1>Employee List</h1>
<h3>
New Employee
</h3>
<table border="1">
<tr>
<th>Name</th>
<th>Email</th>
<th>Address</th>
<th>Telephone</th>
<th>Action</th>
<th>Action</th>
<th>Action</th>
<th>Action</th>
</tr>
<c:forEach var="student" items="${listEmployee}">
<tr>
<td>${student.studentName}</td>
<td>${student.gender}</td>
<td>${student.technology}</td>
<td>${student.city}</td>
<td>${student.email}</td>
<td>${student.password}</td>
<td>${student.phone}</td>
<td>${student.image}</td>
<td>Edit
Delete</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
register.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!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>Registration Page</title>
<style type="text/css">
.error {
color: red;
}
</style>
</head>
<body>
<h3 align="center">${headerMessage}</h3>
<form:form action="registerSuccess"
method="post" modelAttribute="student" enctype="multipart/form-data">
<table align="center">
<caption align="top">Student registration form</caption>
<tr>
<td>Enter Email:</td>
<td><form:input path="email" /></td>
<td><form:errors path="email" cssClass="error"/></td>
</tr>
<tr>
<td>Enter Password:</td>
<td><form:password path="password"/></td>
<td><form:errors path="password" cssClass="error"/></td>
</tr>
<tr>
<td>Enter your Name:</td>
<td><form:input path="studentName"/></td>
<td><form:errors path="studentName" cssClass="error"/></td>
</tr>
<tr>
<td>Enter Phone No:</td>
<td><form:input path="phone"/></td>
<td><form:errors path="phone" cssClass="error"/></td>
</tr>
<tr>
<td>Gender:</td>
<td><form:radiobutton path="gender" value="Male" label="Male" />
<form:radiobutton path="gender" value="Female" label="Female" /></td>
<td><form:errors path="gender" cssClass="error" /></td>
</tr>
<tr>
<td>Select Technology:</td>
<td><form:select path="technology">
<form:options items="${technologyList}" />
</form:select></td>
<td><form:errors path="technology" cssClass="error" /></td>
</tr>
<tr>
<td>Select city:</td>
<td><form:select path="city">
<form:options items="${citesList}" />
</form:select></td>
<td><form:errors path="city" cssClass="error" /></td>
</tr>
<td><input type="submit" value="Register"></td>
</tr>
</table>
</form:form>
<br>
VewAll
</body>
</html>
welcome.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>Welcome Page</title>
</head>
<body>
<h3 align="right">Back</h3>
<h2 align="center">${headerMessage}</h2>
<h3 align="center">You have registered with following Info::::</h3>
<table align="center" border="5px">
<tr>
<td>Student email:</td>
<td>${student.email}</td>
</tr>
<tr>
<td>Student Name:</td>
<td>${student.studentName}</td>
</tr>
<tr>
<td>Student Phone:</td>
<td>${student.phone}</td>
</tr>
<tr>
<td>Student Gender</td>
<td>${student.gender}</td>
</tr>
<tr>
<td>Selected Technology:</td>
<td>${student.technology}</td>
</tr>
<tr>
<td>City</td>
<td>${student.city}</td>
</tr>
<tr>
<td>City</td>
<td>${student.image}</td>
</tr>
</table>
</body>
</html>
package com.infotech.dao;
import com.infotech.model.Student;
import java.util.List;
public interface StudentDAO {
public void addEmployee(Student student);
public List<Student> getAllStudent();
public void deleteStudent(Integer id);
public Student updateStudent(Student student);
public Student getStudent(int id);
}
package com.infotech.dao.impl;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.infotech.dao.StudentDAO;
import com.infotech.model.Student;
#Repository
public class StudentDAOImpl implements StudentDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public void addEmployee(Student student) {
sessionFactory.getCurrentSession().saveOrUpdate(student);
}
#Override
#SuppressWarnings("unchecked")
public List<Student> getAllStudent() {
// TODO Auto-generated method stub
return sessionFactory.getCurrentSession().createQuery("from Student").list();
}
#Override
public void deleteStudent(Integer id) {
// TODO Auto-generated method stub
Student student=(Student) sessionFactory.getCurrentSession().load(Student.class, id);
if (null != student) {
this.sessionFactory.getCurrentSession().delete(student);
}
}
#Override
public Student updateStudent(Student student) {
sessionFactory.getCurrentSession().update(student);
return student ;
}
#Override
public Student getStudent(int id) {
// TODO Auto-generated method stub
return (Student) sessionFactory.getCurrentSession().get(
Student.class, id);
}
}
package com.infotech.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
#Table(name = "student_table")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#NotEmpty
#Pattern(regexp="[^0-9]+")
#Size(min=6,max=20)
#Column(name = "student_name")
private String studentName;
#NotEmpty
#Column(name = "gender")
private String gender;
#Size(min=1)
#NotNull
#Column(name = "technology")
private String technology;
#NotEmpty
#Column(name = "city")
private String city;
#NotEmpty
#Email
#Column(name = "email")
private String email;
#NotEmpty
#Column(name = "password")
private String password;
#NotNull
#Min(value = 1000000000)
#Column(name = "phone")
private Long phone;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setPhone(Long phone) {
this.phone = phone;
}
public Long getPhone() {
return phone;
}
public String getTechnology() {
return technology;
}
public void setTechnology(String technology) {
this.technology = technology;
}
}
package com.infotech.service;
import com.infotech.model.Student;
import java.util.List;
public interface StudentService {
public void addStudent(Student student);
public List<Student> getAllStudent();
public void deleteStudent(Integer id);
public Student getStudent(int id);
public Student updateEmployee(Student student);
}
package com.infotech.service.impl;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.infotech.dao.StudentDAO;
import com.infotech.model.Student;
import com.infotech.service.StudentService;
#Service
#Transactional
public class StudentServiceImpl implements StudentService {
#Autowired
private StudentDAO studentdao;
#Override
public void addStudent(Student student) {
// TODO Auto-generated method stub
studentdao.addEmployee(student);
}
#Override
#Transactional
public List<Student> getAllStudent() {
// TODO Auto-generated method stub
return studentdao.getAllStudent();
}
#Override
#Transactional
public void deleteStudent(Integer id) {
// TODO Auto-generated method stub
studentdao.deleteStudent(id);
}
#Override
#Transactional
public Student getStudent(int id) {
// TODO Auto-generated method stub
return studentdao.getStudent(id);
}
#Override
#Transactional
public Student updateEmployee(Student student) {
// TODO Auto-generated method stub
return studentdao.updateStudent(student);
}
}
package com.infotech.controller;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
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.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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.infotech.model.Student;
import com.infotech.service.StudentService;
#Controller
public class MyController {
#Autowired
private StudentService studentService;
public static String uploadDirectory = System.getProperty("user.dir")+"/uploads";
#RequestMapping(value = {"/","/register"} ,method=RequestMethod.GET)
public String registerPage(Model model){
model.addAttribute("student", new Student());
return "register";
}
#RequestMapping(value ="/registerSuccess" ,method=RequestMethod.POST)
public ModelAndView registerSuccess(#Valid #ModelAttribute("student") Student student,BindingResult bindingResult ){
if(bindingResult.hasErrors()){
return new ModelAndView("register");
}
studentService.addStudent(student);
ModelAndView modelAndView = new ModelAndView("welcome");
modelAndView.addObject("student", student);
return modelAndView;
}
#ModelAttribute
public void headerMessage(Model model){
model.addAttribute("headerMessage", "Welcome to Starve Technology");
List<String> techList = new ArrayList<>();
techList.add("Hibernate");
techList.add("Spring");
techList.add("JSP");
techList.add("Servlet");
techList.add("Struts");
List<String> citesList = new ArrayList<>();
citesList.add("Pune");
citesList.add("Chennai");
citesList.add("Delhi");
citesList.add("Other");
model.addAttribute("technologyList", techList);
model.addAttribute("citesList", citesList);
}
#RequestMapping(value = "/home" )
public ModelAndView vewPage(ModelAndView model){
List<Student> liststudents=studentService.getAllStudent();
model.addObject("listEmployee", liststudents);
model.setViewName("home");
return model;
}
#RequestMapping(value = "/editEmployee", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) {
int id = Integer.parseInt(request.getParameter("id"));
Student student = studentService.getStudent(id);
ModelAndView model = new ModelAndView("register");
model.addObject("student", student);
return model;
}
#RequestMapping(value = "/deleteEmployee", method = RequestMethod.GET)
public ModelAndView deleteEmployee(HttpServletRequest request) {
int id = Integer.parseInt(request.getParameter("id"));
studentService.deleteStudent(id);
return new ModelAndView("redirect:/");
}
}
I am newly working on spring mvc,I am using "spring in practice" book and this is the first mvc programme which I tried and I am getting the below error
WARN PageNotFound:1101 - No mapping found for HTTP request with URI [/MVC_BOOK_Annotation/main/list.do] in DispatcherServlet with name 'main'
below is my code
RosterController
package com.web;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.model.Member;
#Controller
public final class RosterController {
private List<Member> members = new ArrayList<Member>();
public RosterController() {
members.add(new Member("John", "Lennon"));
members.add(new Member("Paul", "McCartney"));
members.add(new Member("George", "Harrison"));
members.add(new Member("Ringo", "Starr"));
}
#RequestMapping
public void list(Model model) {
model.addAttribute(members);
}
#RequestMapping
public void member(#RequestParam("id") Integer id, Model model) {
model.addAttribute(members.get(id));
}
}
Member.java
package com.model;
public class Member {
private String firstName;
private String lastName;
public Member() {
}
public Member(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String toString() {
return firstName + " " + lastName;
}
}
main-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean class="com.web.RosterController" name="/roster/"></bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp">
</bean>
</beans>
web.xml
<web-app id="AppName" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>main</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/main/*</url-pattern>
</servlet-mapping>
</web-app>
list.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>
<ul>
<c:forEach var="member" items="${memberList}" varStatus="status">
<li><a href="member.do?id=${status.index}"> <c:out
value="${member}"></c:out>
</a></li>
</c:forEach>
</ul>
</body>
</html>
member.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>
<h1>Member: ${member}</h1>
<p>
Back
</p>
</body>
</html>
the above code is almost similar to the book code but still I am unable to find where is the mistake.I attached an #RequestMapping attribute to the list() and member() methods,This identifies them as request-servicing methods.Below is my project structure screenshot.
You need to add * after /roster/ in your bean definition.
Try following setting:
<bean class="com.web.RosterController" name="/roster/*"></bean>
instead of
<bean class="com.web.RosterController" name="/roster/"></bean>
And access /MVC_BOOK_Annotation/main/roster/list.do
You are using #RequestMapping without value-parameter, that way requests to your path wont get catched.
How to use #requestMapping headers?
I highly recommend reading all of this, without that knowledge you wont get far ...
You are using annotations to search your controller. You should be using the below code.
context:component-scan base-package="com"
tag in your Main-servlet
You need to add the below mapping:
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<!-- <resources mapping="/resources/**" location="/resources/" /> -->
<!-- <mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/public-web-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>
<!-- View Handler -->
<beans:bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<beans:property name="favorPathExtension" value="true"/>
<beans:property name="mediaTypes">
<beans:map>
<beans:entry key="xml" value="text/xml"/>
<beans:entry key="json" value="application/json"/>
<beans:entry key="html" value="text/html"/>
<beans:entry key="less" value="text/html"/>
</beans:map>
</beans:property>
<beans:property name="viewResolvers">
<beans:list>
<beans:bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<beans:property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView"/>
</beans:bean>
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/"/>
</beans:bean>
</beans:list>
</beans:property>
</beans:bean>
I am new to spring, was working on an example. The example shows how to add data to table using hibernate and list it also, I tried to add extra delete option but its updating record instead. I will post complete code below. ( 2 ) I develop simple web apps using jsp and servlets and lots of jquery ajax, I want to use ajax also with spring, will I be able to code the same way or its something different which i have to learn. To be frank I am scared after seeing the spring pattern.. :).
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/production"/>
<property name="username" value="tpsl_admin"/>
<property name="password" value="admin"/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.org.domain.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="myUserDAO" class="com.org.dao.UserDAOImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<bean name="/user/*.htm" class="com.org.web.UserController" >
<property name="userDAO" ref="myUserDAO" />
</bean>
<!--
The index controller.
-->
<bean name="indexController" class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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-app_3_0.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
UserDAO.java
package com.org.dao;
import com.org.domain.User;
import java.util.List;
public interface UserDAO {
public void saveUser(User user) ;
public List<User> listUser() ;
public void deleteUser(User user) ;
}
UserDAOImpl.java
package com.org.dao;
import com.org.domain.User;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class UserDAOImpl implements UserDAO {
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
#Override
public void saveUser(User user) {
hibernateTemplate.saveOrUpdate(user);
}
#Override
#SuppressWarnings("unchecked")
public List<User> listUser() {
return hibernateTemplate.find("from User");
}
#Override
public void deleteUser(User user) {
hibernateTemplate.delete(user);
}
}
User.java
package com.org.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="USER")
public class User {
private Long id;
private String name;
private String password;
private String gender;
private String country;
private String aboutYou;
private String[] community;
private Boolean mailingList;
#Id
#GeneratedValue
#Column(name="USER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name="USER_NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="USER_PASSWORD")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name="USER_GENDER")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Column(name="USER_COUNTRY")
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Column(name="USER_ABOUT_YOU")
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}
#Column(name="USER_COMMUNITY")
public String[] getCommunity() {
return community;
}
public void setCommunity(String[] community) {
this.community = community;
}
#Column(name="USER_MAILING_LIST")
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}
}
UserController.java
package com.org.web;
import com.org.dao.UserDAO;
import com.org.domain.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
#RequestMapping(params = "add", method = RequestMethod.POST)
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response, User user) throws Exception {
userDAO.saveUser(user);
return new ModelAndView("redirect:list.htm");
}
#RequestMapping(params = "delete", method = RequestMethod.POST)
#Transactional
public ModelAndView delete(HttpServletRequest request,
HttpServletResponse response, User user) throws Exception {
userDAO.deleteUser(user);
return new ModelAndView("redirect:list.htm");
}
public ModelAndView list(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelMap modelMap = new ModelMap();
modelMap.addAttribute("userList", userDAO.listUser());
modelMap.addAttribute("user", new User());
return new ModelAndView("userForm", modelMap);
}
}
ok thats all with the code, the ide i am using is netbeans, sprinf ver is 3.1.1. Hibernate 3.0. Some one please show me where i need to change I am trying since 2 days with fail. Also explain my own code if possible I have many doubts.
Thankyou
userForm.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<style type="text/css">
.even {
background-color: silver;
}
</style>
<title>Registration Page</title>
</head>
<body>
<form:form action="add.htm" commandName="user" method="post">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobutton path="gender" value="M" label="M" />
<form:radiobutton path="gender" value="F" label="F" /></td>
</tr>
<tr>
<td>Country :</td>
<td><form:select path="country">
<form:option value="0" label="Select" />
<form:option value="India" label="India" />
<form:option value="USA" label="USA" />
<form:option value="UK" label="UK" />
</form:select></td>
</tr>
<tr>
<td>About you :</td>
<td><form:textarea path="aboutYou" /></td>
</tr>
<tr>
<td>Community :</td>
<td><form:checkbox path="community" value="Spring" label="Spring" />
<form:checkbox path="community" value="Hibernate" label="Hibernate" />
<form:checkbox path="community" value="Struts" label="Struts" />
</td>
</tr>
<tr>
<td></td>
<td><form:checkbox path="mailingList" label="Would you like to join our mailinglist?" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="add" value="Register"></td>
<td colspan="2"><input type="button" name="delete" value="Delete"></td>
</tr>
</table>
</form:form>
<c:if test="${fn:length(userList) > 0}">
<table cellpadding="5">
<tr class="even">
<th>ID</th>
<th>Name</th>
<th>Gender</th>
<th>Country</th>
<th>About You</th>
<th>Mailing List</th>
<th>Community</th>
</tr>
<c:forEach items="${userList}" var="user" varStatus="status">
<tr class="<c:if test="${status.count % 2 == 0}">even</c:if>">
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.gender}</td>
<td>${user.country}</td>
<td>${user.aboutYou}</td>
<td>${user.mailingList}</td>
<td>${user.community}</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
In your dispatcherservlet.xml please comment the below line
<prop key="hibernate.hbm2ddl.auto">create</prop>
as everytime when you restart your server, it will auto create the table when server starts. Please check the mapping correctly for deleting the user and have print or breakpoints and debug the issue, seeing your code hibernateTemplate.delete(user) should work fine.