I've made a simple form and I am trying to validate it but I have some trouble. This is my controller:
import ninja.majewski.store.forms.ContactDTO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;
#Controller
public class MainController {
#RequestMapping(value = "/contact", method = RequestMethod.GET)
public String contact(Model model) {
addBasicInfo(model);
model.addAttribute("form", new ContactDTO());
return "contact";
}
#RequestMapping(value = "/contact", method = RequestMethod.POST)
public String contact(Model model, #ModelAttribute("form") #Valid ContactDTO form, BindingResult result) {
addBasicInfo(model);
model.addAttribute("form", new ContactDTO());
// return false
System.out.println(result.hasErrors());
if (result.hasErrors()) {
return "contact";
} else {
return "redirect:/home";
}
}
}
This is my DTO class:
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Size;
public class ContactDTO {
#NotEmpty
#Size(min = 3)
private String name;
#NotEmpty
#Email
private String email;
private String message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
And my form HTML:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
</body>
</html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>I AM A HORSE</title>
<spring:url value="/resources/css/bootstrap.css" var="bootstrapCss"/>
<link href="${bootstrapCss}" rel="stylesheet" type="text/css"/>
</head>
<body>
<jsp:include page="parts/header.jsp"/>
<jsp:include page="parts/leftMenu.jsp"/>
<table>
<td>
<form:form action="/contact" modelAttribute="form" method="post">
Name:
<form:input path="name" id="name"/>
<form:errors path="name" cssclass="error"/>
<br/>
Email:
<form:input path="email" id="email"/>
<form:errors path="email" cssclass="error"/>
<br/>
Message:
<form:input path="message" id="message"/>
<form:errors path="message" cssclass="error"/>
<br/>
<input type="submit" value="Send message"/>
</form:form>
</td>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="/resources/js/bootstrap.min.js"></script>
</body>
</html>
And my app configuration:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="ninja.majewski"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
The problem is that even when I submit empty form BindingResult.hasErrors() gives false. Where have I made a mistake?
#ModelAttribute should be first parameter of the method. Try to replace it with Model, and declare #Valid annotation before #ModelAttribute.
#RequestMapping(value = "/contact", method = RequestMethod.POST)
public String contact(#Valid #ModelAttribute("form") ContactDTO form, BindingResult result, Model model) {
addBasicInfo(model);
Related
DB Connection Stuffs
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtils {
private static Connection connection = null;
private static PreparedStatement preparedStatement = null;
private static ResultSet resultSet = null;
public static Connection getConnection(String shopingkart) {
String url = "jdbc:mysql://localhost:3306/" + shopingkart;
String user = "root";
String pwd = "root1234";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url, user, pwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static PreparedStatement getPreparedStatement(String sql) {
try {
if (connection != null) {
preparedStatement = connection.prepareStatement(sql,
java.sql.Statement.RETURN_GENERATED_KEYS);
}
} catch (SQLException e) {
e.printStackTrace();
}
return preparedStatement;
}
public static void closeResources(ResultSet rs, PreparedStatement pst,
Connection conn) {
try {
if (rs != null)
rs.close();
if (pst != null)
pst.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}`
Util Class
This is my util class. here i have done the database operation for getting the the data from database.
package com.sushovan.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.sushovan.bin.Product;
public class Allutills {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
public List<Product> getAllProducts() {
Product product = null;
List<Product> pList = new ArrayList<Product>();
String sql = "select * from Product";
connection = DBUtils.getConnection("shopingkart");
preparedStatement = DBUtils.getPreparedStatement(sql);
try {
resultSet = preparedStatement.executeQuery();
if (resultSet != null) {
while (resultSet.next()) {
product = new Product(resultSet.getInt(1),
resultSet.getString(2), resultSet.getInt(3));
pList.add(product);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return pList;
}
}
Servlet Class
this is my servlet class the controller class.
package com.sushovan.servlets;
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 com.sushovan.bin.Product;
import com.sushovan.utils.Allutills;
#WebServlet("/productServlet")
public class ProductServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Allutills allutills = new Allutills();
List<Product> allProList = new ArrayList<Product>();
allProList = allutills.getAllProducts();
HttpSession session = request.getSession(true);
if (session != null) {
session.setAttribute("allProList", allProList);
}
RequestDispatcher dispatcher = request
.getRequestDispatcher("showProduct.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
.jsp page
This is my view page where i am trying to display my list of objects
<%#page import="java.util.List"%>
<%#page import="java.util.ArrayList"%>
<%#page import="com.sushovan.bin.Product"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div align="center" style="border: medium;">
<table>
<tr>
<td><input type="text" value="Id" disabled="disabled">
<td><input type="text" value="Product Name" disabled="disabled">
<td><input type="text" value="Product Price"
disabled="disabled">
</tr>
</table>
</div>
<%
ArrayList<Product> allproList=(ArrayList<Product>)
request.getAttribute("allProList");
for(Product product : allproList){
out.println(product.getPid());
out.println(product.getPname());
out.println(product.getPprice());
}
%>
</body>
</html>
This the Product class
package com.sushovan.bin;
public class Product {
private int pid;
private String pname;
private int pprice;
/***********Getters And Setters*****************/
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public int getPprice() {
return pprice;
}
public void setPprice(int pprice) {
this.pprice = pprice;
}
/**********************Getter And Setters********************/
/******************Constuctors******************/
public Product(int pid, String pname, int pprice) {
super();
this.pid = pid;
this.pname = pname;
this.pprice = pprice;
}
public Product() {
super(); }
}
New Edited Jsp I didn't use here my Util classes. I have done all the operations in the jsp page
`<%#page import="java.util.List"%>
<%#page import="java.util.ArrayList"%>
<%#page import="com.sushovan.bin.Product"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.Connection"%>
<%#page import="com.sushovan.utils.DBUtils"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%-- <% --%>
// ArrayList<Product> allProList=(ArrayList<Product>)
request.getAttribute("allProList");
<%-- %> --%>
<!-- <table> -->
<!-- <tr> -->
<!-- <th>pid</th> -->
<!-- <th>pname</th> -->
<!-- <th>price</th> -->
<!-- </tr> -->
<%-- <c:forEach var="product" items="${allProList}"> --%>
<!-- <tr> -->
<%-- <td><c:out value="${product.pid}" /></td> --
%>
<%-- <td><c:out value="${product.pname}" /></td> -
-%>
<%-- <td><c:out value="${product.price}" /></td> -
-%>
<!-- </tr> -->
<%-- </c:forEach> --%>
<!-- </table> -->
<%
Connection connection= null;
PreparedStatement preparedStatement= null;
ResultSet resultSet= null;
String sql="select * from Product";
//CuisineBin cuisineBin= new CuisineBin();
connection= DBUtils.getConnection("shopingkart");
preparedStatement= connection.prepareStatement(sql);
resultSet= preparedStatement.executeQuery();
%>
<table align="left">
<tr>
<td><input type="text" value="Product Id" class="text" size="30px">
<td><input type="text" value="Product Name" class="text" size="30px">
<td><input type="text" value="Product Rate" class="text" size="30px">
<td><input type="text" value="Buy" class="text" size="30px">
</tr>
</table>
<%
while(resultSet.next()){
int id= resultSet.getInt(1);
String name= resultSet.getString(2);
int price= resultSet.getInt(3);
%>
<table align="left">
<tr>
<td><input type="text" id="pid" name="pid" value= "<%= resultSet.getInt(1)
%>" size="30px">
<td><input type="text" id="pid" name="pid" value="
<%=resultSet.getString(2) %>" size="30px">
<td><input type="text" id="pid" name="pid" value="<%=resultSet.getInt(3)
%>" size="30px">
<td><input type="submit" value="Buy Now" width="30px" size="30px">
</tr>
</table>
<%} %>
</body>
</html>`
Emp.java
package com.javatpoint;
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.javatpoint;
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.javatpoint.Emp;
import com.javatpoint.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:/empform.jsp");//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);
}
}
EmpDao.java
package com.javatpoint;
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.javatpoint.Emp;
public class EmpDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public int save(Emp p){
String sql="insert into emp(name,salary,designation) values('"+p.getName()+"',"+p.getSalary()+",'"+p.getDesignation()+"')";
return template.update(sql);
}
public Emp getEmpById(int id){
String sql="select * from emp where name=?";
return template.queryForObject(sql, new Object[]{id},new BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return template.query("select * from emp",new RowMapper<Emp>(){
public Emp mapRow(ResultSet rs, int row) throws SQLException {
Emp e=new Emp();
e.setName(rs.getString(1));
e.setSalary(rs.getFloat(2));
e.setDesignation(rs.getString(3));
return e;
}
});
}
}
spring1-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.javatpoint"/>
<bean id="ds" 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="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.javatpoint.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>spring1</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring1</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
empform.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Add New Employee</h1>
<form method="post" action="save">
<table >
<tr>
<td>Name : </td>
<td><input path="name" /></td>
</tr>
<tr>
<td>Salary :</td>
<td><input path="salary" /></td>
</tr>
<tr>
<td>Designation :</td>
<td><input path="designation" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Save" /></td>
</tr>
</table>
<form>
</body>
</html>
viewemp.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Employees List</h1>
<table border="2" width="70%" cellpadding="2">
<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</th><th>Edit</th><th>Delete</th></tr>
<c:forEach var="emp" items="${list}">
<tr>
<td>${emp.id}</td>
<td>${emp.name}</td>
<td>${emp.salary}</td>
<td>${emp.designation}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
<br/>
Add New Employee
</body>
</html>
hi
I am trying to fetching the data from the database but it show's the only curd .
enter image description here it show the like that .
and it display the jsp file data. I am check the all possible way to display the data from the database.curd will be displayed but it show's the jsp file data.
please check the my code and provide the solution.
thank you.
I am not sure about this solution is gonna work in you case,
but i think you forget to add JSTL Core Tags
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
after this jstl know <c:forEach var="emp" items="${list}"> will render as for loop and in each iteration emp is your object variable
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.
I am here again with a new concern. I'm getting the Etat HTTP 400 error page when I am trying to create a new Utilisateur in mysql database. But no error is displayed in the console.
My code:
Utilisateur.java
package com.model;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="utilisateur")
public class Utilisateur implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="idutilisateur")
private int idUtilisateur;
#Column(name="emailutilisateur")
private String emailUtilisateur;
#Column(name="motpasseutilisateur")
private String motPasseUtilisateur;
#Column(name="nomutilisateur")private String nomUtilisateur;
#Column(name="dateinscriptionutilisateur")
private Timestamp dateInscriptionUtilisateur;
public int getIdUtilisateur() {
return idUtilisateur;
}
public void setIdUtilisateur(int idUtilisateur) {
this.idUtilisateur = idUtilisateur;
}
public String getEmailUtilisateur() {
return emailUtilisateur;
}
public void setEmailUtilisateur(String emailUtilisateur) {
this.emailUtilisateur = emailUtilisateur;
}
public String getMotPasseUtilisateur() {
return motPasseUtilisateur;
}
public void setMotPasseUtilisateur(String motPasseUtilisateur) {
this.motPasseUtilisateur = motPasseUtilisateur;
}
public String getNomUtilisateur() {
return nomUtilisateur;
}
public void setNomUtilisateur(String nomUtilisateur) {
this.nomUtilisateur = nomUtilisateur;
}
public Timestamp getDateInscriptionUtilisateur() {
return dateInscriptionUtilisateur;
}
public void setDateInscriptionUtilisateur(Timestamp dateInscriptionUtilisateur) {
this.dateInscriptionUtilisateur = dateInscriptionUtilisateur;
}
#Override
public String toString() {
return "Utilisateur [idUtilisateur=" + idUtilisateur + ", emailUtilisateur=" + emailUtilisateur
+ ", motPasseUtilisateur=" + motPasseUtilisateur + ", nomUtilisateur=" + nomUtilisateur
+ ", dateInscriptionUtilisateur=" + dateInscriptionUtilisateur + "]";
}
}
UtilisateurDaoImpl.java
package com.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.model.Utilisateur;
#Repository
public class UtilisateurDaoImpl implements UtilisateurDao {
#Autowired
private SessionFactory sessionFactory;
public void addUtilisateur(Utilisateur utilisateur) {
sessionFactory.getCurrentSession().saveOrUpdate(utilisateur);
}
#SuppressWarnings("unchecked")
public List<Utilisateur> getAllUtilisateur() {
List<Utilisateur> listeUtilisateur = sessionFactory.getCurrentSession().createQuery("from Utilisateur").list();
return listeUtilisateur;
}
public Utilisateur getUtilisateurById(int idUtilisateur) {
return (Utilisateur)sessionFactory.getCurrentSession().get(Utilisateur.class, idUtilisateur);
}
public Utilisateur updateUtilisateur(Utilisateur utilisateur) {
sessionFactory.getCurrentSession().update(utilisateur);
return utilisateur;
}
public void deleteUtilisateur(int idUtilisateur) {
Utilisateur utilisateur = (Utilisateur)sessionFactory.getCurrentSession().load(Utilisateur.class, idUtilisateur);
if(utilisateur != null){
this.sessionFactory.getCurrentSession().delete(utilisateur);
}
}
}
UtilisateurServiceImpl.java
package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dao.UtilisateurDao;
import com.model.Utilisateur;
#Service
#Transactional
public class UtilisateurServiceImpl implements UtilisateurService {
#Autowired
private UtilisateurDao utilisateurDao;
public void setUtilisateurDao(UtilisateurDao utilisateurDao) {
this.utilisateurDao = utilisateurDao;
}
#Transactional
public void addUtilisateur(Utilisateur utilisateur) {
utilisateurDao.addUtilisateur(utilisateur);
}
#Transactional
public List<Utilisateur> getAllUtilisateur() {
return utilisateurDao.getAllUtilisateur();
}
#Transactional
public Utilisateur getUtilisateurById(int idUtilisateur) {
return utilisateurDao.getUtilisateurById(idUtilisateur);
}
#Transactional
public Utilisateur updateUtilisateur(Utilisateur utilisateur) {
return utilisateurDao.updateUtilisateur(utilisateur);
}
#Transactional
public void deleteUtilisateur(int idUtilisateur) {
utilisateurDao.deleteUtilisateur(idUtilisateur);
}
}
UtilisateurController.java
package com.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.jboss.logging.Logger;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.model.Utilisateur;
import com.service.UtilisateurService;
#Controller
public class UtilisateurController {
#SuppressWarnings("unused")
private final static Logger logger = Logger.getLogger("UtilisateurController");
public UtilisateurController(){
System.out.println("UtilisateurController()");
}
#Autowired
private UtilisateurService service;
#RequestMapping(value="/newUtilisateur", method=RequestMethod.GET)
public ModelAndView newUtilisateur(ModelAndView model){
Utilisateur utilisateur = new Utilisateur();
model.addObject("utilisateur", utilisateur);
model.setViewName("utilisateurForm");
return model;
}
#RequestMapping(value="/saveUtilisateur", method = RequestMethod.POST)
public ModelAndView saveUtilisateur(#ModelAttribute Utilisateur utilisateur) {
System.out.println(utilisateur.getIdUtilisateur());
if (utilisateur.getIdUtilisateur() == 0) {
service.addUtilisateur(utilisateur);
} else {
service.updateUtilisateur(utilisateur);
}
return new ModelAndView("redirect:/");
}
#RequestMapping(value="/", method=RequestMethod.GET)
public ModelAndView listeUtilisateur(ModelAndView model) throws IOException{
List<Utilisateur> listeUtilisateur = service.getAllUtilisateur();
model.addObject("listeUtilisateur", listeUtilisateur);
model.setViewName("listeutilisateur");
return model;
}
#RequestMapping(value = "/editUtilisateur", method = RequestMethod.GET)
public ModelAndView editUtilisateur(HttpServletRequest request) {
int idUtilisateur = Integer.parseInt(request.getParameter("idUtilisateur"));
System.out.println(idUtilisateur);
Utilisateur utilisateur = service.getUtilisateurById(idUtilisateur);
ModelAndView model = new ModelAndView("utilisateurForm");
model.addObject("utilisateur", utilisateur);
return model;
}
#RequestMapping(value="/deleteUtilisateur", method=RequestMethod.GET)
public ModelAndView deleteUtilisateur(HttpServletRequest request){
service.deleteUtilisateur(Integer.parseInt(request.getParameter("idUtilisateur")));
return new ModelAndView("redirect:/");
}
}
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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com"/>
<mvc:annotation-driven/>
<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
<context:property-placeholder location="classpath:application.properties"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/vues/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.show_format">${hibernate.show_format}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
<property name="packagesToScan" value="com.model"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
utilisateurForm.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Edit / Save Utilisateur</title>
</head>
<body>
<div align="center">
<h1> Edit / Save Utilisateur</h1>
<form:form action="saveUtilisateur" method="post" modelAttribute="utilisateur">
<table>
<form:hidden path="idUtilisateur"/>
<tr>
<td>Adresse email</td>
<td><form:input path="emailUtilisateur"/></td>
</tr>
<tr>
<td>Mot de passe</td>
<td><form:password path="motPasseUtilisateur"/></td>
</tr>
<tr>
<td>Nom d'utilisateur</td>
<td><form:input path="nomUtilisateur"/></td>
</tr>
<tr>
<td>Date d'inscription</td>
<td><form:input path="dateInscriptionUtilisateur"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save"/></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
listeutilisateur.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Liste des utilisateurs</title>
<link rel="stylesheet" type="html/css" href="/WEB-INF/style.css"/>
</head>
<body>
<div align="center">
<h1>Liste des utilisateurs</h1>
<table border="1">
<tr>
<th>Id.</th>
<th>Nom d'utilisateur</th>
<th>Adresse email</th>
<th>Mot de passe</th>
<th>Date d'inscription</th>
<th>Action</th>
</tr>
<c:forEach items="${listeUtilisateur}" var="u">
<tr>
<td><c:out value="${u.idUtilisateur}"/></td>
<td><c:out value="${u.nomUtilisateur}"/></td>
<td><c:out value="${u.emailUtilisateur}"/></td>
<td><c:out value="${u.motPasseUtilisateur}"/></td>
<td><c:out value="${u.dateInscriptionUtilisateur}"/></td>
<td>Edit Delete</td>
</tr>
</c:forEach>
</table>
<h3>Nouveau ? Cliquer ici</h3>
</div>
</body>
</html>
application.properties
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/gestionutilisateur
database.username=root
database.password=1234
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.show_format=true
hibernate.hbm2ddl.auto=update
I finally find what's wrong. It's a matter of date format. I declare a Timestamsp in my model but type something like "2017-10-05" in my view.
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>