java.lang.NullPointerException in spring datasource - java

I done the database table in MySql . I want connection between spring application and database .
For example , i am inserting value in edit-text it could be saved in Database(MySql)
But i got the error . I am new for spring , please need help .
Following is my error log.
16:05:44,784 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/SpringSample].[mvc-dispatcher]] (http-localhost/127.0.0.1:8080-1) Servlet.service() for servlet mvc-dispatcher threw exception: java.lang.NullPointerException
at com.rxoffice.test.controller.JDBCStudentDAO.findByStudentId(JDBCStudentDAO.java:65) [classes:]
at com.rxoffice.test.controller.Home.hi(Home.java:33) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_32]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [rt.jar:1.6.0_32]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [rt.jar:1.6.0_32]
at java.lang.reflect.Method.invoke(Method.java:597) [rt.jar:1.6.0_32]
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176) [spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:734) [jboss-servlet-api_3.0_spec-1.0.1.Final.jar:1.0.1.Final]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.1.Final.jar:1.0.1.Final]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.17.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.17.Final.jar:]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.17.Final.jar:]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.17.Final.jar:]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:165) [jboss-as-web-7.1.3.Final.jar:7.1.3.Final]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.17.Final.jar:]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.17.Final.jar:]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.17.Final.jar:]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:372) [jbossweb-7.0.17.Final.jar:]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.17.Final.jar:]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:679) [jbossweb-7.0.17.Final.jar:]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:931) [jbossweb-7.0.17.Final.jar:]
at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_32]
following are my files .
JDBCStudentDAO.java -
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
public class JDBCStudentDAO implements StudentDAO {
/*#Autowired
DataSource dataSource;*/
private DataSource dataSource;
JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public void insert(Student student) {
// TODO Auto-generated method stub
String sql = "INSERT INTO student_info " + "(id , name) VALUES (?, ?)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, student.getId());
ps.setString(2, student.getName());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
#Override
public Student findByStudentId(int stdId) {
// TODO Auto-generated method stub
String sql = "SELECT * FROM student_info WHERE id = ?";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, stdId);
Student student = null;
ResultSet rs = ps.executeQuery();
if (rs.next()) {
student = new Student(
rs.getInt("id"),
rs.getString("name")
);
}
rs.close();
ps.close();
return student;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}

As you mention in the comments, the error occurs at dataSource.getConnection() - meaning that dataSource is null. You have commented out autowiring that bean, so you're probably forgetting to explicitly setting it:
/*#Autowired DataSource dataSource;*/
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
The relevant parts of your applicationContext.xml file might shed more light on the problem - you might need
<context:annotation-config/>
<context:component-scan base-package="com.whatever.jdbc... , more.packages.to.scan,..."/>
or an explicit <property name="dataSource" ref="..." /> on the JDBCStudentDao bean XML config.
Cheers,

As stated in the comments, DataSource is null. The reason for that is that it hasn't been injected. To fix this, do the following:
1) Make sure JDBCStudentDAO is loaded by spring (applicationContext.xml should be loaded by whatever means, wither by explicitly loading the context or declaration in web.xml)
2) Make Sure DataSource is initialized in your applicationContext.xml or remove the comment before #Autowired
When you start your application, you should see messages that indicate that your datasource is bound (to the database configured in your applicationContext.xml) and that your DAO and entities have been loaded.

Related

How can I solve java.lang.Class.forName(Unknown Source) error?

