I am new to java and im using Eclipse IDE. Im doing a project where Admin is adding employees to the system. and i need to display the list of the employees by retrieving the data from the database and view it in a separate table (separate jsp page). even though the data is added to the database im not able to retrieve it. and i have used a for each loop in the jsp page. when the view page jspPropertyNotFoundException is being called .
Model classes
public class Person {
private String Nic;
private String Name;
private String Email;
private String Phone;
private String Address;
public Person(String Nic, String Name, String Email, String Phone, String Address) {
this.Nic = Nic;
this.Name = Name;
this.Email = Email;
this.Phone = Phone;
this.Address = Address;
}
public void setNic(String Nic) {
this.Nic = Nic;
}
public String getNic() {
return Nic;
}
public class Employee extends Person {
private String YearsOfExperience;
private String Specialization;
private String Salary;
public Employee(String Nic, String Name, String Email, String Phone, String Address, String YearsOfExperience,
String Specialization, String Salary) {
super(Nic, Name, Email, Phone, Address);
this.YearsOfExperience = YearsOfExperience;
this.Specialization = Specialization;
this.Salary = Salary;
}
public String getYearsOfExperience() {
return YearsOfExperience;
}
jsp page i want display the data (EmployeeList.jsp)
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<table>
<c:forEach var="emp" items="${employeeDetails}">
<c:set var="Nic" value="${emp.Nic}"/>
<c:set var="Name" value="${emp.Name}"/>
<c:set var="Email" value="${emp.Email}"/>
<c:set var="Phone" value="${emp.Phone}"/>
<c:set var="Address" value="${emp.Address}"/>
<c:set var="YearsOfExperience" value="${emp.YearsOfExperience}"/>
<c:set var="Specialization" value="${emp.Specialization}"/>
<c:set var="Salary" value="${emp.Salary}"/>
<tbody>
<tr>
<td>${emp.Nic}</td>
<td>${emp.Name}</td>
<td>${emp.Email}</td>
<td>${emp.Phone}</td>
<td>${emp.Address}</td>
<td>${emp.YearsOfExperience}</td>
<td>${emp.Specialization}</td>
<td>${emp.Salary}</td>
</tr>
</tbody>
</c:forEach>
</table>
addEmployee Servlet
#WebServlet("/addEmployeeServlet")
public class addEmployeeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String Nic= request.getParameter("Nic");
String Name= request.getParameter("Name");
String Email= request.getParameter("Email");
String Phone= request.getParameter("Phone");
String Address= request.getParameter("Address");
String YearsOfExperience= request.getParameter("YearsOfExperience");
String Specialization = request.getParameter("Specialization");
String Salary= request.getParameter("Salary");
boolean isTrue;
isTrue = EmployeeDBUtil.AddEmployee(Nic,Name,Email,Phone,Address,YearsOfExperience,Specialization,Salary);
//if inserted to database
if(isTrue == true) {
List <Employee> employeeDetails = EmployeeDBUtil.viewAllEmployee();
request.setAttribute("employeeDetails",employeeDetails);
RequestDispatcher dis1 =request.getRequestDispatcher("EmployeeList.jsp");
dis1.forward(request, response);
}
else {
RequestDispatcher dis2 =request.getRequestDispatcher("Unsuccess.jsp");
dis2.forward(request, response);
}
}
EmployeeDBUtil
public class EmployeeDBUtil {
private static Connection con= null;
private static Statement stmt = null;
private static ResultSet rs = null;
private static boolean isSuccess;
// data from the database
public static List<Employee> viewAllEmployee() {
ArrayList <Employee> emp = new ArrayList<>();
try {
con = DBconnection.getConnection();
stmt = con.createStatement();
String sql = "Select * from employee";
rs= stmt.executeQuery(sql);
while(rs.next()) {
String Nic= rs.getString(1);
String Name = rs.getString(2);
String Email = rs.getString(3);
String Phone =rs.getString(4);
String Address =rs.getString(5);
String YearsOfExperience =rs.getString(6);
String Specialization =rs.getString(7);
String Salary =rs.getString(8);
Employee e = new Employee(Nic,Name,Email,Phone,Address,YearsOfExperience,Specialization,Salary);
emp.add(e);
System.out.println("im here");
}
}catch(Exception e){
e.printStackTrace();
}
return emp;
}
Web Xml file
?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>AddEmployee</servlet-name>
<servlet-class>com.carepoint.servlet.addEmployeeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddEmployee</servlet-name>
<url-pattern>/Add</url-pattern>
</servlet-mapping>
</web-app>
when i add an employee to the system and it goes to the EmployeeList.jsp page but it does show the table or the list . Though the Nic is in person model. This is the error that is shown .
May 09, 2020 7:04:31 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet [jsp] threw exception
org.apache.jasper.el.JspPropertyNotFoundException: /EmployeeList.jsp(315,9) '${emp.Nic}' Property [Nic] not found on type [com.carepoint.model.Employee]
at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:120)
at org.apache.jsp.EmployeeList_jsp._jspx_meth_c_005fset_005f0(EmployeeList_jsp.java:659)
at org.apache.jsp.EmployeeList_jsp._jspx_meth_c_005fforEach_005f0(EmployeeList_jsp.java:558)
at org.apache.jsp.EmployeeList_jsp._jspService(EmployeeList_jsp.java:441)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
at com.carepoint.servlet.addEmployeeServlet.doPost(addEmployeeServlet.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
May 09, 2020 7:04:31 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [AddEmployee] in context with path [/Care-Point-Service-Station] threw exception [An exception occurred processing [/EmployeeList.jsp] at line [315]
312:
313: <c:forEach var="emp" items="${employeeDetails}">
314:
315: <c:set var="Nic" value="${emp.Nic}"/>
316: <c:set var="Name" value="${emp.Name}"/>
317: <c:set var="Email" value="${emp.Email}"/>
318: <c:set var="Phone" value="${emp.Phone}"/>
Stacktrace:] with root cause
org.apache.jasper.el.JspPropertyNotFoundException: /EmployeeList.jsp(315,9) '${emp.Nic}' Property [Nic] not found on type [com.carepoint.model.Employee]
at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:120)
at org.apache.jsp.EmployeeList_jsp._jspx_meth_c_005fset_005f0(EmployeeList_jsp.java:659)
at org.apache.jsp.EmployeeList_jsp._jspx_meth_c_005fforEach_005f0(EmployeeList_jsp.java:558)
at org.apache.jsp.EmployeeList_jsp._jspService(EmployeeList_jsp.java:441)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
at com.carepoint.servlet.addEmployeeServlet.doPost(addEmployeeServlet.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
why cant i retrieve the data ?
Address the following things in your code:
Follow Java naming conventions e.g. Nic should be named as nic. You have violated the convention for all your variables.
Since you have already used the annotation, #WebServlet, you do not need to declare mapping in web.xml.
Given below is the Minimal, Complete, and Verifiable example:
Person.java:
package beans;
public class Person {
private String nic;
private String name;
private String email;
private String phone;
private String address;
public Person(String nic, String name, String email, String phone, String address) {
this.nic = nic;
this.name = name;
this.email = email;
this.phone = phone;
this.address = address;
}
public String getNic() {
return nic;
}
public void setNic(String nic) {
this.nic = nic;
}
}
Employee.java:
package beans;
public class Employee extends Person {
private String yearsOfExperience;
private String specialization;
private String salary;
public Employee(String nic, String name, String email, String phone, String address, String yearsOfExperience,
String specialization, String salary) {
super(nic, name, email, phone, address);
this.yearsOfExperience = yearsOfExperience;
this.specialization = specialization;
this.salary = salary;
}
}
AddEmployeeServlet.java:
package servlets;
import java.io.IOException;
import java.util.List;
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 beans.Employee;
#WebServlet("/addEmployeeServlet")
public class AddEmployeeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Employee> employeeDetails = List.of(new Employee("123", null, null, null, null, null, null, null),
new Employee("456", null, null, null, null, null, null, null));
request.setAttribute("employeeDetails", employeeDetails);
request.getRequestDispatcher("employees.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
employees.jsp:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<table>
<c:forEach var="emp" items="${employeeDetails}">
<tr>
<td>${emp.nic}</td>
</tr>
</c:forEach>
</table>
Output:
Related
I've done JUnit Tests for all my sql statements and it worked correctly but now I am trying to list out the data from my table in an html table and I am getting an HTTP Status 500 – Internal Server Error. Also When I do a main method in my MainController.java file I can print out the list of data.
MainController.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.student.bean.Student;
import com.student.dao.StudentDAO;
#Controller
public class MainController {
#Autowired
private StudentDAO studentDAO;
#RequestMapping(value="/")
public ModelAndView listStudent(ModelAndView model){
List<Student> listStudent = studentDAO.list();// line 24
model.addObject("listStudent", listStudent);
model.setViewName("index");
return model;
}
}
StudentDAOImpl.java
package com.student.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import com.student.bean.Student;
public class StudentDAOImpl implements StudentDAO {
private JdbcTemplate jdbcTemplate;
public StudentDAOImpl(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public static final String TABLE = "students";
#Override
public int save(Student obj) {
String qry = "insert into " + TABLE + "(id, first_name, last_name, gpa, major) values (?, ?, ?, ?,?)";
return jdbcTemplate.update(qry, obj.getId(), obj.getFirstName(), obj.getLastName(), obj.getGpa(),
obj.getMajor());
}
#Override
public int update(Student obj) {
String qry = "update " + TABLE + " set first_name = ?, last_name = ?, gpa = ?, major = ? where id = ?";
return jdbcTemplate.update(qry, obj.getFirstName(), obj.getLastName(), obj.getGpa(), obj.getMajor(),
obj.getId());
}
#Override
public Student get(Integer id) {
String qry = "select * from " + TABLE + " where id =" + id;
ResultSetExtractor<Student> extractor = new ResultSetExtractor<Student>() {
public Student extractData(ResultSet rs) throws SQLException, DataAccessException {
if (rs.next()) {
int studentId = rs.getInt("id");
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
double gpa = rs.getDouble("gpa");
String major = rs.getString("major");
return new Student(studentId, firstName, lastName, gpa, major);
}
return null;
}
};
return jdbcTemplate.query(qry, extractor);
}
#Override
public int delete(Integer id) {
String qry = "delete from " + TABLE + " where id =" + id;
return jdbcTemplate.update(qry);
}
#Override
public List<Student> list() {
String qry = "select * from " + TABLE;
RowMapper<Student> rowMapper = new RowMapper<Student>() {
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
int studentId = rs.getInt("id");
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
double gpa = rs.getDouble("gpa");
String major = rs.getString("major");
return new Student(studentId, firstName, lastName, gpa, major);
}
};
return jdbcTemplate.query(qry, rowMapper);//line 84
}
}
Error
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: students)
at org.sqlite.core.DB.newSQLException(DB.java:1010)
at org.sqlite.core.DB.newSQLException(DB.java:1022)
at org.sqlite.core.DB.throwex(DB.java:987)
at org.sqlite.core.NativeDB.prepare_utf8(Native Method)
at org.sqlite.core.NativeDB.prepare(NativeDB.java:134)
at org.sqlite.core.DB.prepare(DB.java:264)
at org.sqlite.jdbc3.JDBC3Statement.executeQuery(JDBC3Statement.java:73)
at org.springframework.jdbc.core.JdbcTemplate$1QueryStatementCallback.doInStatement(JdbcTemplate.java:438)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:375)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:451)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:461)
at com.student.dao.StudentDAOImpl.list(StudentDAOImpl.java:84)
at com.student.controller.MainController.listStudent(MainController.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)```
My Custom Validation Classes
1.UserAvailablity.java
package com.vicky.finalYearProject.customValidations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
#Constraint(validatedBy = UserAvailabilityValidator.class)
#Target({ElementType.METHOD, ElementType.FIELD})
#Retention(RetentionPolicy.RUNTIME)
public #interface UserAvailability {
public String message() default "Email is already Registered";
public Class<?>[] groups() default { };
public Class<? extends Payload>[] payload() default { };
}
2.UserAvailabilityValidator.class
package com.vicky.finalYearProject.customValidations;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import com.vicky.finalYearProject.Service.CheckUserAvailabilityService;
public class UserAvailabilityValidator implements ConstraintValidator<UserAvailability, String>{
#Autowired
CheckUserAvailabilityService availabilityService;
#Override
public void initialize(UserAvailability constraintAnnotation) {
ConstraintValidator.super.initialize(constraintAnnotation);
}
#Override
public boolean isValid(String email, ConstraintValidatorContext context) {
boolean available = false;
available = availabilityService.isAvailable(email);//return true or false
return available;
}
}
My Entities
User.java
package com.vicky.finalYearProject.Entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.springframework.stereotype.Component;
import com.vicky.finalYearProject.customValidations.UserAvailability;
#Entity
#Component
#Table( name = "customers",
uniqueConstraints=
#UniqueConstraint(columnNames={"email"})
)
public class User {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#NotNull
#Column(name = "email", length = 50)
#Pattern(regexp = "^([a-zA-Z0-9_\\-\\.]+)#([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})$")
#UserAvailability//custom validator
private String email;
#NotNull
#Column(name = "password")
#Length(min = 1 , message = "Enter Valid Password")
private String password;
#NotNull
#Column(name = "firstName")
#Length(min = 1 , message = "Enter Valid firstName")
private String firstName;
#NotNull
#Column(name = "middleName")
#Length(min = 1 , message = "Enter Valid middleName")
private String middleName;
#NotNull
#Column(name = "lastName")
#Length(min = 1 , message = "Enter Valid lastName")
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
return "User [id=" + id + ", email=" + email + ", password=" + password + ", firstName=" + firstName
+ ", middleName=" + middleName + ", lastName=" + lastName + "]";
}
}
My xml form Mapping with User class... by form:form
*
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix= "form" uri ="http://www.springframework.org/tags/form" %>
<body bgcolor = "black">
<h1 style="color: white">ADD USER INFORMATION</h1>
<hr>
<div style="color: white">
<form:form action ="${pageContext.request.contextPath}/user/conformation"
modelAttribute="user"
method="post">
First Name : <form:input path="firstName"/>
<form:errors path ="firstName" cssClass="error"/>
<br><br>
Middle Name: <form:input path="middleName"/>
<form:errors path ="middleName" cssClass="error"/>
<br><br>
Last Name: <form:input path="lastName"/>
<form:errors path ="lastName" cssClass="error"/>
<br><br>
Email : <form:input path="email"/>
<form:errors path ="email" cssClass="error"/>
<br><br>
password : <form:input type="password" path="password"/>
<form:errors path ="password" cssClass="error"/>
<br><br>
<input type = "Submit" value="next"/>
</form:form>
</div>
<hr>
cancle
</body>
</html>
*
ERROR I GOT when I submit My jsp page
Aug 11, 2020 12:29:33 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select user0_.id as id1_0_, user0_.email as email2_0_, user0_.firstName as firstNam3_0_, user0_.lastName as lastName4_0_, user0_.middleName as middleNa5_0_, user0_.password as password6_0_ from customers user0_ where user0_.email='sdghag#jsjdhak.zdhzg'
Aug 11, 2020 12:29:40 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/finalYearProject2] threw exception [Request processing failed; nested exception is javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.] with root cause
java.lang.NullPointerException
at com.vicky.finalYearProject.customValidations.UserAvailabilityValidator.isValid(UserAvailabilityValidator.java:26)
at com.vicky.finalYearProject.customValidations.UserAvailabilityValidator.isValid(UserAvailabilityValidator.java:1)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:180)
at org.hibernate.validator.internal.engine.constraintvalidation.SimpleConstraintTree.validateConstraints(SimpleConstraintTree.java:62)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:75)
at org.hibernate.validator.internal.metadata.core.MetaConstraint.doValidateConstraint(MetaConstraint.java:130)
at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:123)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:555)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:518)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:488)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:450)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:400)
at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:172)
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:116)
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:80)
at org.hibernate.action.internal.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:197)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:75)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:332)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:289)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:196)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:127)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:705)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:700)
at com.vicky.finalYearProject.DAO.UserDaoImplimantation.addUser(UserDaoImplimantation.java:16)
at com.vicky.finalYearProject.Service.PurchaseService.purchase(PurchaseService.java:46)
at com.vicky.finalYearProject.Controller.UserController.purchaseconformed(UserController.java:74)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:117)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:835)
Hibernaete.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">120699#mysqL</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/final_year_project</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
Spring Configuration
1.ViewResolverConfigrationClass.java
package com.vicky.finalYearProject.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.vicky.finalYearProject")
public class ViewResolverConfigrationClass {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewresolver = new InternalResourceViewResolver();
viewresolver.setPrefix("/WEB-INF/view/");
viewresolver.setSuffix(".jsp");
return viewresolver;
}
}
2.DispecherServletConfigClass.java
package com.vicky.finalYearProject.Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class DispecherServletConfigClass extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {ViewResolverConfigrationClass.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
I tried alot to figure out Even it works well without #UserAvailability in User.java Class
EVEN it works well with #UserAvailability when UserAvailabilityValidator.IsValid() returns false
Can Anyone please solve this issue For me...Thank you`enter code here
I THINK HIBERNATE IS AGAIN VALIDATING ALL CONSTRAINT AFTER SPRING THIS ERROR ERROR IS COME WHEN I TRY TO USE SAVE METHOD IN HIBERNATE
UserController.java
package com.vicky.finalYearProject.Controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.vicky.finalYearProject.Entity.Department;
import com.vicky.finalYearProject.Entity.Student;
import com.vicky.finalYearProject.Entity.University;
import com.vicky.finalYearProject.Service.StudentSignupService;
#Controller
#RequestMapping("/student")
public class StudentController {
#Autowired
Student student;
#Autowired
StudentSignupService studentSignupSvc;
List<String> universities;
List<String> departments;
#GetMapping("/signup")
public String studentLogin(Model model) {
universities = studentSignupSvc.getAllUniversity();
departments = studentSignupSvc.getAllDepartment();
model.addAttribute("student", student);
model.addAttribute("universityOptions", universities);
model.addAttribute("departmentOptions", departments);
return "student/signup";
}
#PostMapping("/conformation")
public String studentConformation(
#Valid #ModelAttribute("student") Student student,
BindingResult result,
Model model,
HttpServletRequest request) {
if(result.hasErrors()) {
model.addAttribute("universityOptions", universities);
model.addAttribute("departmentOptions", departments);
return "student/signup";
}
else {
String universityName = (String)request.getParameter("theUniversity");
String departmentName = (String)request.getParameter("theDepartment");
University university = studentSignupSvc.getUniversity(universityName);
Department department = studentSignupSvc.getDepartment(departmentName);
student.setUniversity(university);
student.setDepartment(department);
studentSignupSvc.signup(student); //CAUSE OF ERROR If I comment this line everything work fine
//and sigup service is perfactly auto wired i checked it.
return "student/studentConformation";
}
}
}
In the UserAvailabilityValidator class, is the availabilityService well autowired ? If the service is null, you will have this error.
Spring ought to inject dependencies into any ConstraintValidator-implementing class, even without marking them as #Bean or #Component, so I'm guessing you are missing the spring wiring.
Do you have a LocalValidatorFactoryBean in your spring configuration? From the documentation:
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
#Configuration
public class AppConfig {
#Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
}
I am trying to save a simple form input to the database using Spring MVC, Hibernate, and Spring form jstl.
When I added the line <form:input path="teamName" type="text" class="form-control" id="TeamNameInput" placeholder="Team Name"/>
I get this error: Neither BindingResult nor plain target object for bean name 'team' available as request attribute
Here's my code:
Team entity:
#Entity
#Table(name = "teams")
public class Team {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name = "teamname")
private String teamName;
//
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="users_teams",
joinColumns=#JoinColumn(name="teams_id"),
inverseJoinColumns=#JoinColumn(name="username"))
private List<User> users;
// getters and setters
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
public Team() {
// TODO Auto-generated constructor stub
}
public Team(String teamName) {
this.teamName = teamName;
}
/**
* #return the groupName
*/
public String getTeamName() {
return teamName;
}
/**
* #return the users
*/
public List<User> getUsers() {
return users;
}
/**
* #param users the users to set
*/
public void setUsers(List<User> users) {
this.users = users;
}
/**
* #param teamName the groupName to set
*/
public void setTeamName(String teamName) {
this.teamName = teamName;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Team [teamName=" + teamName + ", users=" +
users + "]";
}
}
User Entity:
#Entity
#Table(name="users")
public class User {
#Id
#Column(name="username")
private String userName;
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="users_teams",
joinColumns=#JoinColumn(name="username"),
inverseJoinColumns=#JoinColumn(name="teams_id"))
private List<Team> teams;
public User() {
// TODO Auto-generated constructor stub
}
public User(String userName) {
this.userName = userName;
}
/**
* #return the username
*/
public String getUsername() {
return userName;
}
/**
* #param username the username to set
*/
public void setUsername(String userName) {
this.userName = userName;
}
/**
* #return the teams
*/
public List<Team> getTeams() {
return teams;
}
/**
* #param teams the teams to set
*/
public void setTeams(List<Team> teams) {
this.teams = teams;
}
public void add(Team team) {
if (teams == null) {
teams = new ArrayList<>();
}
teams.add(team);
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "User [username=" + userName + ", teams=" +
teams + "]";
}
}
Controller:
#Controller
public class Controller {
#GetMapping("/")
public String listProjects(Model theModel) {
/*
* To get the username using Spring Security
*/
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
theModel.addAttribute("username", username);
/*
* Get the current user by username
*/
User user = userService.findByUsername(username);
/*
* Get the teams of the current user
*/
List<Team> theTeams = user.getTeams();
//Add teams to the model attribute
theModel.addAttribute("teams", theTeams);
System.out.println("This is a test " + username);
return "home";
}
#PostMapping("/saveTeam")
public String saveOrUpdateTeams(#ModelAttribute("team") Team
theTeam,BindingResult result) {
//GET USER BY USERNAME FROM DATABASE
Authentication auth =
SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
User user = userService.findByUsername(username);
// GET TEAMS OF CURRENT USER
user.add(theTeam);
userService.saveOrUpdate(user);
return "redirect:/";
}
JSP:
<form:form
action="${pageContext.request.contextPath }/saveTeam"
modelAttribute="team"
method="POST">
<div class="form-group">
<label for="TeamNameInput">Team Name</label>
<form:input path="teamName"
type="text" class="form-control" id="TeamNameInput"
placeholder="Team Name"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary"
data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save
changes</button>
</div>
</form:form>
And here's the error I am getting:
org.apache.jasper.JasperException: An exception occurred processing [/WEB-INF/view/home.jsp] at line [57]
54:
method="POST">
55: <div
class="form-group">
56: <label for="TeamNameInput">Team Name</label>
57: <form:input path="teamName"
58: type="text" class="form-control" id="TeamNameInput"
59: placeholder="Team Name"/>
60: </div>
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:593)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.security.web.header.HeaderWriterFilter$HeaderWriterRequestDispatcher.forward(HeaderWriterFilter.java:143)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
Root Cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'team' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:177)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:198)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:163)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:122)
org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:459)
org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:356)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:86)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:83)
org.apache.jsp.WEB_002dINF.view.home_jsp._jspx_meth_form_005finput_005f0(home_jsp.java:490)
org.apache.jsp.WEB_002dINF.view.home_jsp._jspx_meth_form_005fform_005f1(home_jsp.java:432)
org.apache.jsp.WEB_002dINF.view.home_jsp._jspService(home_jsp.java:197)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:444)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.security.web.header.HeaderWriterFilter$HeaderWriterRequestDispatcher.forward(HeaderWriterFilter.java:143)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
What is not working in my code?
I have tried to change #PostMapping to #RequestMapping(value = "/saveTeam", method = RequestMethod.POST)
and added <form:hidden path="id"/> but nothing was changed.
Why is my model attribute team is not detected?
As #JBNizet mentioned in his comment, I needed to add the model attribute "team" to the controller method used to display the form (which is mapped by "/").
I had to add the following two lines of code:
Team theTeam = new Team();
theModel.addAttribute("team", theTeam);
Here's the full code of the controller method:
#GetMapping("/")
public String listProjects(Model theModel) {
/*
* To get the username using Spring Security
*/
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
theModel.addAttribute("username", username);
Team theTeam = new Team();
theModel.addAttribute("team", theTeam);
/*
* Get the current user by username
*/
User user = userService.findByUsername(username);
/*
* Get the teams of the current user
*/
List<Team> theTeams = user.getTeams();
//Add teams to the model attribute
theModel.addAttribute("teams", theTeams);
System.out.println("This is a test " + username);
return "home";
}
I have a Spring Boot application that is connected to an Oracle DB.
This DB has a bunch of stored procedures and functions written in PL/SQL.
I am trying to call a very simple PL/SQL function that takes a string as input and returns a string as output. But I am getting an exception while calling it.
Error:
PLS-00306: wrong number or types of arguments in call to 'CHECK_ACTIVE_APPL'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
2019-03-05 11:14:57.456 ERROR WCD1122021 --- [nio-9090-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: Error calling CallableStatement.getMoreResults; SQL [PKG_USROUTER.CHECK_ACTIVE_APPL]; nested exception is org.hibernate.exception.SQLGrammarException: Error calling CallableStatement.getMoreResults] with root cause
java.sql.SQLException: ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'CHECK_ACTIVE_APPL'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CCallableStatement.doOall8(T4CCallableStatement.java:205)
at oracle.jdbc.driver.T4CCallableStatement.executeForRows(T4CCallableStatement.java:1043)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1336)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613)
at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:3714)
at oracle.jdbc.driver.OracleCallableStatement.execute(OracleCallableStatement.java:4755)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:1378)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.execute(ProxyPreparedStatement.java:44)
at com.zaxxer.hikari.pool.HikariProxyCallableStatement.execute(HikariProxyCallableStatement.java)
at org.hibernate.result.internal.OutputsImpl.<init>(OutputsImpl.java:52)
at org.hibernate.procedure.internal.ProcedureOutputsImpl.<init>(ProcedureOutputsImpl.java:34)
at org.hibernate.procedure.internal.ProcedureCallImpl.buildOutputs(ProcedureCallImpl.java:453)
at org.hibernate.procedure.internal.ProcedureCallImpl.getOutputs(ProcedureCallImpl.java:404)
at org.hibernate.procedure.internal.ProcedureCallImpl.outputs(ProcedureCallImpl.java:663)
at org.hibernate.procedure.internal.ProcedureCallImpl.execute(ProcedureCallImpl.java:646)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$ProcedureExecution.doExecute(JpaQueryExecution.java:332)
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:91)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:136)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:125)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:590)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:578)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy121.checkActiveAppl(Unknown Source)
at com.example.demo.service.LinkApplService.checkActiveAppl(LinkApplService.java:47)
at com.example.demo.controller.LinkApplController.getAllApplLinks(LinkApplController.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:870)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
PL/SQL Function:
FUNCTION CHECK_ACTIVE_APPL (appl IN VARCHAR2)
RETURN VARCHAR2 AS
activeFlag VARCHAR2(1);
BEGIN
SELECT appl_actv_cd INTO activeFlag FROM link_appl WHERE appl_id=appl;
RETURN activeFlag;
END CHECK_ACTIVE_APPL;
LinkApplController.java
#Controller
#RequestMapping("/applications")
#Log4j2
public class LinkApplController {
#Autowired
private LinkApplService linkApplService;
#GetMapping
public String getAllApplLinks(Model model) {
String activeFlag = linkApplService.checkActiveAppl("TITAN");
log.debug("################activeFlag: " + activeFlag);
return "index";
}
}
LinkApplService.java
#Service
public class LinkApplService {
#Autowired
private LinkApplRepository linkApplRepository;
public String checkActiveAppl(String linkApplId) {
return linkApplRepository.checkActiveAppl(linkApplId);
}
}
LinkApplRepository.java
#RepositoryRestResource
public interface LinkApplRepository extends PagingAndSortingRepository<LinkAppl, String> {
#Procedure(name = "checkActiveAppl")
String checkActiveAppl(#Param("linkApplId") String linkApplId);
}
LinkAppl.java
#Entity
#Table(name = "LINK_APPL")
#NamedStoredProcedureQueries({
#NamedStoredProcedureQuery(
name = "checkActiveAppl",
procedureName = "PKG_USROUTER.CHECK_ACTIVE_APPL",
parameters = {
#StoredProcedureParameter(name = "linkApplId", type = String.class, mode = ParameterMode.IN),
#StoredProcedureParameter(name = "activeFlag", type = String.class, mode = ParameterMode.OUT)
}
)
})
public class LinkAppl {
private String applId;
private String applDeTx;
private String seqNbResetCd;
private String intfMsgFrmtCd;
private String sndRcvCd;
private String applAcptMsgFrmtCd;
private String applActvCd;
private String sodEodIn;
private String linkNotesTx;
private String lastModByUsrId;
private Timestamp lastModTs;
private String sndCnctStsCd;
private Long maxSeqNb;
private String batIntfIn;
private String gfpSrcSiteCd;
private String rcvRterAckmentIn;
private String rcvMqCodIn;
private String fxApplIn;
private String rcvEodpAckmentIn;
}
Finally, this SO link (How to call Oracle Function or Procedure using Hibernate (EntityManager) or JPA 2) and this article (https://vladmihalcea.com/how-to-call-oracle-stored-procedures-and-functions-from-hibernate/) helped me resolve my issue. Changes I did to get things working.
LinkAppl.java
#Entity
#Table(name = "LINK_APPL")
public class LinkAppl {
private String applId;
private String applDeTx;
private String seqNbResetCd;
private String intfMsgFrmtCd;
private String sndRcvCd;
private String applAcptMsgFrmtCd;
private String applActvCd;
private String sodEodIn;
private String linkNotesTx;
private String lastModByUsrId;
private Timestamp lastModTs;
private String sndCnctStsCd;
private Long maxSeqNb;
private String batIntfIn;
private String gfpSrcSiteCd;
private String rcvRterAckmentIn;
private String rcvMqCodIn;
private String fxApplIn;
private String rcvEodpAckmentIn;
}
LinkApplService.java
#Service
#Log4j2
public class LinkApplService {
private static final String CHECK_ACTIVE_APPL_QUERY = "select PKG_USROUTER.CHECK_ACTIVE_APPL(:appl) from DUAL";
#PersistenceContext
private EntityManager em;
#Autowired
private LinkApplRepository linkApplRepository;
public String checkApplicationActive(String applicationId) {
String activeFlag = (String) em.createNativeQuery(CHECK_ACTIVE_APPL_QUERY)
.setParameter("appl", applicationId)
.getSingleResult();
log.debug("activeFlag: " + activeFlag);
return activeFlag;
}
}
LinkApplController.java
#Controller
#RequestMapping("/applications")
#Log4j2
public class LinkApplController {
#Autowired
private LinkApplService linkApplService;
#GetMapping
public String getAllApplLinks(Model model) {
String activeFlag = linkApplService.checkApplicationActive("TITAN");
log.debug("################activeFlag: " + activeFlag);
model.addAttribute("activeFlag", activeFlag);
return "index";
}
}
am working on Struts 2 radio button. I want to retrieve the list from my action class but it is giving following error
These are my files:
struts.xml -
<action name="radioButtonAction"
class="com.mkyong.common.action.RadioButtonAction" method="display">
<result name="none">/radiobutton.jsp</result>
</action>
<action name="resultAction" class="com.mkyong.common.action.RadioButtonAction">
<result name="success">/result.jsp</result>
</action>
radiobutton.jsp -
<body>
<h1>Struts 2 radio button example</h1>
<s:form action="resultAction" namespace="/">
<h2>
<s:radio label="Gender" name="yourGender" list="genders" value="defaultGenderValue" />
<s:radio label="Gender" name="yourLanguage" list="languages"
listKey="languageCode" listValue="languageDisplay" value="defaultLanguageValue" />
<s:radio label="Answer" name="yourAnswer" list="#{'1':'Yes','2':'No'}" value="2" />
</h2>
<s:submit value="submit" name="submit" />
</s:form>
</body>
RadioButtonAction.java --
package com.mkyong.common.action;
import java.util.ArrayList;
import java.util.List;
import com.mkyong.common.model.Language;
import com.opensymphony.xwork2.ActionSupport;
public class RadioButtonAction extends ActionSupport{
private List<String> genders;
private List<Language> languages ;
private String yourGender;
private String yourAnswer;
private String yourLanguage;
private static final String MALE = "male";
private static final String FEMALE = "female";
private static final String UNKNOWN = "unknown";
public RadioButtonAction(){
genders = new ArrayList<String>();
genders.add(MALE);
genders.add(FEMALE);
genders.add(UNKNOWN);
languages = new ArrayList<Language>();
languages.add( new Language("EN", "English") );
languages.add( new Language("FR", "France") );
languages.add( new Language("CN_ZH", "Chinese") );
languages.add( new Language("DE", "German") );
}
//return default gender value
public String getDefaultGenderValue(){
return UNKNOWN;
}
//return default language value
public String getDefaultLanguageValue(){
return "CN_ZH";
}
public String execute() {
return SUCCESS;
}
public String display() {
return NONE;
}
//getter ad setter methods
}
Languge.java --
package com.mkyong.common.model;
public class Language{
private String languageCode;
private String languageDisplay;
//getter and setter methods
public Language(String languageCode, String languageDisplay) {
this.languageCode = languageCode;
this.languageDisplay = languageDisplay;
}
}
Anything I did, still the same error persists,I know why this is happening...
SCHWERWIEGEND: Servlet.service() for servlet [jsp] in context with path [/RadioButton] threw exception [An exception occurred processing [radiobutton.jsp] at line [13]
10:
11: <h2>
12: <s:radio label="Gender" name="yourGender" list="genders" value="defaultGenderValue" />
13:
14: <s:radio label="Gender" name="yourLanguage" list="languages"
15: listKey="languageCode" listValue="languageDisplay" value="defaultLanguageValue" />
16:
Stacktrace:] with root cause
tag 'radio', field 'list', name 'yourGender': The requested list key 'genders' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
at org.apache.struts2.components.Component.fieldError(Component.java:257)
at org.apache.struts2.components.Component.findValue(Component.java:353)
at org.apache.struts2.components.ListUIBean.evaluateExtraParams(ListUIBean.java:81)
at org.apache.struts2.components.Radio.evaluateExtraParams(Radio.java:70)
at org.apache.struts2.components.UIBean.evaluateParams(UIBean.java:884)
at org.apache.struts2.components.UIBean.end(UIBean.java:533)
at org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:39)
at org.apache.jsp.radiobutton_jsp._jspx_meth_s_005fradio_005f0(radiobutton_jsp.java:249)
at org.apache.jsp.radiobutton_jsp._jspx_meth_s_005fform_005f0(radiobutton_jsp.java:192)
at org.apache.jsp.radiobutton_jsp._jspService(radiobutton_jsp.java:143)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:138)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
how can fix this ... Anyone has an idea?
You need getter methods for genders and languages.
public List getGenders() {
return genders;
}
Same for languages.