New to the world of struts2 and hibernate. I designed a form to perform CRUD operations. Projects runs without any errors... But when I submit the form values are not inserted in mySQL database. Another issue - existing values from mySQL table are not populated in datatable on jsp form. Following is code from jsp and other class files. I need to understand if I've missed something here
<%--
Document : ctsFrmCaseCategory
Created on : Nov 17, 2015, 9:30:00 PM
Author : nishad
--%>
<%# 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">
<%#taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
<s:head />
<style type="text/css">
#import url(style.css);
</style>
</head>
<body>
<s:form action="saveOrUpdateCategory">
<s:push value="category">
<s:hidden name="ccg_ID" />
<s:textfield name="ccg_CategoryName" label="Category Name" />
<s:textfield name="ccg_Description" label="Description" />
<s:checkbox name="ccg_DeleteFlag" label="Delete User?" />
<s:checkbox name="ccg_ActiveFlag" label="Active User?" />
<s:hidden name="ccg_CreateDate" />
<s:hidden name="ccg_CreateUser" />
<s:hidden name="ccg_ModifyDate" />
<s:hidden name="ccg_ModifyUser" />
<s:submit />
</s:push>
</s:form>
<s:if test="categoryList.size() > 0">
<div class="content">
<table class="userTable" cellpadding="5px">
<tr class="even">
<th>Category Name</th>
<th>Description</th>
<th>Delete Flag</th>
<th>Active Flag</th>
<th>Create Date</th>
<th>Create User</th>
<th>Modify Date</th>
<th>Modify User</th>
</tr>
<s:iterator value="categoryList" status="categoryStatus">
<tr
class="<s:if test="#categoryStatus.odd == true ">odd</s:if><s:else>even</s:else>">
<td><s:property value="ccg_CategoryName" /></td>
<td><s:property value="ccg_Description" /></td>
<td><s:property value="ccg_DeleteFlag" /></td>
<td><s:property value="ccg_ActiveFlag" /></td>
<td><s:property value="ccg_CreateDate" /></td>
<td><s:property value="ccg_CreateUser" /></td>
<td><s:property value="ccg_ModifyDate" /></td>
<td><s:property value="ccg_ModifyUser" /></td>
<td><s:url id="editURL" action="editCategory">
<s:param name="ccg_ID" value="%{ccg_ID}"></s:param>
</s:url> <s:a href="%{editURL}">Edit</s:a></td>
<td><s:url id="deleteURL" action="deleteCategory">
<s:param name="ccg_ID" value="%{ccg_ID}"></s:param>
</s:url> <s:a href="%{deleteURL}">Delete</s:a></td>
</tr>
</s:iterator>
</table>
</div>
</s:if>
</body>
</html>
CategotyDAO.java code ---
package com.cts.dao;
import java.util.List;
import com.cts.domain.Category;
public interface CategoryDAO {
public void saveOrUpdateCategory(Category category);
public List<Category> listCategory();
public Category listCategoryById(Long categoryId);
public void deleteCategory(Long categoryId);
}
CategoryDAOImpl.java code ---
package com.cts.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.cts.domain.Category;
public class CategoryDAOImpl implements CategoryDAO {
#SessionTarget
Session session;
#TransactionTarget
Transaction transaction;
/**
* Used to save or update a category.
*/
public void saveOrUpdateCategory(Category category) {
try {
session.saveOrUpdate(category);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to delete a category.
*/
public void deleteCategory(Long categoryId) {
try {
Category category = (Category) session.get(Category.class, categoryId);
session.delete(category);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to list all the categorys.
*/
#SuppressWarnings("unchecked")
public List<Category> listCategory() {
List<Category> courses = null;
try {
courses = session.createQuery("from Category").list();
} catch (Exception e) {
e.printStackTrace();
}
return courses;
}
/**
* Used to list a single category by Id.
*/
public Category listCategoryById(Long categoryId) {
Category category = null;
try {
category = (Category) session.get(Category.class, categoryId);
} catch (Exception e) {
e.printStackTrace();
}
return category;
}
}
CategoryAction.java code ---
package com.cts.web;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.cts.dao.CategoryDAO;
import com.cts.dao.CategoryDAOImpl;
import com.cts.domain.Category;
public class CategoryAction extends ActionSupport implements ModelDriven<Category> {
private static final long serialVersionUID = -6659925652584240539L;
private Category category = new Category();
private List<Category> categoryList = new ArrayList<Category>();
private CategoryDAO categoryDAO = new CategoryDAOImpl();
public Category getModel() {
return category;
}
/**
* To save or update category.
* #return String
*/
public String saveOrUpdate()
{
categoryDAO.saveOrUpdateCategory(category);
return SUCCESS;
}
/**
* To list all categories.
* #return String
*/
public String list()
{
categoryList = categoryDAO.listCategory();
return SUCCESS;
}
/**
* To delete a category.
* #return String
*/
public String delete()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
categoryDAO.deleteCategory(Long.parseLong(request.getParameter("ccg_ID")));
return SUCCESS;
}
/**
* To list a single category by Id.
* #return String
*/
public String edit()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
category = categoryDAO.listCategoryById(Long.parseLong(request.getParameter("ccg_ID")));
return SUCCESS;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public List<Category> getCategoryList() {
return categoryList;
}
public void setCategoryList(List<Category> categoryList) {
this.categoryList = categoryList;
}
}
Category.java code ---
package com.cts.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
#Entity
#Table(name = "cts_mcasecategory")
public class Category {
private Long ccg_ID;
private String ccg_CategoryName;
private String ccg_Description;
private boolean ccg_DeleteFlag;
private boolean ccg_ActiveFlag;
private Date ccg_CreateDate;
private int ccg_CreateUser;
private Date ccg_ModifyDate;
private int ccg_ModifyUser;
#Id
#GeneratedValue
#Column(name = "ccg_ID")
public Long getCcg_ID() {
return ccg_ID;
}
public void setCcg_ID(Long ccg_ID) {
this.ccg_ID = ccg_ID;
}
#Column(name = "ccg_CategoryName")
public String getCcg_CategoryName() {
return ccg_CategoryName;
}
public void setCcg_CategoryName(String ccg_CategoryName) {
this.ccg_CategoryName = ccg_CategoryName;
}
#Column(name = "ccg_Description")
public String getCcg_Description() {
return ccg_Description;
}
public void setCcg_Description(String ccg_Description) {
this.ccg_Description = ccg_Description;
}
#Column(name = "ccg_DeleteFlag")
public boolean isCcg_DeleteFlag() {
return ccg_DeleteFlag;
}
public void setCcg_DeleteFlag(boolean ccg_DeleteFlag) {
this.ccg_DeleteFlag = ccg_DeleteFlag;
}
#Column(name = "ccg_ActiveFlag")
public boolean isCcg_ActiveFlag() {
return ccg_ActiveFlag;
}
public void setCcg_ActiveFlag(boolean ccg_ActiveFlag) {
this.ccg_ActiveFlag = ccg_ActiveFlag;
}
#Column(name = "ccg_CreateDate")
public Date getCcg_CreateDate() {
return ccg_CreateDate;
}
public void setCcg_CreateDate(Date ccg_CreateDate) {
this.ccg_CreateDate = ccg_CreateDate;
}
#Column(name = "ccg_CreateUser")
public int getCcg_CreateUser() {
return ccg_CreateUser;
}
public void setCcg_CreateUser(int ccg_CreateUser) {
this.ccg_CreateUser = ccg_CreateUser;
}
#Column(name = "ccg_ModifyDate")
public Date getCcg_ModifyDate() {
return ccg_ModifyDate;
}
public void setCcg_ModifyDate(Date ccg_ModifyDate) {
this.ccg_ModifyDate = ccg_ModifyDate;
}
#Column(name = "ccg_ModifyUser")
public int getCcg_ModifyUser() {
return ccg_ModifyUser;
}
public void setCcg_ModifyUser(int ccg_ModifyUser) {
this.ccg_ModifyUser = ccg_ModifyUser;
}
}
Struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="example.xml"/>
<!-- Configuration for the default package. -->
<package name="default" extends="struts-default">
<action name="saveOrUpdateCategory" method="saveOrUpdate" class="com.cts.web.CategoryAction">
<result name="success" type="redirect">listCategory</result>
</action>
<action name="listCategory" method="list" class="com.cts.web.CategoryAction">
<result name="success">/ctsFrmCaseCategory.jsp</result>
</action>
<action name="editCategory" method="edit" class="com.cts.web.CategoryAction">
<result name="success">/ctsFrmCaseCategory.jsp</result>
</action>
<action name="deleteCategory" method="delete" class="com.cts.web.CategoryAction">
<result name="success" type="redirect">listCategory</result>
</action>
</package>
Related
This is my JSP file
<html>
<head>
<title>Todo's for ${name}</title>
</head>
<body>
<h1>Your ToDo's</h1>
<table>
<caption>Your Todo's are as follows:</caption>
<thead>
<tr>
<th>Description</th>
<th>Target Date</th>
<th>Is it completed?</th>
</tr>
</thead>
<tbody>
<th:block th:each="todo : ${todos}">
<tr>
<td th:text="${todo.desc}"></td>
<td th:text="${todo.targetDate}"></td>
<td th:text="${todo.done}"></td>
</tr>
</th:block>
</tbody>
</table>
<br/>
Add Todo
</body>
</html>
This is my TodoService.java file
package com.example.springboot.demo.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.springframework.stereotype.Service;
import com.in28minutes.springboot.web.model.Todo;
#Service
public class TodoService {
private static List<Todo> todos = new ArrayList<Todo>();
private static int todoCount = 3;
static {
todos.add(new Todo(1, "Prakriti", "Learn Spring MVC", new Date(),
false));
todos.add(new Todo(2, "Prakriti", "Learn Struts", new Date(), false));
todos.add(new Todo(3, "Prakriti", "Learn Hibernate", new Date(),
false));
}
public List<Todo> retrieveTodos(String user) {
List<Todo> filteredTodos = new ArrayList<Todo>();
for (Todo todo : todos) {
if (todo.getUser().equals(user)) {
filteredTodos.add(todo);
}
}
return filteredTodos;
}
public void addTodo(String name, String desc, Date targetDate,
boolean isDone) {
todos.add(new Todo(++todoCount, name, desc, targetDate, isDone));
}
public void deleteTodo(int id) {
Iterator<Todo> iterator = todos.iterator();
while (iterator.hasNext()) {
Todo todo = iterator.next();
if (todo.getId() == id) {
iterator.remove();
}
}
}
}
I have three values in the table but it doesn't retrieve them, can't understand why I have used the thymeleaf block properly only. Below is my TodoController.java file.
package com.example.springboot.demo.controller;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.example.springboot.demo.service.LoginService;
import com.example.springboot.demo.service.TodoService;
#Controller
#SessionAttributes("name")
public class TodoController {
#Autowired
TodoService service;
#RequestMapping(value="/list-todos", method=RequestMethod.GET)
public String showTodosList(ModelMap model) {
String name=(String)model.get("name");
model.put("todos",service.retrieveTodos(name));
return "list-todos";
}
#RequestMapping(value="/add-todos", method=RequestMethod.GET)
public String showaddTodoPage(ModelMap model) {
return "add-todos";
}
#RequestMapping(value="/add-todos", method=RequestMethod.POST)
public String addTodos(ModelMap model, #RequestParam String desc) {
service.addTodo((String)model.get("name"), desc, new Date(), false);
return "redirect:/list-todos";
}
}
This is my Todo.java
package com.in28minutes.springboot.web.model;
import java.util.Date;
public class Todo {
private int id;
private String user;
private String desc;
private Date targetDate;
private boolean isDone;
public Todo(int id, String user, String desc, Date targetDate,
boolean isDone) {
super();
this.id = id;
this.user = user;
this.desc = desc;
this.targetDate = targetDate;
this.isDone = isDone;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Date getTargetDate() {
return targetDate;
}
public void setTargetDate(Date targetDate) {
this.targetDate = targetDate;
}
public boolean isDone() {
return isDone;
}
public void setDone(boolean isDone) {
this.isDone = isDone;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Todo other = (Todo) obj;
if (id != other.id) {
return false;
}
return true;
}
#Override
public String toString() {
return String.format(
"Todo [id=%s, user=%s, desc=%s, targetDate=%s, isDone=%s]", id,
user, desc, targetDate, isDone);
}
}
Output:
Please let me know what's needed to be done for the values to be displayed in the table.
Try using,
<tr th:each="todo : ${todos}">
<td th:text="${todo.desc}"></td>
<td th:text="${todo.targetDate}"></td>
<td th:text="${todo.done}"></td>
</tr>
I am trying to insert the data into database and view the data into crud format. But it shows the error message HTTP Status 404
i have checked the code line by line, there is no error.
but cant display the data into the crud view.
Employee.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>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<h3>Add / Edit Employee!!!</h3>
<form method="post" action="/SpringMVCTutorial/employee.html" commandName="employee">
<div class="table-responsive">
<table class="table table-bordered" style="width: 300px">
<input type="text" name="id" />
<input type="text" name="name" />
<input type="text" name="age" />
<input type="text" name="dept" />
<input class="btn btn-primary btn-sm" type="submit" value="Submit" />
</tr>
</table>
</div>
</form>
<br>
<br>
<h3>List of Employees</h3>
<table class="table table-bordered" style="width: 300px">
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Department</th>
<th>Edit/Delete</th>
</tr>
<c:forEach items="$ {employeeList}" var="employee">
<tr>
<td width="60" align="center">${employee.id}</td>
<td width="60" align="center">${employee.name}</td>
<td width="60" align="center">${employee.age}</td>
<td width="60" align="center">${employee.dept}</td>
<td width="60" align="center">Edit/Delete</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Employee.java
package com.javainterviewpoint;
import java.io.Serializable;
public class Employee implements Serializable
{
private static final long serialVersionUID = -1280037900360314186L;
private Integer id;
private String name;
private Integer age;
private String dept;
public Employee()
{
super();
}
public Employee(Integer id, String name, Integer age, String dept)
{
super();
this.id = id;
this.name = name;
this.age = age;
this.dept = dept;
}
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 Integer getAge()
{
return age;
}
public void setAge(Integer age)
{
this.age = age;
}
public String getDept()
{
return dept;
}
public void setDept(String dept)
{
this.dept = dept;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((dept == null) ? 0 : dept.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (age == null)
{
if (other.age != null)
return false;
} else if (!age.equals(other.age))
return false;
if (dept == null)
{
if (other.dept != null)
return false;
} else if (!dept.equals(other.dept))
return false;
if (id == null)
{
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null)
{
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
#Override
public String toString()
{
return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", dept=" + dept + "]";
}
}
EmployeeController.java
package com.javainterviewpoint;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class EmployeeController
{
#Autowired
private EmployeeDAO employeeDAO;
#RequestMapping(value = "/employee",method=RequestMethod.POST)
public ModelAndView saveEmployee(#ModelAttribute("employee") Employee employee)
{
try
{
if(employeeDAO.getEmployeeById(employee.getId()) != null);
employeeDAO.updateEmployee(employee);
}
catch(EmptyResultDataAccessException e)
{
System.out.println("inside catch");
employeeDAO.saveEmployee(employee);
}
return new ModelAndView("redirect:/employees");
}
#RequestMapping(value = "/edit/{id}")
public ModelAndView editEmployee(#ModelAttribute("employee") Employee employee,#PathVariable("id") int id)
{
ModelAndView model = new ModelAndView("employees");
employee = employeeDAO.getEmployeeById(id);
List<Employee> employeeList = employeeDAO.getAllEmployees();
model.addObject("employee",employee);
model.addObject("employeeList",employeeList);
return model;
}
#RequestMapping(value = "/delete/{id}")
public ModelAndView deleteEmployee(#ModelAttribute("employee") Employee employee,#PathVariable("id") int id)
{
employeeDAO.deleteEmployee(id);
return new ModelAndView("redirect:/employees");
}
#RequestMapping(value = "/employees")
public ModelAndView listEmployees(#ModelAttribute("employee") Employee employee)
{
ModelAndView model = new ModelAndView("employees");
List<Employee> employeeList = employeeDAO.getAllEmployees();
System.out.println(employeeList);
model.addObject("employeeList", employeeList);
return model;
}
}
EmployeeDao.java
package com.javainterviewpoint;
import java.util.List;
public interface EmployeeDAO
{
public void saveEmployee(Employee employee);
public Employee getEmployeeById(int id);
public void updateEmployee(Employee employee);
public void deleteEmployee(int id);
public List<Employee> getAllEmployees();
}
EmployeeDaoImpl.java
package com.javainterviewpoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
#Repository
public class EmployeeDAOImpl implements EmployeeDAO
{
private JdbcTemplate jdbcTemplate;
// JdbcTemplate setter
public void setJdbcTemplate(JdbcTemplate jdbcTemplate)
{
this.jdbcTemplate = jdbcTemplate;
}
// Saving a new Employee
public void saveEmployee(Employee employee)
{
String sql = "insert into employee1 values(?,?,?,?)";
System.out.println("dao called");
jdbcTemplate.update(sql, new Object[]
{ employee.getId(), employee.getAge(), employee.getDept(), employee.getName() });
}
// Getting a particular Employee
public Employee getEmployeeById(int id)
{
String sql = "select * from employee1 where id=?";
Employee employee = (Employee) jdbcTemplate.queryForObject(sql, new Object[]
{ id }, new RowMapper<Employee>()
{
#Override
public Employee mapRow(ResultSet rs, int rowNum) throws SQLException
{
Employee employee = new Employee();
employee.setId(rs.getInt(1));
employee.setAge(rs.getInt(2));
employee.setDept(rs.getString(3));
employee.setName(rs.getString(4));
return employee;
}
});
return employee;
}
// Getting all the Employees
public List<Employee> getAllEmployees()
{
String sql = "select * from employee1";
List<Employee> employeeList = jdbcTemplate.query(sql, new ResultSetExtractor<List<Employee>>()
{
#Override
public List<Employee> extractData(ResultSet rs) throws SQLException, DataAccessException
{
List<Employee> list = new ArrayList<Employee>();
while (rs.next())
{
Employee employee = new Employee();
employee.setId(rs.getInt(1));
employee.setAge(rs.getInt(2));
employee.setDept(rs.getString(3));
employee.setName(rs.getString(4));
list.add(employee);
}
return list;
}
});
return employeeList;
}
// Updating a particular Employee
public void updateEmployee(Employee employee)
{
String sql = "update employee1 set age =?, dept=?,name=? where id=?";
jdbcTemplate.update(sql, new Object[]
{ employee.getAge(), employee.getDept(), employee.getName(), employee.getId() });
}
// Deletion of a particular Employee
public void deleteEmployee(int id)
{
String sql = "delete employee1 where id=?";
jdbcTemplate.update(sql, new Object[]
{ id });
}
}
SpringMVC-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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.javainterviewpoint" />
<bean id="employeeDAOImpl" class="com.javainterviewpoint.EmployeeDAOImpl">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<!-- Database Configurations -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/headway" />
<property name="username" value="root" />
<property name="password" value="toor" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/JSP/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Problem is action attribute has wrong url:
<form method="post" action="/SpringMVCTutorial/employee.html" commandName="employee">
As per controller:
#RequestMapping(value = "/employee",method=RequestMethod.POST)
public ModelAndView saveEmployee(#ModelAttribute("employee") Employee employee)
Your action url must be some what:
<form method="post" action="employee" commandName="employee">
Please tell us which url pattern spring dispatcher servlet is mapped to?
I suppose that your spring dispatcher servlet in web.xml file is mapped to something like this:
<servlet-mapping>
<servlet-name>springdispatcherservlet</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
and since your saveEmployee method based on this line
#RequestMapping(value = "/employee",method=RequestMethod.POST)
is mapped to "/employee", your form in jsp file should be like this:
<form method="post" action="test/employee">
A point here which is worth mentioning is that "test/employee" is a relative address and definitely it is possible to use an absolute one.
just give this a try and let me know the result.
hope it helps.
Hi there,
My task is displaying a list of object from database to JSP. But i don't know why it only show when i run servlet class,while not show anything when i run JSP. First I used setAttribute method to pass the list to JSP and at JSP i use JSTL tags for retriving data. I think everything is ok but don't why it happend like that. Here's my code
Asiakas.java
package Luokat;
public class Asiakas {
private int asiakas_id;
private String nimi;
private int puhelinnumero;
private String spostiosoite;
/**
*
*/
public Asiakas() {
asiakas_id = 0;
nimi= null;
puhelinnumero =0;
spostiosoite = null;
}
/**
* #param asiakas_id
* #param nimi
* #param puhelinnumero
* #param spostiosoite
*/
public Asiakas(int asiakas_id, String nimi, int puhelinnumero,
String spostiosoite) {
super();
this.asiakas_id = asiakas_id;
this.nimi = nimi;
this.puhelinnumero = puhelinnumero;
this.spostiosoite = spostiosoite;
}
public int getAsiakas_id() {
return asiakas_id;
}
public void setAsiakas_id(int asiakas_id) {
this.asiakas_id = asiakas_id;
}
public String getNimi() {
return nimi;
}
public void setNimi(String nimi) {
this.nimi = nimi;
}
public int getPuhelinnumero() {
return puhelinnumero;
}
public void setPuhelinnumero(int puhelinnumero) {
this.puhelinnumero = puhelinnumero;
}
public String getSpostiosoite() {
return spostiosoite;
}
public void setSpostiosoite(String spostiosoite) {
this.spostiosoite = spostiosoite;
}
#Override
public String toString() {
return "Asiakas [asiakas_id=" + asiakas_id + ", nimi=" + nimi
+ ", puhelinnumero=" + puhelinnumero + ", spostiosoite="
+ spostiosoite + "]";
}
}
NaytaAsiakasServlet
package Servletit;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
import DBHoitaja.DBHoitaja;
import Luokat.Asiakas;
/**
* Servlet implementation class NaytaAsiakasServlet
*/
#WebServlet("/NaytaAsiakasServlet")
public class NaytaAsiakasServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public NaytaAsiakasServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
NaytaAsiakasServlet nayta = new NaytaAsiakasServlet();
request.setAttribute("asiakasLista", nayta.findAll());
request.getRequestDispatcher("admin_page.jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public List<Asiakas> findAll(){
List<Asiakas> list = new ArrayList<Asiakas>();
try {
list.add(new Asiakas(0, "Kaísa",0445206766,"kaisaa#haaga-helia.fi"));
list.add(new Asiakas(1, "Kaísa",0445206766,"kaisaa#haaga-helia.fi"));
list.add(new Asiakas(3, "Kaísa",0445206766,"kaisaa#haaga-helia.fi"));
} catch(Exception e){
list =null;
}
return list;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
admin_page.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# 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>Ylläpito Sivu</title>
</head>
<body>
<table border="1" cellpadding="2" cellspacing="2" width="500">
<tr>
<th>Id</th>
<th>Nimi</th>
<th>Puhelin</th>
<th>Sähköposti</th>
</tr>
<c:forEach var="asiakas" items="${asiakasLista}" >
<tr>
<td><c:out value="${asiakas.asiakas_id}" /></td>
<td><c:out value="${asiakas.nimi}" /></td>
<td><c:out value="${asiakas.puhelinnumero}" /></td>
<td><c:out value="${asiakas.spostiosoite}" /></td>
</tr>
</c:forEach>
</table>
</body>
</html>
From your question I can understand that you are totally new to J2EE!! And also you are trying to run the servlet class and JSP, which is not going to work anyway.
Please read the below specified tutorials and have some idea on how run a simple web application.
how to write hello world servlet Example
Sample Code for Hello World:
I'm developing a simple register system that allow users to register. I have the following configuration, entity and service:
persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="pro-jpa" transaction-type="JTA">
<jta-data-source>jdbc/__testPerso</jta-data-source>
<class>com.jules.esiee.entities.Utilisateur</class>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables" />
</properties>
</persistence-unit>
</persistence>
Bean Utilisateur.java
package com.jules.esiee.entities;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.persistence.*;
import com.jules.esiee.dao.UtilisateurDao;
#ManagedBean
#RequestScoped
#Entity
#Table(name="utilisateur")
public class Utilisateur {
#Id
#GeneratedValue( strategy = GenerationType.IDENTITY )
private long id;
#Column(name="nom")
private String nom;
#Column(name="prenom")
private String prenom;
#Column(name="age")
private int age;
#EJB
#Transient
private UtilisateurDao userDao;
public long getId()
{
return id;
}
public void setId(long _id)
{
id = _id;
}
public String getNom()
{
return nom;
}
public void setNom(String _nom)
{
nom = _nom;
}
public String getPrenom()
{
return prenom;
}
public void setPrenom(String _prenom)
{
prenom = _prenom;
}
public int getAge()
{
return age;
}
public void setAge(int _age)
{
age = _age;
}
public void sauvegarde() throws Exception
{
userDao.creer(this);
}
public void validationAge(FacesContext context, UIComponent component, Object convertedValue) throws ValidatorException {
this.age = (int) convertedValue;
if(!testAge())
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Vous êtes mineur",null));
}
}
public String validation()
{
FacesContext facesContext = FacesContext.getCurrentInstance();
if(!this.testAge())
{
facesContext.addMessage("f:age", new FacesMessage(FacesMessage.SEVERITY_ERROR,"Erreur sur l'âge, vous êtes mineur, bande de bouffons", "test"));
return null;
}
else
{
if(!alreadyInDB())
{
//this.sauvegarde();
return "listeUser";
}
else
{
facesContext.addMessage("f:nom", new FacesMessage(FacesMessage.SEVERITY_ERROR,"Utilisateur déjà existant", "test"));
return null;
}
}
}
public boolean alreadyInDB()
{
if(userDao.trouver(this) == null)
{
return false;
}
else
{
return true;
}
}
public boolean testAge()
{
if(this.age < 18) return false;
return true;
}
}
DAO UtilisateurDao.java
package com.jules.esiee.dao;
import java.io.Serializable;
import javax.persistence.*;
import javax.ejb.*;
import com.jules.esiee.entities.Utilisateur;
#Stateless
public class UtilisateurDao implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private static final String JPQL_SELECT_ALREADY = "SELECT u.prenom,u.nom,u.age FROM Utilisateur u WHERE u.prenom=:prenom AND u.nom=:nom AND u.age=:age";
// Injection du manager, qui s'occupe de la connexion avec la BDD
#PersistenceContext( unitName = "pro-jpa" )
private EntityManager em;
// Enregistrement d'un nouvel utilisateur
public void creer( Utilisateur utilisateur ) throws Exception {
try {
em.persist( utilisateur );
} catch ( Exception e ) {
throw new Exception( e );
}
}
// Recherche d'un utilisateur à parter de son adresse email
public Utilisateur trouver( Utilisateur _utilisateur){
Utilisateur utilisateur = null;
Query requete = em.createQuery( JPQL_SELECT_ALREADY );
requete.setParameter( "prenom", _utilisateur.getPrenom());
requete.setParameter("nom", _utilisateur.getNom());
requete.setParameter("age", _utilisateur.getAge());
try {
utilisateur = (Utilisateur) requete.getSingleResult();
} catch ( NoResultException e ) {
return null;
}
return utilisateur;
}
}
There are 2 problems:
When I persist a new user, it doesn't appear in the database. No exception is being thrown here.
When I select an existing user, it throws the following exception:
[Ljava.lang.Object; cannot be cast to com.jules.esiee.entities.Utilisateur
I don't really understand what the method getSingleResult() returns.
First I suggest to separate the Entity from the Managed Bean.The Entity should not know anything about the DAO or the Managed Bean. Secondly try annotate the method 'sauvegarde' in the DAO using #TransactionAttribute(TransactionAttributeType.REQUIRES_NEW).
I am about developing a small application using EJB JPA MySQL netbeans7.2,
so my application has the following goal: get the list of names and their IDs and add other names to the list.
My classes are:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.rachid.entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "employee")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e"),
#NamedQuery(name = "Employee.findById", query = "SELECT e FROM Employee e WHERE
e.id = :id"),
#NamedQuery(name = "Employee.findByName", query = "SELECT e FROM Employee e WHERE
e.name = :name")})
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Size(max = 20)
#Column(name = "name")
private String name;
public Employee() {
}
public Employee(Integer id) {
this.id = id;
}
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;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Employee)) {
return false;
}
Employee other = (Employee) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.rachid.entities.Employee[ id=" + id + " ]";
}
}
The session bean that uses the entity is:
package com.rachid.session;
import com.rachid.entities.Employee;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
#Stateless
#LocalBean
public class EmployeeSessionBean {
#PersistenceContext(unitName = "EnterpriseApplication1-ejbPU")
private EntityManager em;
public List<Employee> getAllEmployees() {
Query query = em.createNamedQuery("Employee.findAll");
return query.getResultList();
}
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
public Employee updateEmployee(Employee parameter) {
return em.merge(parameter);
}
public void addEmployee(Employee employee){
em.persist(employee);
}
}
The managed bean is:
package managedBeans;
import com.rachid.entities.Employee;
import com.rachid.session.EmployeeSessionBean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ViewScoped;
import javax.inject.Named;
#Named(value = "employeeManagedBean")
#ViewScoped
public class EmployeeManagedBean implements Serializable {
public EmployeeManagedBean() {
}
#EJB
private EmployeeSessionBean employeeBean;
private Employee employee;
private Employee newEmployee;
private List<Employee> employees;
public List<Employee> getEmployees(){
employees = new ArrayList<Employee>();
return employeeBean.getAllEmployees();
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public void add(){
if(newEmployee!= null){
employeeBean.addEmployee(newEmployee);
}
}
public String update(){
System.out.println("***UPDATE***");
employee = employeeBean.updateEmployee(employee);
return "Employees List";
}
public Employee getNewEmployee() {
return newEmployee;
}
public void setNewEmployee(Employee newEmployee) {
this.newEmployee = newEmployee;
}
}
Unfortunately, when I invoke the method addEmployee in the jsf page, nothing is written to the database. I was worried about the transaction management handled by the container; that is the updates and inserts are managed by the container and it may not be written to the database immediately, so I annotate the addEmployee method (in the EJB) with the #TransationalAttribute(TransactionalAttributeType.REQUIRED) but the result still the same.
Is there anything that I am missing here in my code or my understanding of the issue's context?
(Note that I am a beginner in EJB :) )
Here are the jsf pages (an index page that shows the list and another one to add new element to the list):
index.xhtml file:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
Hello from Facelets
<f:view>
<h:form>
<h1><h:outputText value="List"/></h1>
<h:dataTable value="#{employeeManagedBean.employees}" var="item">
<h:column>
<f:facet name="header">
<h:outputText value="Id"/>
</f:facet>
<h:outputText value="#{item.id}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Name"/>
</f:facet>
<h:outputText value="#{item.name}"/>
</h:column>
</h:dataTable>
</h:form>
</f:view>
<h:form>
<h:commandButton value="nouveau" action="ajouter.xhtml" type="submit" />
</h:form>
</h:body>
ajouter.xhtml file:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org
/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:body>
<f:view>
<h:form>
<h1><h:outputText value="Create/Edit"/></h1>
<h:panelGrid columns="2">
<h:outputLabel value="Id:" for="id" />
<h:inputText id="id" value="#{employeeManagedBean.newEmployee.id}"
title="Id"
required="true" requiredMessage="The Id field is required."/>
<h:outputLabel value="Name:" for="name" />
<h:inputText id="name" value="#{employeeManagedBean.newEmployee.name}"
title="Name" />
</h:panelGrid>
</h:form>
</f:view>
<h:form>
<h:commandButton value="ajouter" action="index.xhtml" type="submit"
actionListener="#{employeeManagedBean.add()}" />
</h:form>
</h:body>