Reputation: 359
I'm learning about Servlets/jsps and have some test classes written. Everything seems to work as expected, the only problem I'm running into is being able to compile a simple Java class. This is the class:
package ilya.model;
public class DatabaseConnection {
public String getConnection()
{
String result;
try {
Class.forName("org.postgresql.Driver");
System.out.println("found the driver");
result = "Connection established!";
}
catch (ClassNotFoundException e)
{
System.out.println("No driver");
result = "No Connection";
}
return result;
}
}
The jsp trying to access it is pretty simple and I don't think it has anything to do with it. If anyone wants me to post it let me know.
Here's the Exception I receive when class is initialised for the first time:
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 15 in the generated java file
Only a type can be imported. ilya.model.DatabaseConnection resolves to a package
This compile fine in a regular Java project. Any ideas?
Update Here is the JSP file. It's actually working now. I tried the same project on a different machine and everything worked. Must be something wrong with Eclipse.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="ilya.model.BeerSuggestor, ilya.model.DatabaseConnection" %>
<%!
int count=0;
String connect;
public void jspInit() {
ServletConfig sconfig = getServletConfig();
String lname = sconfig.getInitParameter("lastName");
ServletContext context = sconfig.getServletContext();
context.setAttribute("lastName", lname);
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%-- DatabaseConnection intialized here --%>
<%
DatabaseConnection db = new DatabaseConnection();
connect = db.getConnection();
%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>The count is: <%= this.count++ %></p>
<p>The count is: <%= 500 %></p>
<p>The count is: <%= config.getInitParameter("lastName") %></p>
<%-- Value of connect printed here --%>
<p>The connection result is: <%=" " + connect %>
</body>
</html>
Upvotes: 1
Views: 2956
Reputation: 959
Agreed with previous comments. It looks like, you are trying to establish a database connection directly from your JSP.
Please check the line in JSP, specially where you are setting the driver in jsp.
You can try this from your jsp as well.
<%
Class.forName("org.postgresql.Driver");
Connection myConn=DriverManager.getConnection("jdbcostgresql://localhost/db_name?user=db_user&password=db_pwd");
%>
Upvotes: 0
Reputation: 75426
You cannot have plain Java in JSP files as you show here..
Create a separate class in the appropriate source folder inside Eclipse for this.
Upvotes: 1