So I'm starting a web application and I want to use JSP pages (I've used them before) to access dynamically to the database and retrieve data from different tables.
I have by now a basic DatabaseHelper class, an App class that only tests the DB helper connection and a simple query, and a jsp file. The problem I'm facing is that the Database connection works great if run from the App.java class, but if I run it from the JSP file it will throw a SQLException saying it didn't find a suitable driver. (I'll leave code and error message below)
I've tried different options I've read here in StackOverflow and other pages: I put the driver in the server's classpath, in the WEB-INF/lib, in the project's build path as external JAR (this one works for the Java app class mentioned before)...
And here is the environment:
Database: Microsoft SQL Server 2017
Driver: sqljdbc42.jar
Server: Glassfish 4.0
IDE: Eclipse Oxygen.3
So any hint on how can I solve this problem and use the Database helper from the jsp file will be happily welcome.
Thanks!
Error message:
[2018-03-28T12:39:48.883+0200] [glassfish 4.0] [SEVERE] [] [pl.mais.db.DBHelper] [tid: _ThreadID=21 _ThreadName=http-listener-1(3)] [timeMillis: 1522233588883] [levelValue: 1000] [[
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost;databaseName=campus_db;user=******;password=*****
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at pl.mais.db.DBHelper.open(DBHelper.java:41)
at org.apache.jsp.index_jsp._jspService(index_jsp.java:58)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
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:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:748)
]]
App.java
package pl.mais.general;
import pl.mais.db.DBHelper;
public class App {
public static void main (String[] args) {
DBHelper db = new DBHelper();
db.open();
db.testSelectFaculties();
db.close();
}
}
DBHelper.java
package pl.mais.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author sergi
*
*/
public class DBHelper {
// JDBC driver name and database URL
private final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private final String DB_URL = "jdbc:sqlserver://localhost;databaseName=campus_db;";
// Database credentials
private static final String DB_USER = "*****";
private static final String DB_PASS = "*****";
private Connection conn = null;
private Statement stmt = null;
public DBHelper() {
try {
Class.forName(JDBC_DRIVER);
} catch (Exception e) {
e.printStackTrace();
}
}
public void open() {
try {
String connectionUrl = DB_URL + "user=" + DB_USER + ";password=" + DB_PASS;
//System.out.println("Connecting to database...");
conn = DriverManager.getConnection(connectionUrl);
//System.out.println("Creating statement...");
stmt = conn.createStatement();
} catch (SQLException ex) {
Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void close() {
try {
stmt.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String[] testSelectFaculties() {
try {
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT * FROM faculties";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
ArrayList<String> results = new ArrayList<String>();
// Iterate through the data in the result set and display it.
while (rs.next()) {
results.add(rs.getString(1) + " - " + rs.getString(2));
System.out.println(rs.getString(1) + " - " + rs.getString(2));
}
return (String[])results.toArray();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
index.jsp
<%#page import="pl.mais.db.DBHelper"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
DBHelper db = new DBHelper();
db.open();
String[] faculties = db.testSelectFaculties();
db.close();
for (int i = 0; i < faculties.length; i++) {
%>
<h2>
<%=
faculties[i]
%>
</h2>
<%
}
%>
</body>
</html>
Making the JDBC Driver JAR Files Accessible:
To integrate the JDBC driver into a GlassFish Server domain, copy the JAR files into the domain-dir/lib directory, then restart the server. This makes classes accessible to all applications or modules deployed on servers that share the same configuration.
Source: Oracle documentation.
Related
I'm trying to send variables between jsp and servlets, but I got this error that I still can't figure out why. It keeps sending HTTP Status 500 error.
it sending HTTP status 500 eror and java.lang.NullPointerException
but when i test java class in junit it ran fine.
this is jsp:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page import="model.StudentDao"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Student</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Student</h1>
<table class="table">
<tr>
<th>Student ID</th>
<th>Student Name</th>
</tr>
<c:forEach items="${requestScope.students}" var="student">
<tr>
<td><c:out value="${student.getStudentId()}"/></td>
<td><c:out value="${student.getStudentName()}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
and this my servlet:
package controller;
import...
#WebServlet("/StudentListServlet")
public class StudentListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public StudentListServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DbConnect dbConnect = new DbConnect();
Connection connection = dbConnect.connect();
StudentDao studentDao = new StudentDao(connection);
ArrayList<Student> students = null;
try {
students = studentDao.findAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("students", students);
request.getRequestDispatcher("student.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
StudentDao :
package model;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class StudentDao {
private Connection connection;
public StudentDao(Connection connection) {
super();
this.connection = connection;
}
public ArrayList<Student> findAll() throws SQLException{
ArrayList<Student> students = new ArrayList<>();
Student student = null;
Statement statement = this.connection.createStatement();
String sqlText = "SELECT * FROM student";
ResultSet resultSet = statement.executeQuery(sqlText);
while(resultSet.next()){
student = new Student();
student.setStudentId(resultSet.getString("student_Id"));
student.setStudentName(resultSet.getString("student_Name"));
students.add(student);
}
resultSet.close();
statement.close();
return students;
}
}
DbConnect:
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnect {
private static final String URL = "jdbc:mysql://localhost:3306/university";
private static final String USER = "root";
private static final String PASSWORD = "";
private Connection connection;
public Connection connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
this.connection = DriverManager.getConnection(URL, USER, PASSWORD);
if(!this.connection.isClosed())
System.out.println("MySQL Connected");
else
System.out.println("MySQL Connect fail!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return this.connection;
}
public void close() throws SQLException {
this.connection.close();
}
}
Stack Trace :
SEVERE: Servlet.service() for servlet [controller.StudentListServlet] in context with path [/MySQLDemo] threw exception
java.lang.NullPointerException
at model.StudentDao.findAll(StudentDao.java:21)
at controller.StudentListServlet.doGet(StudentListServlet.java:34)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Sorry for the long post.
anyone with an idea why this get error?
You are not loading the jdbc driver in your servelet
you can the jdbc driver as follows:
String driver = "com.mysql.jdbc.Driver";
// Load the JDBC driver
Class driver_class = Class.forName(driver);
This is how far i have come trying to respond with a List<> of Users to a Client . Every time i get Error 500 so i tried to respond with just a String and it worked so there is not a problem with the server/client communication. I searched the Internet and i found some examples that they returned Lists<> without error but i can't get mine to work.
User Class
package org.cs131111.user;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "user")
public class User implements Serializable{
private String studentID;
private String Fname;
private String Lname;
private int semester;
public User(){}
public User(String sID,String fname,String lname,int sem){
this.studentID=sID;
this.Fname=fname;
this.Lname=lname;
this.semester = sem;
}
public String getId() {
return studentID;
}
#XmlElement
public void setId(String id) {
this.studentID = id;
}
public String getName() {
return Fname+"_"+Lname;
}
#XmlElement
public void setFName(String name) {
this.Fname = name;
}
#XmlElement
public void setLName(String name) {
this.Lname = name;
}
public int getSemester() {
return semester;
}
#XmlElement
public void setSemester(int semester) {
this.semester = semester;
}
}
UserList class
package org.cs131111.user;
import org.cs131111.db.DatabaseConnection;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class UserList {
public List<User> list = null;
public List<User> getAllUsers(){
User stud = null;
DatabaseConnection newc = null;
newc = new DatabaseConnection();
list = new ArrayList<User>();
try {
newc.results=newc.query.executeQuery("select * from `students`");
while(newc.results.next()){
stud = new User(newc.results.getString("studentid"),newc.results.getString("fname"),newc.results.getString("lname"),newc.results.getInt("semester"));
list.add(stud);
System.out.println(stud.getId()+" "+stud.getName());
}
} catch (SQLException ex) {
Logger.getLogger(UserList.class.getName()).log(Level.SEVERE, null, ex);
}
newc.close();
return list;
}
}
UserService class
package org.cs131111.user;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/UserService")
public class UserService {
UserList userOb = new UserList();
#GET
#Path("/users")
#Produces(MediaType.APPLICATION_XML)
public List<User> getUsers(){
final List<User> users = userOb.getAllUsers();
return users;
}
}
The Client
<%#page import="java.util.List"%>
<%#page import="User.User"%>
<%#page import="java.io.IOException"%>
<%#page import="java.net.MalformedURLException"%>
<%#page import="java.io.InputStreamReader"%>
<%#page import="java.io.BufferedReader"%>
<%#page import="java.net.HttpURLConnection"%>
<%#page import="java.net.URL"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<%
try {
URL url = new URL("http://localhost:11118/EclassServer/webresources/UserService/users");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/xml");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
List<User> u= (List<User>)conn.getContent();
out.println("Output from Server .... \n");
String test=u.get(1).getId();
out.println(test);
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
%>
</body>
</html>
Server's stack trace
Warning: StandardWrapperValve[jsp]: Servlet.service() for servlet jsp threw exception
java.lang.RuntimeException: Failed : HTTP error code : 500
at org.apache.jsp.clientGet_jsp._jspService(clientGet_jsp.java:80)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
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)
I can't post this as a comment so here it is. You can't really expect HttpUrlConnection.getContent to return a List of User instances. From the Javadoc
This method first determines the content type of the object by calling
the getContentType method. If this is the first time that the
application has seen that specific content type, a content handler for
that content type is created:
If the application has set up a content handler factory instance using
the setContentHandlerFactory method, the createContentHandler method
of that instance is called with the content type as an argument; the
result is a content handler for that content type. If no content
handler factory has yet been set up, or if the factory's
createContentHandler method returns null, then the application loads
the class named:
The usual way to get the content (when using HttpUrlConnection) is by using BufferedReader in combination with InputStreamReader something like
if(resCode==200){
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
stringBuilder = new StringBuilder();
String line=null;
while((line = reader.readLine()) != null){
stringBuilder.append(line + "\n");
}
}
But even now you will only get your User list as one large string (formatted as XML) and you should use an object mapper to convert the content/entity string to a List of User instances.
If, on the other hand, you used a Jersey client, it would be able to do the conversion automatically for you (it uses JAXB under the hood). Your Jersey client code might look something like (not tested)
WebTarget target = client.target(UriBuilder.fromUri("http://localhost:11118/EclassServer/webresources/UserService/users").build());
GenericType<List<User>> genType = new GenericType<List<User>>();
List<User> userList =(String) target.request().accept(MediaType.XML_APPLICATION).get(genType);
You don't have a correct root element. You've added the #XmlRootElement annotation to the User class, but it's not the root element as you're returning a list of users not a single user.
I recommend to specify a XSD and generate the JAXB classes rather than writing them yourself.
I need help. I'm developing app for uploading text files. For this moment I encountered error which I cannot clearly understand. Here is my code:
Index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Servlet based API for querying text file</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
</head>
<body>
<h3>Please choose file</h3>
<div class="container">
<form action="TextProccessing" method="post"
enctype="multipart/form-data">
<div class="form-group">
<label for="browseTxt">Upload file:</label>
<input type="file" name="browseTxt" id="browseTxt" value="select text file">
<p class="help-block">
<b>Note:</b> Please choose .txt file only
</p>
</div>
<BUTTON class="btn btn-default" type="submit">Upload</BUTTON>
</form>
</div>
<h2>Place for text</h2>
<div class="container"></div>
</body>
</html>
TextProccessing
package com.controller;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#MultipartConfig(maxFileSize = 16177215)
public class TextProccessing extends HttpServlet {
private static final long serialVersionUID = 1L;
private final static String RESULT_PAGE = "/result.jsp";
private final String dbURL = "jdbc:mysql://127.0.0.1:3306/textfilesdb";
private final String dbUser = "root";
private final String dbPassword = "root";
// for this moment
private String file_Name_test = "file_Name_test";
private String file_size_test = "file_size_test";
private String fileCreationDate_test = "fileCreationDate_test";
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
InputStream inputStream = null;
Part filePart = request.getPart("browseTxt");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
// connects to the database
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPassword);
// constructs SQL statement
String sql = "INSERT INTO files(file_Name, file_size, fileCreationDate, text_file) values (?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, file_Name_test);
statement.setString(2, file_size_test);
statement.setString(3, fileCreationDate_test);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(4, inputStream);
}
// sends the statement to the database server
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
getServletContext().getRequestDispatcher(RESULT_PAGE).forward(request, response);
}
}
}
it seems ok but I have such error stacktrace
browseTxt 1189 text/plain
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near '?le_Name,
file_size, ?leCreationDate, text_file) values ('?le_Name_test',
'file_' at line 1 at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown
Source) at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
Source) at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:400) at
com.mysql.jdbc.Util.getInstance(Util.java:383) at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:980) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783) at
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447) at
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594) at
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545) at
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901)
at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2113)
at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2049)
at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2034)
at com.controller.TextProccessing.doPost(TextProccessing.java:68) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:648) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
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)
And my DB structure
create database TextFilesDB;
use TextFilesDB;
CREATE TABLE files ( id int(11) NOT NULL AUTO_INCREMENT,
file_Name varchar(45) NOT NULL, file_size varchar(45) DEFAULT
NULL, fileCreationDate varchar(45) DEFAULT NULL, text_file
mediumblob, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf16
It seems that you have some format problem with the columns names. Can you try to replace
INSERT INTO files(file_Name, file_size, fileCreationDate, text_file) values (?, ?, ?, ?)
by
INSERT INTO files(file_Name, file_size, fileCreationDate, text_file) values (?, ?, ?, ?)
Can anyone please tell me to use which jdbc driver to connect with oracle 9.0.1.1?
i'm using jdk1.6.
i've used classes12 and ojdbc6 but they are causing errors.
Following is my code
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 exception is comeing while using ojdbc6.jar.
java.sql.SQLException: ORA-03120: two-task conversion routine: integer overflow
Following is stack trace of above exception
java.sql.SQLException: ORA-03120: two-task conversion routine: integer overflow
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:440)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:837)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:445)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1010)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1315)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3576)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3657)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1350)
at erpJavaFiles.Employee.addEmployee(Employee.java:113)
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)
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.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:237)
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)
try ojdbc14.jar. it will work definetely.
You should not be using classes12.jar; that's for JDK 1.2. ojdbc6.jar is what you want; that's appropriate for JDK 6.
Check the value of a and the data type of column n in table c. Ensure column n has a set length, i.e. NUMBER(10,0) vs just NUMBER.
I would try the query in SQL Developer too. If you don't already have it you can get it here.
There's Oracle bug 5671074 in some 9i versions that causes this exception when server and client have different "endianness".
Are you sure it's not your case?
I need to display the newly generated excel (from tables using Apache POI) in a web browser (whatever it is, Firefox, Opera or IE). I've created the JSP file with
contentType="application/vnd.ms-excel"
But I'm not getting it.
Here's my code snippet :
<%#page session="true" contentType="application/vnd.ms-excel" pageEncoding="UTF-8"%>
<%#page import="org.apache.poi.ss.usermodel.CellStyle"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%#page import="org.apache.poi.ss.usermodel.CreationHelper"%>
<%#page import="org.apache.poi.hssf.usermodel.HSSFCell"%>
<%#page import="org.apache.poi.hssf.usermodel.HSSFRow"%>
<%#page import="org.apache.poi.hssf.usermodel.HSSFWorkbook"%>
<%#page import="org.apache.poi.hssf.usermodel.HSSFSheet"%>
<html>
<head>
<%!
int r=0;
HSSFWorkbook book;
HSSFSheet sheet;
HSSFRow row;
CreationHelper createHelper = book.getCreationHelper();
Connection conn;
Statement stmt;
ResultSet rs;
%>
<title>Report</title>
<%
book = new HSSFWorkbook();
sheet = book.createSheet("Report");
%>
</head>
<body>
<%
try {
// Header of the Excel File
row = sheet.createRow(r);
row.createCell(0).setCellValue("Visit ID");
row.createCell(1).setCellValue("Carrier Name");
row.createCell(2).setCellValue("Phone Number");
row.createCell(3).setCellValue("Patient Name");
row.createCell(4).setCellValue("Subscriber ID");
row.createCell(5).setCellValue("Subscriber Name");
row.createCell(6).setCellValue("Chart Number");
row.createCell(7).setCellValue("Date Of Birth");
row.createCell(8).setCellValue("Subscriber Employer");
row.createCell(9).setCellValue("Service Date");
row.createCell(10).setCellValue("Provider Name");
row.createCell(11).setCellValue("CPT Code");
row.createCell(12).setCellValue("Aging Date");
row.createCell(13).setCellValue("Total");
row.createCell(14).setCellValue("Follow Up Notes");
row.createCell(15).setCellValue("Internal Status Code");
CellStyle cellStyle = book.createCellStyle();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("MM/dd/yyyy"));
Statement stNotes;
ResultSet rsNotes;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/maintain", "root", "root");
stmt = conn.createStatement();
stNotes = conn.createStatement();
rs = stmt.executeQuery("SELECT b.VisitID, b.CarrierName, b.PhoneNum, b.PatientName, "
+ "b.SubscriberID, b.SubscriberName, b.ChartNum, b.DoB, b.SubscriberEmp, "
+ "b.ServiceDate, b.ProviderName, b.CPTCode, b.BillingDate, b.BalanceAmt "
+ "FROM billing b INNER JOIN followup f ON b.VisitID = f.VisitID GROUP BY VisitID");
while(rs.next()) {
r++;
row = sheet.createRow(r);
row.createCell(0).setCellValue(rs.getString("VisitID"));
row.createCell(1).setCellValue(rs.getString("CarrierName"));
row.createCell(2).setCellValue(rs.getString("PhoneNum"));
row.createCell(3).setCellValue(rs.getString("PatientName"));
row.createCell(4).setCellValue(rs.getString("SubscriberID"));
row.createCell(5).setCellValue(rs.getString("SubscriberName"));
row.createCell(6).setCellValue(rs.getString("ChartNum"));
row.createCell(7).setCellValue(rs.getString("DoB"));
row.createCell(8).setCellValue(rs.getString("SubscriberEmp"));
row.createCell(9).setCellValue(rs.getString("ServiceDate"));
row.createCell(9).setCellStyle(cellStyle);
row.createCell(10).setCellValue(rs.getString("ProviderName"));
row.createCell(11).setCellValue(rs.getString("CPTCode"));
row.createCell(12).setCellValue(rs.getString("BillingDate"));
row.createCell(12).setCellStyle(cellStyle);
row.createCell(13).setCellValue(rs.getString("BalanceAmt"));
rsNotes = stNotes.executeQuery("SELECT Date, InternalStatusCode, FollowUpNote "
+ "FROM followup WHERE VisitID='" + rs.getString("VisitID") + "' ORDER BY Date");
while(rsNotes.next()) {
row.createCell(14).setCellValue(rsNotes.getString("Date") + " - " + rsNotes.getString("FollowUpNote"));
row.createCell(15).setCellValue(rs.getString("VisitID"));
}
}
}
catch(ClassNotFoundException cnf) {
out.print("<br> Error : MySQL Driver not found. <br>");
}
catch(Exception ex) {
out.print("Error : <br>" + ex);
}
%>
</body>
</html>
I'm getting this exception with Tomcat 6.0.26 :
exception
org.apache.jasper.JasperException: java.lang.NullPointerException
org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:156)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:329)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
root cause
java.lang.NullPointerException
org.apache.jsp.GetReport_jsp.<init>(GetReport_jsp.java:29)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
java.lang.reflect.Constructor.newInstance(Constructor.java:513)
java.lang.Class.newInstance0(Class.java:355)
java.lang.Class.newInstance(Class.java:308)
org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:145)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:329)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
Did I miss something or anything wrong?
Can anybody help me to get rid of this problem?
Thanx in advance.
The way you are trying to do it doesn't make any sense. You can't mix HTML with Excel like that. Better create a servlet instead of a JSP page and let this servlet output only the Excel file and nothing else.
Something like this:
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
// ... plus all the other libs you need
public class ExcelServlet extends HttpServlet {
public void doGet (HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
HSSFWorkbook book;
// ...
// fill the book
// ...
res.setContentType("application/vnd.ms-excel");
book.write(res.getOutputStream());
res.getOutputStream().close();
}
}
HSSFWorkbook book;
HSSFSheet sheet;
HSSFRow row;
CreationHelper createHelper = book.getCreationHelper();
You are using the book object before initializing it.
I'd recommend not doing it this way.
Scriptlet code in JSPs is simply wrong.
Putting database access in a page like this isn't good, either.
A better approach would be Spring MVC and its JExcelView.
Here's a tip on how to debug JSP exceptions:
in the stacktrace, this class
java.lang.NullPointerException
org.apache.jsp.GetReport_jsp.<init>(GetReport_jsp.java:29)
is the generated java class for your GetReport.jsp. You can look in the $TOMCAT_HOME/work/<enginename>/<hostname>/<appname> folder to see the actual code generated, and see what exactly is at line 29.
Take a look at WorkbookTag project from SourceForge which does exactly what you need: HTML worksheet rendering using Apache POI... WorkbookTag