HTTP Status 404 - - mysql

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.

Related

HTTP Status 500 - Servlet.init() for servlet management threw exception

Emp.java
package com.management;
public class Emp {
private int id;
private String name;
private float salary;
private String designation;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
EmpController.java
package com.management;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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;
import com.management.Emp;
import com.management.EmpDao;
#Controller
public class EmpController {
#Autowired
EmpDao dao;//will inject dao from xml file
/*It displays a form to input data, here "command" is a reserved request attribute
*which is used to display object data into form
*/
#RequestMapping("/empform")
public ModelAndView showform(){
return new ModelAndView("empform","command",new Emp());
}
/*It saves object into database. The #ModelAttribute puts request data
* into model object. You need to mention RequestMethod.POST method
* because default request is GET*/
#RequestMapping(value="/save",method = RequestMethod.POST)
public ModelAndView save(#ModelAttribute("emp") Emp emp){
dao.save(emp);
return new ModelAndView("redirect:/viewemp");//will redirect to viewemp request mapping
}
/* It provides list of employees in model object */
#RequestMapping("/viewemp")
public ModelAndView viewemp(){
List<Emp> list=dao.getEmployees();
return new ModelAndView("viewemp","list",list);
}
/* It displays object data into form for the given id.
* The #PathVariable puts URL data into variable.*/
#RequestMapping(value="/editemp/{id}")
public ModelAndView edit(#PathVariable int id){
Emp emp=dao.getEmpById(id);
return new ModelAndView("empeditform","command",emp);
}
/* It updates model object. */
#RequestMapping(value="/editsave",method = RequestMethod.POST)
public ModelAndView editsave(#ModelAttribute("emp") Emp emp){
dao.update(emp);
return new ModelAndView("redirect:/viewemp");
}
/* It deletes record for the given id in URL and redirects to /viewemp */
#RequestMapping(value="/deleteemp/{id}",method = RequestMethod.GET)
public ModelAndView delete(#PathVariable int id){
dao.delete(id);
return new ModelAndView("redirect:/viewemp");
}
}
EmpDao.java
package com.management;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.management.Emp;
public class EmpDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public int save(Emp p){
String sql="insert into Emp99(name,salary,designation) values('"+p.getName()+"',"+p.getSalary()+",'"+p.getDesignation()+"')";
return template.update(sql);
}
public int update(Emp p){
String sql="update Emp99 set name='"+p.getName()+"', salary="+p.getSalary()+", designation='"+p.getDesignation()+"' where id="+p.getId()+"";
return template.update(sql);
}
public int delete(int id){
String sql="delete from Emp99 where id="+id+"";
return template.update(sql);
}
public Emp getEmpById(int id){
String sql="select * from Emp99 where id=?";
return template.queryForObject(sql, new Object[]{id},new BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return template.query("select * from Emp99",new RowMapper<Emp>(){
public Emp mapRow(ResultSet rs, int row) throws SQLException {
Emp e=new Emp();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getFloat(3));
e.setDesignation(rs.getString(4));
return e;
}
});
}
}
servlet-management.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:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.spring" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://loclahost:3306/test1" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.spring.EmpDao">
<property name="template" ref="jt"></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>management</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>management</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
hi
my trying to insert the value to the database by using the spring-mvc.
and using the mysql database.
while execution process it shows the error like that-org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.spring.EmpDao] for bean with name 'dao' defined in ServletContext resource [/WEB-INF/management-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.spring.EmpDao .
please provide the soluation.
thank you.

Data not inserted in mySQL database from jsp form

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>

Second level Cache Perfomance

Recently I was studying some possibilities to improve my code , and I did some changes on it . I installed the hibernate configurations to use the second level cache, but the result of this improvement wasn't good enough .I was expecting a shortly time in my database queries. When I made some research after the implementation, the time was bigger than I had before this modification in my code . Even if I enable the cache query , my results don't change. What I saw after enable the query cache was worse time results . Another thing what I could see , was, if my tables has some relationship with another one , the search time increase a lot.
HibernateUtil
package com.journaldev.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
System.out.println("Hibernate Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate serviceRegistry created");
SessionFactory sessionFactoryLocal = configuration.buildSessionFactory(serviceRegistry);
return sessionFactoryLocal;
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}}
Employee
package com.journaldev.hibernate.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 org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
#Entity
#Table(name = "EMPLOYEE")
#Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "emp_id")
private long id;
#Column(name = "emp_name")
private String name;
#Column(name = "emp_salary")
private double salary;
public Employee(String name) {
this.name = name;
}
public Employee() {
}}
Adress
package com.journaldev.hibernate.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
#Entity
#Table(name = "ADDRESS")
#Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="employee")
public class Address {
#Id
#GeneratedValue
private long id;
#Column(name = "address_line1")
private String addressLine1;
#Column(name = "zipcode")
private String zipcode;
#Column(name = "city")
private String city;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Employee Relation Adress
package com.journaldev.hibernate.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Cascade;
#Entity
#Table(name = "EMPLOYEE")
#Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "emp_id")
private long id;
#Column(name = "emp_name")
private String name;
#Column(name = "emp_salary")
private double salary;
#OneToOne(mappedBy = "employee")
#Cascade(value = org.hibernate.annotations.CascadeType.ALL)
private Address address;
public Employee(String name) {
this.name = name;
}
public Employee() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
Class teste
package com.journaldev.hibernate.main;
import org.hibernate.Session;
import com.journaldev.hibernate.model.Employee;
import com.journaldev.hibernate.util.HibernateUtil;
import java.util.Date;
public class HibernateEHCacheMain {
public static void main(String[] args) {
//insert10000();
// System.out.println("Temp Dir:" + System.getProperty("java.io.tmpdir"));
long init1 = new Date().getTime();
list10000WithCache();
long end1 = new Date().getTime();
long result1 = end1 - init1;
long init2 = new Date().getTime();
list10000WithCache();
long end2 = new Date().getTime();
long result2 = end2 - init2;
long init3 = new Date().getTime();
list10000WithCache();
//list10000WithoutCache();
long end3 = new Date().getTime();
long result3 = end3 - init3;
System.err.println("Result 1 : " + result1 + "\nResult 2 :" + result2 + "\nResult 3 :" + result3);
System.exit(1);
}
private static void insert10000() {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
for (int i = 0; i < 10000; i++) {
session.save(new Employee(i + ""));
if (i % 20 == 0) {
session.flush();
session.clear();
}
}
session.getTransaction().commit();
session.close();
}
private static void list10000WithoutCache() {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.createQuery("from Employee").list();
session.getTransaction().commit();
session.close();
}
private static void list10000WithCache() {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.createQuery("from Employee").setCacheable(true).list();
session.getTransaction().commit();
session.close();
}
}
Hibernate.cfg
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "classpath://org/hibernate/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">pass</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/mydb</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.default_batch_fetch_size">20</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- For singleton factory -->
<!-- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</property>
-->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- enable second level cache and query cache -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="net.sf.ehcache.configurationResourceName">/myehcache.xml</property>
<mapping class="com.journaldev.hibernate.model.Employee" />
<mapping class="com.journaldev.hibernate.model.Address" />
</session-factory>
</hibernate-configuration>
myehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect" dynamicConfig="true">
<diskStore path="java.io.tmpdir/ehcache" />
<defaultCache maxEntriesLocalHeap="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"
maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" statistics="true">
<persistence strategy="localTempSwap" />
</defaultCache>
<cache name="employee" maxEntriesLocalHeap="10000" eternal="false"
timeToIdleSeconds="5" timeToLiveSeconds="10">
<persistence strategy="localTempSwap" />
</cache>
<cache name="org.hibernate.cache.internal.StandardQueryCache"
maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120">
<persistence strategy="localTempSwap" />
</cache>
<cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
maxEntriesLocalHeap="5000" eternal="true">
<persistence strategy="localTempSwap" />
</cache>
</ehcache>
How Query Caching works ?
Query Cache is used to cache the results of a query. When the query cache is turned on, the results of the query are stored against the combination query and parameters. Every time the query is fired the cache manager checks for the combination of parameters and query. If the results are found in the cache, they are returned, otherwise a database transaction is initiated.
Why Query Cache should not use ?
As you can see, it is not a good idea to cache a query if it has a number of parameters, because then a single parameter can take a number of values. For each of these combinations the results are stored in the memory. This can lead to extensive memory usage.
They are many pitfalls in enabling query second level caching.Please go through this link.
I dont see any issues in your configuration.All you need to enable statistic on sessionfactory to find second level caching is working or not.
Statistics statistics = sessionFactory.getStatistics();
statistics.setStatisticsEnabled(true);
You can check below values
statistics.getEntityFetchCount()
statistics.getSecondLevelCacheHitCount()
statistics.getSecondLevelCachePutCount()
statistics.getSecondLevelCacheMissCount()
Go with this post for precise explanation on second level caching with statistics.

Spring MVC with jdbc "table is not mapped"

So I´m trying to make an application with all http request get, put, post, delete.I'm making first a login with mysql and spring 3. So here I got this:
login.jsp:
<form:form id="myForm" method="post"
class="bs-example form-horizontal" commandName="UsersLogin">
signup.jsp
<form:form id="myForm" method="post"
class="bs-example form-horizontal" commandName="Users">
persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/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_2_0.xsd}"
version="2.0">
<persistence-unit name="punit">
</persistence-unit>
</persistence>
Here is my jpaContext.xml:
<context:annotation-config />
<jpa:repositories base-package="com.portuzona.repository" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="punit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<entry key="hibernate.hbm2ddl.auto" value="validate" />
<entry key="hibernate.format_sql" value="true" />
</map>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<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/portuzona?autoReconnect=true&createDatabaseIfNotExist=true&" />
<property name="username" value="root" />
<property name="password" value="1234" />
</bean>
</beans>
com.portuzona.model
Users model:
#Entity
#Table(name="users")
public class Users {
#Id
#GeneratedValue
private Long id;
#NotEmpty
#Size(min=4, max=20)
private String userName;
#NotEmpty
private String firstName;
#NotEmpty
private String lastName;
#NotEmpty
#Size(min=4, max=8)
private String password;
#NotEmpty
private String status;
#NotEmpty
#Email
private String emailAddress;
#NotNull
#Past
#DateTimeFormat(pattern="MM/dd/yyyy")
private Date dateOfBirth;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
USersLogin model:
public class UsersLogin {
#NotEmpty
#Size(min=4, max=20)
private String userName;
#NotEmpty
#Size(min=4, max=8)
private String password;
public String getPassword() {
return password;
}
public String getUserName() {
return userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
com.portuzona.service
public interface UsersService {
Users save(Users users);
boolean findByLogin(String userName, String password);
boolean findByUserName(String userName);
}
Implementation:
#Service("UsersService")
public class UsersServiceImpl implements UsersService {
#Autowired
private UsersRepository usersRepository;
#Transactional
public Users save(Users users) {
return usersRepository.save(users);
}
public boolean findByLogin(String userName, String password) {
Users stud = usersRepository.findByUserName(userName);
if(stud != null && stud.getPassword().equals(password)) {
return true;
}
return false;
}
public boolean findByUserName(String userName) {
Users use = usersRepository.findByUserName(userName);
if(use != null) {
return true;
}
return false;
}
}
com.portuzona.repository
#Repository("UsersRepository")
public interface UsersRepository extends JpaRepository<Users, Long> {
#Query("SELECT s FROM users s WHERE s.userName = :userName")
Users findByUserName(#Param("userName") String userName);
}
com.portuzona.controller
#Controller
#SessionAttributes("users")
public class UsersController {
#Autowired
private UsersService userService;
#RequestMapping(value="/signup", method=RequestMethod.GET)
public String signup(Model model) {
Users users = new Users();
model.addAttribute("users", users);
return "signup";
}
#RequestMapping(value="/signup", method=RequestMethod.POST)
public String signup(#Valid #ModelAttribute("users") Users users, BindingResult result, Model model) {
if(result.hasErrors()) {
return "signup";
} else if(userService.findByUserName(users.getUserName())) {
model.addAttribute("message", "User Name exists. Try another user name");
return "signup";
} else {
userService.save(users);
model.addAttribute("message", "Saved users details");
return "redirect:login.html";
}
}
#RequestMapping(value="/login", method=RequestMethod.GET)
public String login(Model model) {
UsersLogin usersLogin = new UsersLogin();
model.addAttribute("UsersLogin", usersLogin);
return "login";
}
#RequestMapping(value="/login", method=RequestMethod.POST)
public String login(#Valid #ModelAttribute("UsersLogin") UsersLogin usersLogin, BindingResult result) {
if (result.hasErrors()) {
return "login";
} else {
boolean found = userService.findByLogin(usersLogin.getUserName(), usersLogin.getPassword());
if (found) {
return "success";
} else {
return "failure";
}
}
}
}
I got this error when trying to access to /login or /signup where I have my .jsp with my forms:
sep 24, 2015 11:14:35 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet usersHibernateServlet
org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [SELECT s FROM users s WHERE s.userName = :userName]
I have been with this for two days, looking for answers here but no kind of good results from my side... just gives me the same error, any idea?

calling rest api in spring

I am having rest method in spring controller like below:
#RequestMapping(value="/register/{userName}" ,method=RequestMethod.GET)
#ResponseBody
public String getUserName(HttpServletRequest request,#PathVariable String userName ){
System.out.println("User Name : "+userName);
return "available";
}
In jquery I have writeen ajax call like:
$(document).ready(function(){
$('#userName').blur(function(){
var methodURL = "http://localhost:8085/ums/register/"+$('#userName').val();
$.ajax({
type : "get",
URL : methodURL,
data : $('#userName').val(),
success : function(data){
alert(data);
$('#available').show();
}
})
});
});
In web.xml I have:
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
In spring-servlet.xml I have the view resolver like below:
<context:component-scan base-package="com.users.controller" />
<context:annotation-config />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1"/>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="text/xml" />
<entry key="htm" value="text/html" />
</map>
</property>
<property name="ignoreAcceptHeader" value="true" />
<!-- <property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />-->
<property name="defaultContentType" value="text/html" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="2" />
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
When I am running this in server, it is not going to controller.
Please let me know the problem with this code.
Please can any one help on this.
Regards,
Shruti
Since you have the #RequestMapping(value="register/{userName}" on your method definition, your jquery call must follow the same syntax.
var methodURL = "http://localhost:8085/users/register/"+$('#userName').val()+".html";
But you have also a problem in your RequestMapping value, it should start with /
#RequestMapping(value="/register/{userName}"
Also I doubt that you need the ".html" at the end
Add this line to your spring-servlet.xml. It will enable the Web MVC specific annotations like #Controller and #RequestMapping
<mvc:annotation-driven />
Example of an annotated controller
Assuming the url with context is http://localhost:8080/webapp and you want an api call like url /users/register/johnDoe. (johnDoe being the username)
You controller class would look something like the following.
#Controller
#RequestMapping(value="/users")
class UserController {
#ResponseBody
#RequestMapping(value="/register/{username}", method=RequestMethod.GET)
public String registerUser(#PathVariable String username) {
return username;
}
}
Please find my solution for calling REST web-services in Spring Framework.
/**
* REST API Implementation Using REST Controller
* */
#RestController
public class RestReqCntrl {
#Autowired
private UserService userService;
#Autowired
private PayrollService payrollService;
//-------------------Create a User--------------------------------------------------------
#RequestMapping(value = "/registerUser", method = RequestMethod.POST)
public ResponseEntity<User> registerUser(#RequestBody User user, UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating User " + user.getFirstName());
boolean flag = userService.registerUser(user);
if (flag)
{
user.setStatusCode(1);
user.setStatusDesc("PASS");
}else{
user.setStatusCode(0);
user.setStatusDesc("FAIL");
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerUser").buildAndExpand(user.getId()).toUri());
return new ResponseEntity<User>(user,headers, HttpStatus.CREATED);
}
//-------------------Authenticating the User--------------------------------------------------------
#RequestMapping(value = "/authuser", method = RequestMethod.POST)
public ResponseEntity<User> authuser(#RequestBody User user,UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating User " + user.getFirstName());
boolean flag = userService.authUser(user);
if (flag)
{
user.setStatusCode(1);
user.setStatusDesc("PASS");
}else{
user.setStatusCode(0);
user.setStatusDesc("FAIL");
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/authuser").buildAndExpand(user.getFirstName()).toUri());
return new ResponseEntity<User>(user,headers, HttpStatus.ACCEPTED);
}
//-------------------Create a Company--------------------------------------------------------
#RequestMapping(value = "/registerCompany", method = RequestMethod.POST)
public ResponseEntity<String> registerCompany(#RequestBody ComypanyDTO comypanyDTO, UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating comypanyDTO " + comypanyDTO.getCmpName());
String result ="";
boolean flag = payrollService.registerCompany(comypanyDTO);
if (flag)
{
result="Pass";
}else{
result="Fail";
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
}
//-------------------Create a Employee--------------------------------------------------------
#RequestMapping(value = "/registerEmployee", method = RequestMethod.POST)
public ResponseEntity<String> registerEmployee(#RequestBody EmployeeDTO employeeDTO, UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating registerCompany " + employeeDTO.getEmpCode());
String result ="";
boolean flag = payrollService.registerEmpbyComp(employeeDTO);
if (flag)
{
result="Pass";
}else{
result="Fail";
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
}
//-------------------Get Company Deatils--------------------------------------------------------
#RequestMapping(value = "/getCompanies", method = RequestMethod.GET)
public ResponseEntity<List<ComypanyDTO> > getCompanies(UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("getCompanies getCompanies ");
List<ComypanyDTO> comypanyDTOs =null;
comypanyDTOs = payrollService.getCompanies();
//Setting the Respective Employees
for(ComypanyDTO dto :comypanyDTOs){
dto.setEmployeeDTOs(payrollService.getEmployes(dto.getCompanyId()));
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand("LISt").toUri());
return new ResponseEntity<List<ComypanyDTO>>(comypanyDTOs,headers, HttpStatus.ACCEPTED);
}
}
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name="USER_TABLE")
public class User implements Serializable {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String firstName;
private String lastName;
private String email;
private String userId;
private String password;
private String userType;
private String address;
#Transient
private int statusCode;
#Transient
private String statusDesc;
public User(){
}
public User(String firstName, String lastName, String email, String userId, String password, String userType,
String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.userId = userId;
this.password = password;
this.userType = userType;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* #return the userType
*/
public String getUserType() {
return userType;
}
/**
* #param userType the userType to set
*/
public void setUserType(String userType) {
this.userType = userType;
}
/**
* #return the address
*/
public String getAddress() {
return address;
}
/**
* #param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* #return the statusCode
*/
public int getStatusCode() {
return statusCode;
}
/**
* #param statusCode the statusCode to set
*/
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
/**
* #return the statusDesc
*/
public String getStatusDesc() {
return statusDesc;
}
/**
* #param statusDesc the statusDesc to set
*/
public void setStatusDesc(String statusDesc) {
this.statusDesc = statusDesc;
}
}