I am trying to make a project on Servlets using JDBC. But there are some persistent errors in the error log like java.lang.Class.forName(Unknown Source), java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source), java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source), java.lang.Thread.run(Unknown Source) etc. How can I solve such errors from happening?
I am using Apache Tomcat v7.0, mySQL Community Server v5.7 and Eclipse IDE.
This my error log:
java.lang.ClassNotFoundException: com.mysql.driver.JDBC
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Register.register(Register.java:10)
at RegisterServlet.doPost(RegisterServlet.java:34)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
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)
This is the JDBC file code(Register.java):
import java.sql.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Register {
public static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile("^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
public static final Pattern VALID_PHONE_NUMBER_REGEX = Pattern.compile("[7-9][0-9]\\d{9}"); // ,Pattern.CASE_INSENSITIVE);
public static int register(String name,String user,String pass,String cpass,String email, String phone,String city,String state) throws ClassNotFoundException{
int status=0;
try{
Class.forName("com.mysql.driver.JDBC");
Connection con=DriverManager.getConnection("jdbc:sqlite:localhost:8080/Diary.db");
System.out.println("Database connected successfully!!");
PreparedStatement ps=con.prepareStatement("INSERT INTO Trial(name, user, pass, email, phone, city, state, authorized) values(?,?,?,?,?,?,?,?)");
if(pass!=null && cpass!=null && phone!=null && name!=null && user!=null && city!=null && state!=null){
Matcher matcher1 = VALID_EMAIL_ADDRESS_REGEX .matcher(email);
Matcher matcher2 = VALID_PHONE_NUMBER_REGEX .matcher(phone);
if((pass==cpass) && (matcher1.find()) && (matcher2.find())){
ps.setString(1,name);
ps.setString(2,user);
ps.setString(3,pass);
ps.setString(4,email);
ps.setString(5,phone);
ps.setString(6,city);
ps.setString(7,state);
ps.setString(8,"yes");
status=ps.executeUpdate();
}
else{
status = 0;
}
}
}catch(SQLException e){e.getMessage();}
return status;
}
}
This is my servlet (RegisterSevlet.java):
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
int status;
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String name=req.getParameter("name");
String user=req.getParameter("user");
String pass=req.getParameter("pass");
String cpass=req.getParameter("cpass");
String email=req.getParameter("email");
String phone=req.getParameter("phone");
String city=req.getParameter("city");
String state=req.getParameter("state");
try {
status = Register.register(name, user, pass, cpass, email, phone, city, state);
if(status > 0){
out.print("<p>You are successfully registered!</p>");
req.getRequestDispatcher("login.html").include(req, res);
}
else if(status == 0){
out.println("<p>Enter the information correctly!</p>");
res.sendRedirect("register.html");
}
req.getRequestDispatcher("#").include(req, res);
out.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
`Class.forName()`
throws ClassNotFoundException
You need to include multicatch statement for that (same catch for SQLException and ClassNotFoundException)
You can modify your catch statement to this:
catch (ClassNotFoundException | SQLException e)
{
e.printStackTrace();
}
Try this. You can use a multicatch statement wherever you need to catch multiple exceptions.
This exception is thrown whenever a class existed at compile time but not at run time.
Please check that at runtime ur classpath is correct and you are pointing to the library in question (in ur case the mysql connector jar).

Unexpected character ('a' (code 97)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')

I've just tried to calling index.jsp which sends a json to my rest project with http POST.
But it throws me this error:
I can't figure out where is the issue
Any tip? I haven't idea for this.
org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [jersey-serlvet] in context with path [/HibernateTutorialWeb] threw exception [org.codehaus.jackson.JsonParseException: Unexpected character ('a' (code 97)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
at [Source: org.apache.catalina.connector.CoyoteInputStream#24097548; line: 1, column: 2]] with root cause
org.codehaus.jackson.JsonParseException: Unexpected character ('a' (code 97)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
at [Source: org.apache.catalina.connector.CoyoteInputStream#24097548; line: 1, column: 2]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1213)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:375)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportUnexpectedChar(JsonParserMinimalBase.java:306)
at org.codehaus.jackson.impl.Utf8StreamParser._handleUnexpectedValue(Utf8StreamParser.java:1536)
at org.codehaus.jackson.impl.Utf8StreamParser._nextTokenNotInObject(Utf8StreamParser.java:432)
at org.codehaus.jackson.impl.Utf8StreamParser.nextToken(Utf8StreamParser.java:318)
at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2168)
at org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2106)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1004)
at org.codehaus.jackson.jaxrs.JacksonJsonProvider.readFrom(JacksonJsonProvider.java:410)
at com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.readFrom(JacksonProviderProxy.java:139)
at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:474)
at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123)
at com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:46)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
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)
index.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>Send jSon - put method</title>
</head>
<body>
<script>
//var people = {"address": "Address 12", "name": "twelve", "id": 12,"surname": "twelve"};
var people={"address": "hello"};
function sendobject(){
$.ajax({
type: "POST",
url: "http://localhost:8080/HibernateTutorialWeb/rest/person/post",
data: people,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" onclick="sendobject()" value="invia"> </input>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</body>
</<html>
PersonService . java
package com.ws.service;
import java.util.List;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import com.dao.*;
import com.model.*;
#Path("/person")
public class PersonService {
// try hello data
// http://localhost:8080/HibernateTutorialWeb/rest/person/hello/mario
#GET
#Path("/hello/{param}")
public Response getMsg(#PathParam("param") String msg) {
String output = "Jersey say hello : " + msg;
return Response.status(200).entity(output).build();
}
// http://localhost:8080/HibernateTutorialWeb/rest/person/2
#GET
#Path("{id}")
#Produces(MediaType.APPLICATION_JSON)
public Person getPersonById(#PathParam("id") int id) {
return new PersonDao().getPersonById(id);
// error for type of response incorrect
/*
* public ResponseBuilder getPersonById(#PathParam("id") int id){
* PersonDao pDao = new PersonDao (); if(pDao.getPersonById(id) != null)
* {return Response.status(200).entity(new
* PersonDao().getPersonById(id));} else{ return
* Response.status(200).entity("Utente id: "+ id + ", Rimosso"); }
*/
}
// //http://localhost:8080/HibernateTutorialWeb/rest/person/getAllJson
#GET
#Path("/getAllJson")
#Produces(MediaType.APPLICATION_JSON)
public List<Person> getAllJson() {
return new PersonDao().getAllPerson();
}
#GET
#Path("/xml/{id}")
#Produces(MediaType.APPLICATION_XML)
public Person getPersonByIdXML(#PathParam("id") int id) {
return new PersonDao().getPersonById(id);
}
#POST
#Path("/post")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response createUtenteJSON(Person person) {
new PersonDao().saveOrUpdate(person);
String result = "Person saved : " + person;
return Response.status(201).entity(result).build();
}
#PUT
#Consumes(MediaType.APPLICATION_JSON)
public Response updateUtente(Person person) {
if (person.getId() != 0) {
new PersonDao().saveOrUpdate(person);
return Response.ok(person, MediaType.APPLICATION_JSON).build();
} else {
return Response.status(Response.Status.BAD_REQUEST)
.entity("Specificare l'id dell'utente").build();
}
}
#DELETE
#Path("{id}")
public Response removePerson(#PathParam("id") Integer id) {
new PersonDao().deletePerson(id);
return Response.status(200).entity("Utente id: " + id + ", Rimosso")
.build();
}
}
PersonDao.java
package com.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.model.Person;
import com.util.SessionFactoryUtil;
public class PersonDao {
public void saveOrUpdate(Person person) {
Transaction trns = null;
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
if (person.getId() != 0) {
//if exists update obj
session.update(person);
} else {
session.save(person);
}
session.getTransaction().commit();
} catch (RuntimeException e) {
if (trns != null) {
trns.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
}
public void deletePerson(int id) {
Transaction trns = null;
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
Person person = (Person) session.load(Person.class, new Integer(id));
System.out.println("Deleted person :"+person.toString());
session.delete(person);
session.getTransaction().commit();
} catch (RuntimeException e) {
if (trns != null) {
trns.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
}
public List<Person> getAllPerson() {
List<Person> people = new ArrayList<Person>();
Transaction trns = null;
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
people = session.createQuery("from Person").list();
//session.getTransaction().commit();
} catch (RuntimeException e) {
if (trns != null) {
trns.rollback();
}
} finally {
session.flush();
session.close();
}
System.out.println("People list : \n");
for(int i=0;i<people.size();i++){
System.out.println(people.get(i));
}
return people;
}
public Person getPersonById(int id) {
Person person = null;
Transaction trns = null;
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
String queryString = "FROM Person WHERE id = :id";
Query query = session.createQuery(queryString);
query.setInteger("id", id);
person = (Person) query.uniqueResult();
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
session.flush();
session.close();
}
return person;
}
}
Updated :
on index.jsp
var people = JSON.parse({"address": "Indirizzo 12", "name": "dodici", "id": 12,"surname": "dodici"});
Now the error is this :
HTTP Status 500 - java.io.EOFException: No content to map to Object due to end of input
type Exception report
message java.io.EOFException: No content to map to Object due to end of input
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: java.io.EOFException: No content to map to Object due to end of input
com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:420)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.io.EOFException: No content to map to Object due to end of input
org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2173)
org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2106)
org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1004)
org.codehaus.jackson.jaxrs.JacksonJsonProvider.readFrom(JacksonJsonProvider.java:410)
com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.readFrom(JacksonProviderProxy.java:139)
com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:474)
com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123)
com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:46)
com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203)
com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Try to change the Object to JSON line:
var people={"address": "ciao"};
To:
var people=JSON.stringify(eval({"address": "ciao"}));
Make sure that Person class has the same param constructor you passing to it.
According to your image stack trace exception in the comment, The error occurs in the Hibernate with Exception StaleStateException which means:
Thrown when a version number or timestamp check failed, indicating
that the Session contained stale data (when using long transactions
with versioning). Also occurs if we try delete or update a row that
does not exist
This can be resolved by updating the object from database like refresh method in hibernate and then commit will persist the object in databse.
You can use merge method and commit, but here you will override the current data.
Using lock can also be resolved to change the state.
What the error message says is that the POST input the server received was not a valid JSON.
Probably what JQuery produces out of this input: var people={"address": "ciao"}; isn't what you expect. You can try sniffing what was actually transmitted over the HTTP request (using Firebug, Wireshark etc.).
Try using:
var people='{"address": "ciao"}';
instead of
var people={"address": "ciao"};
Solved by me,
There was an error on my jsp.
I was checking if it's a new user from the id.
Backend
if (person.getId() != 0) {
//if exists update obj
session.update(person);
} else {
session.save(person);
}
Jsp:
var people = JSON.stringify
(eval({"address": "Indirizzo 12", "name": "twelve", "id": 12, "surname": "twelve"}));
So with the Id, the dao try to update a record inexistent on db, and this is the cause of the error.
Now thy is my people var in jsp :
var people =
JSON.stringify(eval({"address": "Indirizzo 12", "name": "twelve","surname": "twelve"}));
It works good.

