i am new to web programming. i am trying to connect database using jsp with odbc. i have already written a java code for this. now i need to run on Tomcat server. so i choose JSP to do this job.But this is showing me void type not allowed here and erors. how to run this code using jsp. what are my mistakes. please help me to solve in this.
now this is my code
<%#page import="java.sql.*"%>
<%#page import="java.util.*" %>
<%#page import="java.util.logging.Level"%>
<%#page import="java.util.logging.Logger"%>
<%!
int i=0,j=0,k=0;
Connection conn=null;
Connection connection=null;
static int count=0;
String Cname[]=null;
String Title[]=null;
Statement stmt1=null;
ResultSet NumOfRows=null;
Statement stmt2=null;
ResultSet SpreadsheetValues=null;
Statement stmt3=null;
ResultSet rs3=null;
int RowCount;
//this static function required to connect excel database
static
{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("Exception in connecting to DB"+e.getMessage());
}
}
// connect Sql database
void ConnectSqlDB() {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:ServerDB","sa","sqladmin");
System.out.println("MSSQL connected " +"<br>");
}catch(Exception e){
e.printStackTrace();
System.out.println("Exception in connecting to DB"+e.getMessage());
}
}
void ConnectExcelDB() throws SQLException{
conn=DriverManager.getConnection("jdbc:odbc:spreadsheetdb","","");
}
void getRowcount() throws SQLException{
stmt1=conn.createStatement();
String Qs1="select count(*) from [Sheet1$]";
NumOfRows=stmt1.executeQuery(Qs1);
while(NumOfRows.next()){
Rowcount=NumOfRows.getInt(1);
}
NumOfRows.close();
}
void getExcelValues() throws SQLException{
stmt2=conn.createStatement();
String Qs2="select * from [Sheet1$]";
SpreadsheetValues=stmt2.executeQuery(Qs2);
Cname=new String[Rowcount];
Title=new String[Rowcount];
while(SpreadsheetValues.next()){
// Assigning Spread sheet values to String array
Cname[j]=SpreadsheetValues.getString("Cname");
Title[j]=SpreadsheetValues.getString("Title");
j++;
}
}
SpreadsheetValues.close();
stmt2.close();
conn.close();
SpreadsheetValues=null;
stmt2=null;
conn=null;
}
%>
<%=ConnectSqlDB()%>
<%=ConnectExcelDB()%>
<%=getRowcount()%>
<%=getExcelValues()%>
When you are using a method in a JSP Expression, then your method should return a value. I see all of your methods have a return type of void i.e. returning nothing. Change your methods to return appropriate value.
NOTE
I understand that you are currently learning JSP etc but keep in mind that writing contorl/application logic in a view technology like JSP is a bad practice. Try reading the MVC pattern.
Do not use <%= %> (Expression) to invoke void methods and you should have to avoid Java code in JSP (read SO thread).
<%
ConnectSqlDB();
ConnectExcelDB();
getRowcount();
getExcelValues();
%>
<p>Total Records : <%=RowCount%>
<p>Array element at 0 index <%=name[0]%>
<%
for(String v:name)
{
out.println("<br/>" + v);
}
%>
Related
While connecting one applet to an Access DB using the jdbc:ucanaccess method, I get the following error:
Firstdb.java:44: error: unreported exception SQLException;
must be caught or declared to be thrown
stmt.executeUpdate(sql);
^
The code that I used for the applet is as follows (add() and setBounds() are removed from init()):
public class Firstdb extends Applet implements ActionListener {
TextField t1, t2;
Label l1;
Button b1, b2;
Connection con;
Statement stmt;
public void init() {
try {
con = DriverManager.getConnection("jdbc:ucanaccess://H:/test/db.mdb");
stmt = con.createStatement();
} catch (Exception e) {
}
}
public void actionPerformed(ActionEvent ae) {
String sql;
if (ae.getSource() == b1) {
sql = "insert into user (Uname) values(" + t1.getText() + ")";
stmt.executeUpdate(sql);
} else if (ae.getSource() == b2) {
//do something
}
}
}
Note: java version "1.8.0_141"
Why am I getting this error?
Your code has two fatal flaws:
value is not a valid SQL keyword. It should be values. [Fixed in subsequent edit to question.]
Your dynamic SQL is generating command text with invalid syntax (unquoted string literal).
Also, user is a reserved word (function name), so if you need to use it as a table name you really should enclose it in square brackets.
The proper solution to issue #2 above is to use a parameterized query, e.g.,
sql = "insert into [user] ([Uname]) values (?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, t1.getText());
ps.executeUpdate();
It is a compile error which means that you either need to surround your stmt.executeUpdate(sql); with try-catch statement, or your method should throw an SQLException:
public void actionPerformed(ActionEvent ae) {
try {
String sql;
if (ae.getSource() == b1) {
sql="insert into user (Uname) values("+t1.getText()+")";
stmt.executeUpdate(sql);
} else if (ae.getSource() == b2) {
//do something
}
catch (SQLException e) {
// do something
}
}
or
public void actionPerformed(ActionEvent ae) throws SQLException {
String sql;
if (ae.getSource() == b1) {
sql="insert into user (Uname) values("+t1.getText()+")";
stmt.executeUpdate(sql);
} else if (ae.getSource() == b2) {
//do something
}
}
EDIT: By the way, I don't see if you are loading or registering Oracle JDBC driver class for UCanAccess before opening the database connection:
// Step 1: Loading or registering Oracle JDBC driver class
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
} catch(ClassNotFoundException cnfex) {
System.out.println("Problem in loading or "
+ "registering MS Access JDBC driver");
cnfex.printStackTrace();
}
So do you have it or no? If no, you should add it before getting your connection:
con = DriverManager.getConnection("jdbc:ucanaccess://H:/test/db.mdb");
The message
Firstdb.java:44: error: unreported exception SQLException;
must be caught or declared to be thrown
stmt.executeUpdate(sql);
^
looks like a compile error so the question is, how do you compile/deploy the applet-classes and where exactly do you see that error message. IDEs like Eclipse are creating class-files even in case of compile errors containing and outputting the error message that you can also see in the IDE. Maybe you fail to update the applet classes and end up testing with the same old classes instead of the changed ones leading to the same message over and over again.
If you deploy the applet as part of a web app, the HTTP server might cache the class-file if the web app has been deployed as WAR-file. Also, browsers tend to cache class-files quite aggressively so you should make sure that the browser's cache is empty each time you start a new test.
I'm trying to call a method that connects that is on a Bean on a jsp file. The method will make a request to a RMI Server and return a string. At this point the method is just return a pre-defined string for test.
This is the bean method:
public String getListProjects() throws RemoteException {
this.dataToSend = new Object[2];
this.dataToSend[1] = 0;
this.postCard = new ClientRequest("2", this.dataToSend, "tempo");
try{
this.postCard = this.connectToRMI.getActualProjects(this.postCard);
}catch(Exception e){
e.printStackTrace();
}
return "Hello";
}
And this is the jsp code:
<h1>Projectos Actuais</h1>
<h2><%
fundstarter.model.ConnectToRMIBean aux = new fundstarter.model.ConnectToRMIBean();
try{
aux.getListProjects();
}catch(Exception e){
e.printStackTrace();
}
%>
</h2>
I'm guiding my self from another code, and the method is called like this. But in my case it's not working, and I can't figure out what is wrong.
Since you've tagged this struts2, assuming the getListProjects() is on the Action, in JSP use:
<s:property value="listProjects" />
If instead it is on a bean, declare the bean in the Action, and expose it through a getter:
private MyBean bean;
public MyBean getBean(){
return bean;
}
and in JSP use the dot notation:
<s:property value="bean.listProjects" />
P.S: always avoid Scriptlets (<% %>), they're evil.
Quoting and fixing your latest change on edit with some comments:
<h1>Projectos Actuais</h1>
<h2><%
try{
fundstarter.model.ConnectToRMIBean aux = new fundstarter.model.ConnectToRMIBean();
//Send result into generated HTML page with out.print!
out.print(aux.getListProjects());
}catch(Exception e){
e.printStackTrace();
}
%>
</h2>
As per the flow of Struts there should be field in beanclass with same name of getter & setter. For an example if your method name is getListPorjects then in your bean class there should be a private string variable name listprojects.
Also your method will update with following to way to return listprojects.
example:
public String getListProjects() throws RemoteException {
this.dataToSend = new Object[2];
this.dataToSend[1] = 0;
this.postCard = new ClientRequest("2", this.dataToSend, "tempo");
try{
this.postCard = this.connectToRMI.getActualProjects(this.postCard);
listprojects = "hello"
}catch(Exception e){
e.printStackTrace();
}
return listprojects;
}
Calling bean variable should be with ID over the JSP page.
<jsp:useBean id="aux" class="com.path.to.ConnectToRMIBean" scope="request" />
----
yours stuff
-----
<h1>${aux.listProjects}
hope this will help you. good luck
You are just missing the way <% %> and <%= %> are used in JSP. to print in <% %> tags use
<% out.println("Your results"); %>
and for <%= %>
<%=
String.valueOf(1+2);
%>
I have a basic code snippet below but it is not working.What may be the problem with it.
public List<String> getStores() throws SQLException{
List<String> store_id=new ArrayList<>();
String query="select distinct(store_id) from stores";
Connection con=ConnectDatabase.getDb2ConObj();
Statement stmt=con.createStatement();
java.sql.ResultSet rsResultSet=stmt.executeQuery(query);
while(rsResultSet.next()){
store_id.add(rsResultSet.getString(1));
}
con.close();
return store_id;
}
It is throwing the below exception
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: No operations allowed after connection closed.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:888)
at com.mysql.jdbc.Connection.checkClosed(Connection.java:1931)
at com.mysql.jdbc.Connection.createStatement(Connection.java:3087)
at com.mysql.jdbc.Connection.createStatement(Connection.java:3069)
at com.dao.StoreDao.getStores(StoreDao.java:52)
at org.apache.jsp.adminViewAllStore_jsp._jspService(adminViewAllStore_jsp.java:119)
The code for ConnectDatabse is
public class ConnectDatabase {
static Connection con=null;
static String connectionString="jdbc:mysql://localhost:3306/ayurveda";
static String username="root";
static String password="";
public static Connection getDb2ConObj(){
if(con==null){
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection(connectionString,username,password);
}
catch(ClassNotFoundException | SQLException e)
{
System.out.println("Connect initialized with error"+e.getMessage());
e.printStackTrace();
}
}
return con;
}
I cannot understand the reason for the same.What may be the problem.Since I am closing the connection after I am done with it.
It worked after I enclosed it in a try catch finally block.Changed the code as given below
public List<String> getStores() throws SQLException{
List<String> store_id=new ArrayList<>();
Connection con=ConnectDatabase.getDb2ConObj();
try{
String query="select distinct(store_id) from stores";
Statement stmt=con.createStatement();
java.sql.ResultSet rsResultSet=stmt.executeQuery(query);
while(rsResultSet.next()){
store_id.add(rsResultSet.getString(1));
}
}catch(Exception e){
}finally{
con.close();
}
return store_id;
}
Thanks.
You can use this type of code...for solving your problem
public void actionPerformed(ActionEvent ae)
{
String u=t1.getText();
String p=t2.getText();
if(ae.getSource()==b1)
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:newdsn");
String stp="SELECT * FROM reg";
Statement sa=con.createStatement();
rs=sa.executeQuery(stp);
while(rs.next())
{
String du=rs.getString(2);
String dp=rs.getString(3);
if(du.equals(u)&&dp.equals(p))
{
a=0;
break;
}else{ a=1;}
}
if(a==0){
JOptionPane.showMessageDialog(this,"LOGIN PAGE","Login is successful",1);
}
if(a==1){
JOptionPane.showMessageDialog(this,"LOGIN PAGE","Login is not successful",1);
}}
catch(Exception e){}
}}
if even the it is throwing exception then you check the system 32 bit or 64 bit..you should try if 64bit then please make your dsn in 32 bit and anduse ms access 2002-2003 version
then you get tour solution .....thank u
Use Java 7 -The try-with-resources Statement
According to the oracle documentation, you can combine a try-with-resources block with a regular try block
The typical Java application manipulates several types of resources such as files, streams, sockets, and database connections. Such resources must be handled with great care, because they acquire system resources for their operations. Thus, you need to ensure that they get freed even in case of errors.
Indeed, incorrect resource management is a common source of failures in production applications, with the usual pitfalls being database connections and file descriptors remaining opened after an exception has occurred somewhere else in the code. This leads to application servers being frequently restarted when resource exhaustion occurs, because operating systems and server applications generally have an upper-bound limit for resources.
sample code:
try(Connection con = getConnection()) {
...
}
Read more Java 7 Automatic Resource Management JDBC
Close Statement and ResultSet as well.
Don't load driver class every time when connection is needed. Just load it once in static initialization block.
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I suggest you to use JNDI and DataSource to keep username and password outside the Java code to make it more manageable. Keep the database configuration in a separate xml/properties file instead of hard-coding in Java file.
See Java Tutorial on Connecting with DataSource Objects
I have already posted a nice ConnectionUtil class to manage all the connections in a single class for whole application.
I was trying to write a separate database connection method in .java file which can be called upon by any servlet or jsp file needing the database connection. My code is
import java.sql.*;
import java.lang.*;
public class ConnectionClass {
private String username="root";
private String password="passwd";
/* Adjust the above two as per the username
* password combination of your MySql databse */
public Connection connect()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/schooldatabase";
Connection con = DriverManager.getConnection(url,username,password);
return con;
}
catch(Exception e)
{
response.sendRedirect("studentserr.html");
out.println(e);
}
}
}
Now, the problem is that i'll be returning a Connection type so that all the servlets (which require database connection) may use it to execute various statements. However, in my code what should i return in the catch block ( which means that the connection to the database could not be established) ? Also, in case of a connection failure, I'm redirecting the user to the following page:
"studentserr.html"
This works fine if i use it in a servlet but not in .java class. What should i do for this ??
You should only be catching exceptions at exactly that moment where you can sensibly deal with them. You can't sensibly deal with them in the getConnection() method, so you should instead throw it so that the caller itself needs to deal with it.
Displaying an error page in case of a specific exception is however the responsibility of the servlet container itself. You normally configure the error page in web.xml as follows:
<error-page>
<exception-type>java.sql.SQLException</exception-type>
<location>/WEB-INF/errorpages/database.jsp</location>
</error-page>
You only need to change your code accordingly that you never catch the exception, or at least rethrow as ServletException where necessary.
Here's a minor rewrite:
public class Database {
private String url = "jdbc:mysql://localhost/schooldatabase";
private String username = "root";
private String password = "passwd";
static {
try {
Class.forName("com.mysql.jdbc.Driver"); // You don't need to load it on every single opened connection.
} catch (ClassNotFoundException) {
throw new ExceptionInInitializerError("MySQL JDBC driver missing in classpath", e);
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
}
And here's how you should use it in your DAO classes:
public List<Student> list() throws SQLException {
List<Student> students = new ArrayList<Student>();
Connection connection = null;
// ...
try {
connection = Database.getConnection();
// ...
} finally { // Note: no catch block!
// ...
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
return students;
}
And here is how you should use the DAO class in your servlet's doGet() or doPost().
try {
List<Student> students = studentDAO.list();
request.setAttribute("students", students);
request.getRequestDispatcher("/WEB-INF/students.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException(e);
}
It has to be rethrown as ServletException simply because you can't add SQLException to the throws clause of any HttpServlet method. The servletcontainer will unwrap the SQLException while locating the error page.
Return a null value in case an exception is thrown. In case of getting a null value from your method, handle the exception and don't perform any database operation.
Also, remember to separate the database logic (connection, statement execution) from the business logic and the presentation. In your actual method, this code
response.sendRedirect("studentserr.html");
should never be in the database logic, because is presentation logic.
More info:
Java 101: Layered Architecture
How to avoid Java Code in JSP-Files?
Try moving class "ConnectionClass" into some package. and then call using this package in your java class where you require this (seems to be classpath issue in java file) or in jsp or servlet page.
Example
You need this in Demo.java as
pkg1.ConnectionClass obj = new pkg1.ConnectionClass ();
It is recommended to have database connection class as singleton. So that through out the application only a single instance of connection will be created and shared.
I have a question on code reuse in JSP. I have a JSP page example.jsp that issues a call to a database and gets the results. I have a java class HelperClass.java that accepts a record and prints out the different fields
response.getWriter().println
Now my JSP page has HTML as well and the problem is the content printed out by the HelperClass appears before the content in the JSP page. E.g.
<body>
This is the first line <br/>
HelperClass.printdata("second line");
</body>
output is
secondline This is the first line
Is this a known issue. What is the best way to design an HelperClass for a JSP page that prints content out to the page. Any pointers would be greatly appreciated.
Just do not use a "HelperClass to print data". This makes no sense. There you have EL for.
${bean.property}
That's all. Use a servlet to control, preprocess and postprocess requests. Use taglibs (e.g. JSTL) and EL to access and display backend data.
Here's a basic kickoff example of a Servlet which preprocesses the request before display in JSP:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Person> persons = personDAO.list(); // Get list of persons from DB.
request.setAttribute("persons", persons); // So it's available as `${persons}` in EL.
request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response); // Forward to JSP for display.
}
Here, the Person is just a Javabean class which represents a real world entity.
public class Person {
private Long id;
private String name;
private String email;
private Integer age;
// Add/generate getters and setters here.
}
The PersonDAO#list() method just returns a List of Person objects from the DB:
public List<Person> list() throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<Person> persons = new ArrayList<Person>();
try {
connection = database.getConnection();
statement = connection.createStatement("SELECT id, name, email, age FROM person");
resultSet = statement.executeQuery();
while (resultSet.next()) {
Person person = new Person();
person.setId(resultSet.getLong("id"));
person.setName(resultSet.getString("name"));
person.setEmail(resultSet.getString("email"));
person.setAge(resultSet.getInteger("age"));
persons.add(person);
}
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return persons;
}
Map the servlet in web.xml on an url-pattern of /persons. The JSP is hidden in /WEB-INF so that nobody can access it directly without requesting the servlet first (else one would get an empty table).
Now, here's how persons.jsp look like, it uses JSTL (just drop jstl-1.2.jar in /WEB-INF/lib) c:forEach to iterate over a List and it uses EL to access the backend data and bean properties. The servlet has put the List<Person> as request attribute with name persons so that it's available by ${persons} in EL. Each iteration in c:forEach gives a Person instance back, so that you can display their proeprties with EL.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${persons}" var="person">
<tr>
<td>${person.name}</td>
<td>${person.email}</td>
<td>${person.age}</td>
</tr>
</c:forEach>
</table>
Call it by http://example.com/contextname/persons. That's all. No need for a "HelperClass to print data" ;) To learn more about JSTL, check Java EE tutorial part II chapter 7 and to learn more about EL, check Java EE tutorial part II chapter 5. To learn more about stuff behind PersonDAO, check this article.