JSF interaction with database - java

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.

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.

PrimeFaces pagination not working and throwing exception

Iam using primefaces 5.0.i used data table in primefaces and displayed data from datatabase.Pagination tab displays in vertical wise doesn't display in proper manner. when i used pagination in datatable iam getting following exception
java.sql.SQLException: Listener refused the connection with the following error:
ORA-12519, TNS:no appropriate service handler found
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:480)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:413)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:508)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:203)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:510)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.invoice.customerlisting.getcustomerlist(customerlisting.java:22)
at sun.reflect.GeneratedMethodAccessor21.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:476)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:161)
at org.apache.el.parser.AstValue.getValue(AstValue.java:173)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIData.getValue(UIData.java:731)
at org.primefaces.component.datatable.DataTable.getValue(DataTable.java:867)
at org.primefaces.component.api.UIData.getDataModel(UIData.java:579)
at javax.faces.component.UIData.getRowCount(UIData.java:356)
at org.primefaces.component.api.UIData.calculateFirst(UIData.java:157)
at org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:176)
at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:82)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1786)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1779)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:125)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: oracle.net.ns.NetException: Listener refused the connection with the following error:
ORA-12519, TNS:no appropriate service handler found
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:361)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:966)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:292)
... 56 more
java.sql.SQLException: Listener refused the connection with the following error:
ORA-12519, TNS:no appropriate service handler found
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:480)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:413)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:508)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:203)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:510)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.invoice.customerlisting.getcustomerlist(customerlisting.java:22)
at sun.reflect.GeneratedMethodAccessor21.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:476)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:161)
at org.apache.el.parser.AstValue.getValue(AstValue.java:173)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIData.getValue(UIData.java:731)
at org.primefaces.component.datatable.DataTable.getValue(DataTable.java:867)
at org.primefaces.component.api.UIData.getDataModel(UIData.java:579)
at javax.faces.component.UIData.isRowAvailable(UIData.java:343)
at org.primefaces.component.api.UIData.setRowModel(UIData.java:422)
at org.primefaces.component.api.UIData.setRowIndex(UIData.java:401)
at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:683)
at org.primefaces.component.datatable.DataTableRenderer.encodeRegularTable(DataTableRenderer.java:234)
at org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:196)
at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:82)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1786)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1779)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:125)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: oracle.net.ns.NetException: Listener refused the connection with the following error:
ORA-12519, TNS:no appropriate service handler found
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:361)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:966)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:292)
... 59 more
Here is my jsf page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
>
<h:head></h:head>
<body>
<h:form>
<p:dataTable value="#{customerlisting.getcustomerlist()}" var="cml" style="width:25px;height:30px;" rows="3" paginatorPosition="bottom" paginator="true">
<p:column>
<f:facet name="header">
Customer Id
</f:facet>
<h:outputText value="#{cml.customerid}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">Customer Name</f:facet>
<h:outputText value="#{cml.customername}"></h:outputText>
</p:column>
<p:column><p:commandButton value="Edit"/></p:column>
<p:column><p:commandButton value="Delete"/></p:column>
</p:dataTable>
</h:form>
</body>
</html>
Here is my bean class
package com.invoice;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.SessionScoped;
public class customerlisting {
public List<customer> getcustomerlist()
{
List<customer> cs=new ArrayList<customer>();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","invoice","google");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select customerid,customername from customer order by customerid asc");
while(rs.next())
{
customer cm=new customer();
cm.setCustomerid(rs.getInt(1));
cm.setCustomername(rs.getString(2));
cs.add(cm);
}
}
catch(Exception e)
{
e.printStackTrace();
}
return cs;
}
}
My customer class is
package com.invoice;
public class customer {
int customerid;
String customername;
public String getCustomername() {
return customername;
}
public void setCustomername(String customername) {
this.customername = customername;
}
public int getCustomerid() {
return customerid;
}
public void setCustomerid(int customerid) {
this.customerid = customerid;
}
}
I'm totally stuck with this pagination in primefaces please could some one help me with good solution
You got a Problem with polluting your server and the database with db-connections. This leads to your error, the DB does not allow any further connections.
To avoid this you must close the connections and free the resources on your server, as well on the DB-server.
I will post a snippet with correct resource-handling. Doing this, I will also use correct Java Code Conventions, especially: Classnames should start with a uppercase letter.
Class.forName("oracle.jdbc.driver.OracleDriver");
List<Customer> cs = new ArrayList<Customer>();
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "invoice", "google");
stmt = con.createStatement();
rs = stmt.executeQuery("select customerid,customername from customer order by customerid asc");
while (rs.next()) {
Customer cm = new Customer();
cm.setCustomerid(rs.getInt(1));
cm.setCustomername(rs.getString(2));
cs.add(cm);
}
} catch (Exception e) {
LOG.error("Error connecting to DB: " + e.getMessage(), e);
} finally {
try {
// close resources
rs.close();
stmt.close();
con.close();
} catch (Exception e) {// ignore
} finally {
// setting everything to null (allows Objects to be GC'd)
rs = null;
stmt = null;
con = null;
}
}
return cs;
Bare in mind: gathering a connection to DB is expensive. Consider using ConnectionPooling (like c3p0). ConnectionPooling will open a set of connections to the db for you and reuse them.
Your error is here:
at com.invoice.customerlisting.getcustomerlist(customerlisting.java:22)
That is this line:
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","invoice","google");
You have a problem here on connection and not in primefaces. Isn't trying to open many connections? Try to open the connection just one time in some other method, and on getcustomerlist just create the statement.
public class customerlisting {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","invoice","google");
public List<customer> getcustomerlist()
{
List<customer> cs=new ArrayList<customer>();
try
{
Statement stmt=con.createStatement();

java.lang.NullPointerException in spring datasource

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.

Error while calling a method which passes request and response For storing a file to MYSQL databases

i am developing a project KNOWLEDGE based community sharing system.
in which users can login and share their resources to other Users....
I'm getting a problem in uploading a file to mysql database....
PS..my Instructor strictly Says to use MVC architecture So, i have to use the same..
So i have created only one Servlet named Controller.java.
here i will redirect to other java programs for calculations...
Here is the code for Controller.java
package com.kbcss.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kbcss.command.LoginCommand;
import com.kbcss.command.Commands;
import com.kbcss.command.ResourceCommand;
import com.kbcss.command.UserCommand;
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
public Controller() {super();}
#SuppressWarnings("rawtypes")
private Map commands = new HashMap();
#SuppressWarnings("unchecked")
public void init(ServletConfig config) throws ServletException{
super.init();
System.out.println("i am in init");
this.commands.put("login", new LoginCommand());
this.commands.put("user", new UserCommand());
this.commands.put("resource", new ResourceCommand());
System.out.println("i am about to exit init");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("i am in doget");
processCommand(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("i am in dopost");
processCommand(request, response);
}
private void processCommand(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("i am in processCommand");
String formAction = request.getParameter("form_action");
System.out.println("i am in processCommand state 2");
Commands command = (Commands) commands.get(formAction);
command.execute(request, response);
System.out.println("i am about to exit processCommand");
}
}
and here is the code for saving the resources to MY database table.... Named ResourceCommand .java
package com.kbcss.command;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.sql.DataSource;
import com.oreilly.servlet.MultipartRequest;
public class ResourceCommand extends HttpServlet implements Commands{
private static final long serialVersionUID = 1L;
public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//
// JNDI to connect to database
//
Connection conn = null;
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/tia");
conn = ds.getConnection();
//
// Save file(s) temporarily to filesystem
//
MultipartRequest multi = new MultipartRequest(request, "F:", 10*1024*1024);
Enumeration files = multi.getFileNames();
String filename = "";
File f = null;
while(files.hasMoreElements()) {
String name = (String)files.nextElement();
filename = multi.getFilesystemName(name);
String type = multi.getContentType(name);
f = multi.getFile(name);
}
//
// Insert file into database
//
InputStream is = new FileInputStream(f);
String sql = "INSERT INTO resource (`title`, `cat`, `user`, `filename`, `file`, `like`) VALUES (?, ?, ?, ?, ?, ?)"
;
PreparedStatement stmt = conn.prepareStatement(sql);
// Set some Title
stmt.setString(1, "some thing");
// Set some category
stmt.setString(2, ".net");
// Set some user
stmt.setString(3, "sri");
// Set Filename
stmt.setString(4, f.getName());
// Set the data
stmt.setBinaryStream(5, is, (int) f.length());
// Set Likes
stmt.setInt(6, 2);
stmt.executeUpdate();
is.close();
//
// Release connection
//
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) { ; }
stmt = null;
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) { ; }
conn = null;
}
} catch(Exception e) {
System.out.println(e);
}
}
}
And here is the jSP file where i will upload from....
<%# 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>UPLOAD FILE page</title></head>
<body>
<form method="post" action="Controller" enctype="multipart/form-data">
<input type="hidden" name="form_action" value="resource" />
<b>File to upload to database:</b>
<input type="file" name="attachment" size="36">
<input type="submit" value="Upload">
</form>
</body></html>
And this is the error i'm getting :(
INFO: Reloading Context with name [/KBCSS] is completed
i am in init
i am about to exit init
i am in dopost
i am in processCommand
i am in processCommand state 2
Oct 10, 2013 11:29:59 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Controller] in context with path [/KBCSS] threw exception
java.lang.NullPointerException
at com.kbcss.controller.Controller.processCommand(Controller.java:69)
at com.kbcss.controller.Controller.doPost(Controller.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
and by the way..i have created a Command.java interface here it is.
package com.kbcss.command;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public interface Commands {
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
Can any one guide me PLZZZZZZZZZZZZZZZZZZZZ
i'm stuck for a day and Half and have no clue what i'm doing...
This is what happens if u ask an electrical engineering student to do a Java Project !!!!
GREAT GREAT thanks from My side.....
Chances are that commands.get(formAction); is returning null, so command is also null. When you call command.execute(request, response);, you're trying to access something within a null object. That's going to get you a NullPointerException.
Use your print statements to determine what the exact value of formAction is when you get the exception. Then verify that you're putting a key for that string into commands (if it isn't "login", "user", or "resource", since you're already entering those).
One other thing that may be causing the problem is that you need to add class-types to your Map. Change it to:
private Map<String,Command> commands = new HashMap<String,Command>();
After you do that, you shouldn't have to suppress the warning on the Map.

Categories

Resources