javax.persistence.PersistenceException: Unable to build entity manager factory org.hibernate.engine.jndi.JndiException: Unable to lookup JNDI name

Hi i am Creating my webservices and for data access i have used JPA(Hibernate), mysql and Glassfish server inside Netbeans IDE.
I am getting following exceptions while accessing:
**Client Side logs :**
----------------------
javax.persistence.PersistenceException: Unable to build entity manager factory org.hibernate.engine.jndi.JndiException: Unable to lookup JNDI name
javax.naming.NamingException: Lookup failed for hrdb;
in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl,
java.naming.factory.url.pkgs=com.sun.enterprise.naming}
[Root exception is javax.naming.NameNotFoundException: hrdb not found]
**Server side logs**
--------------------
Warning: StandardWrapperValve[com.mycompany.fkemployeeservices.ApplicationConfig]: Servlet.service() for servlet com.mycompany.fkemployeeservices.ApplicationConfig threw exception
javax.naming.NameNotFoundException: hrdb not found
at com.sun.enterprise.naming.impl.TransientContext.doLookup(TransientContext.java:237)
at com.sun.enterprise.naming.impl.TransientContext.lookup(TransientContext.java:204)
at com.sun.enterprise.naming.impl.SerialContextProviderImpl.lookup(SerialContextProviderImpl.java:66)
at com.sun.enterprise.naming.impl.LocalSerialContextProviderImpl.lookup(LocalSerialContextProviderImpl.java:114)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:478)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:622)
at javax.naming.InitialContext.lookup(InitialContext.java:421)
at javax.naming.InitialContext.lookup(InitialContext.java:421)
at org.hibernate.engine.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:114)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:115)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:399)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:73)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at entitycontrollers.ControllerFactory.getController(ControllerFactory.java:30)
at data.EmployeeDetailsOperations.<init>(EmployeeDetailsOperations.java:24)
at com.mycompany.fkemployeeservices.FKServicesCentralResource.getEmployeeDetails(FKServicesCentralResource.java:38)
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:483)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:195)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:387)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:331)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:103)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:254)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1028)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:372)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
Controller factory
package entitycontrollers;
import javax.persistence.Persistence;
public class ControllerFactory {
public static EvaEmpDetailsJpaController getController() {
return new EvaEmpDetailsJpaController(Persistence.createEntityManagerFactory("com.mycompany_FKEmployeeServices_war_1.0-SNAPSHOTPU"));
}
}
Entity Controllers
package entitycontrollers;
import dbentity.EvaEmpDetails;
import ApplicationSpecificClasses.exceptions.NonexistentEntityException;
import ApplicationSpecificClasses.exceptions.PreexistingEntityException;
import ApplicationSpecificClasses.exceptions.RollbackFailureException;
//import dbentity.EvaEmpDetails;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
/**
*
* #author mukul.kumar
*/
public class EvaEmpDetailsJpaController implements Serializable {
public EvaEmpDetailsJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;
public EvaEmpDetailsJpaController(EntityManagerFactory createEntityManagerFactory) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
this.emf = createEntityManagerFactory;
}
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(EvaEmpDetails evaEmpDetails) throws PreexistingEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
em.persist(evaEmpDetails);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
if (findEvaEmpDetails(evaEmpDetails.getId()) != null) {
throw new PreexistingEntityException("EvaEmpDetails " + evaEmpDetails + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(EvaEmpDetails evaEmpDetails) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
evaEmpDetails = em.merge(evaEmpDetails);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Long id = evaEmpDetails.getId();
if (findEvaEmpDetails(id) == null) {
throw new NonexistentEntityException("The evaEmpDetails with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Long id) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
EvaEmpDetails evaEmpDetails;
try {
evaEmpDetails = em.getReference(EvaEmpDetails.class, id);
evaEmpDetails.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The evaEmpDetails with id " + id + " no longer exists.", enfe);
}
em.remove(evaEmpDetails);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public List<EvaEmpDetails> findEvaEmpDetailsEntities() {
return findEvaEmpDetailsEntities(true, -1, -1);
}
public List<EvaEmpDetails> findEvaEmpDetailsEntities(int maxResults, int firstResult) {
return findEvaEmpDetailsEntities(false, maxResults, firstResult);
}
private List<EvaEmpDetails> findEvaEmpDetailsEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(EvaEmpDetails.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public EvaEmpDetails findEvaEmpDetails(Long id) {
EntityManager em = getEntityManager();
try {
return em.find(EvaEmpDetails.class, id);
} finally {
em.close();
}
}
public int getEvaEmpDetailsCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<EvaEmpDetails> rt = cq.from(EvaEmpDetails.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
Please comment for any other required files i need to put here.
In the pom.xml file dependencies of unknown.binary were created.
<dependency>
<groupId>unknown.binary</groupId>
<artifactId>hibernate-jpamodelgen-4.3.1.Final</artifactId>
<version>SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>unknown.binary</groupId>
<artifactId>mysql-connector-java-5.1.23-bin</artifactId>
<version>SNAPSHOT</version>
</dependency>
<dependency>
<groupId>unknown.binary</groupId>
<artifactId>hibernate-jpamodelgen-4.3.1.Final</artifactId>
<version>SNAPSHOT</version>
<scope>provided</scope>
</dependency>
On removing these dependencies Unable to build entity manager factory error is removed.

IllegalStateException Error

I am creating a login page where Engineer can login through their username started with "engg".
The problem is in the login page when I am giving the right input with right password it gives "Illegal State Exception".In wrong inputs it works fine.Like When i am giving "engg140" present in my oracle table it is giving the exception.the code is:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.java2d.pipe.GeneralCompositePipe;
import accessdb.Dao;
import accessdb.Getset;
public class AdminLogIn extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #return
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
String username=request.getParameter("username");
String password=request.getParameter("password");
Getset g=new Getset();
Dao dao=new Dao();
if(username.equals("") || password.equals(""))
{
response.sendRedirect("login.jsp");
}
else{
String newuname=username.substring(0,4);
// System.out.println(""+username);
if(newuname.equals("engg"))
{
ResultSet rs=dao.EnggLogInUseridCheck(g);
System.out.println(""+newuname);
while(rs.next())
{
String uname=rs.getString("uname");
System.out.println(""+uname);
if(uname.equals(username))
{
g.setuname(username);
System.out.println(""+username);
System.out.println(""+uname);
ResultSet rs1=dao.EnggLogInPasswordCheck(g);
while(rs1.next())
{
String password1=rs1.getString("password");
if(password1.equals(password))
{ System.out.println(""+password1);
System.out.println(""+password);
response.sendRedirect("engghome.jsp");
break;
}
else
{
response.sendRedirect("login.jsp");
return;
}
}
}
}
response.sendRedirect("login.jsp");
}
else
{
response.sendRedirect("login.jsp");
return;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The console output for a right input is as follows:
03:31:26,265 INFO [STDOUT] engg
03:31:26,265 INFO [STDOUT] engg172
03:31:26,265 INFO [STDOUT] engg140
03:31:26,265 INFO [STDOUT] engg140
03:31:26,265 INFO [STDOUT] engg140
03:31:26,281 INFO [STDOUT] 365125
03:31:26,281 INFO [STDOUT] 365125
03:31:26,281 INFO [STDOUT] engg141
03:31:26,281 ERROR [[AdminLogIn]] Servlet.service() for
servlet
AdminLogIn threw exception
java.lang.IllegalStateException
at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:435)
at AdminLogIn.doGet(AdminLogIn.java:80)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:179)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:241)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:580)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
You did not included the "caused by" sections of the stack trace, which are the most important part (actually, the WHOLE stack trace is important).
An, IllegalStateException on a sendRedirect() has to do with the HTTP protocol, and occurs when the response to the client has already been committed. At this point it is not possible to send a redirect any more as the HTTP headers have been sent (or at least queued to be sent) and cannot be changed. Somewhere in your code, in a method you haven't shown, you have written something to the output stream and caused the response to be committed.
This has nothing to do with the database.
I think the response is already committed which is not allowing you to do redirect.
Look here for more information:
Cause Of Response already committed
IllegalStateException while sendRedirect

JSF interaction with database

Following bean's database related code is working in simple Java application but when i use it within JSF page it is giving Java null pointer exception error.
Thanks in advance.
Bean class:-
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
#ManagedBean
#SessionScoped
public class Db implements Serializable{
int eId;
public int geteId() {
return eId;
}
public void seteId(int eId) {
this.eId = eId;
}
public static Connection getConnection() throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:#localhost:1521:globldb3";
String username = "scott";
String password = "tiger";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public String addEmployee() throws Exception{
Connection conn = null;
PreparedStatement pstmt = null;
try {
int a = this.eId;
conn = getConnection();
String query = "INSERT INTO c(n) VALUES(?)";
pstmt = conn.prepareStatement(query);
pstmt.setInt(1,a);
pstmt.executeUpdate(); // execute insert statement
return "success";
} catch (Exception e) {
e.printStackTrace();
return "failure";
} finally {
pstmt.close();
conn.close();
}
}
}
Following is my JSF page
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<body>
<h:form>
<p>Enter value <h:inputText value="#{db.eId}"/> </p>
<p> <h:commandButton value="Add record" action="#{db.addEmployee}"/> </p>
</h:form>
</body>
</html>
Following is stack trace
javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:787)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1252)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:306)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:558)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:379)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:259)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:281)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.NullPointerException
at erpJavaFiles.Employee.addEmployee(Employee.java:118)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 23 more
Here,
} finally {
pstmt.close();
conn.close();
}
you aren't checking if they are null before you close them. If an exception is been thrown upon connecting, they will stay null. Fix it as follows:
} finally {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}
There are no other potential causes for a NPE in the addEmployee() method. I see that you've an e.printStackTrace() call in the catch block. Read this one for the real cause of the problem. I guess that it's a ClassNotFoundException on the JDBC driver class, because you forgot to put the JDBC driver in /WEB-INF/lib folder of the webapp.

Categories

Resources