JSP JavaBeans and Database
i am wondering whats the "correct" or best way to connect to a DB using JavaBeans and using this in JSP pages?
i read abt creating a SQL "Helper" class that has some functions like connect etc... but i am thinking its a bit confusing...
if i have a function
public static Statement Connect() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:auction","","");
stmt = con.createStatement();
} catch (SQLException e) {
System.out.println("ERROR: SQLException occured!\n" + e.getMessage());
} catch (Exception e) {
System.out.println("ERROR: An Exception occured!\n" + e.getMessage());
return stmt;
}then i use it
Statement stmt = SqlHelper.connect();when i want to close the connection how do i do it? is it a must to close connections anyway?
or shld i do it the easy way, having the code
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:auction","","");
stmt = con.createStatement();on all JSP pages?
Thank you
BalusC wrote:Do it in the data layer. Write DAO classes and SQL helper classes. Then let the business layer, the Servlet, interact with the data layer and let the presentation layer, the JSP, display the results.
And don't return a Statement, but a Connection. And yes, closing a Connection is a must, otherwise you're leaking resources which will cause your web application to crash due to a memory shortage.ya thats what i am trying to do... but how do i? like this? except i return a connection instead? and also, i shld return it by reference? mmm... in java isit like return &con?
package AuctionSystem;
import java.sql.*;
public class SqlHelper {
private static Connection con;
private static Statement stmt;
public SqlHelper() {
Connection con = null;
Statement stmt = null;
public static void Connect() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:auction","","");
stmt = con.createStatement();
} catch (SQLException e) {
System.out.println("ERROR: SQLException occured!\n" + e.getMessage());
} catch (Exception e) {
System.out.println("ERROR: An Exception occured!\n" + e.getMessage());
public static Connection getCon() {
return con;
public static Statement getStmt() {
return stmt;
public static void Close() {
con.close();
stmt.close();
public static String FormatString(String string) {
return "'" + string + "'";
}Edited by: iceangel89 on May 27, 2008 3:50 AM
Similar Messages
-
Using HTML, JSP, JavaBeans and Access database
I'm trying to create a login page that will allow users to query, insert, modify, and delete information. I have an HTML page that the user chooses which option they want to do. I have 4 JSP's set up for each option. My biggest issue is getting them to talk to the database using a single JavaBean. I can create several beans to pull the information, post, delete, or modify. I'm having trouble pulling information through the JSP's from the HTML page. Please help...
Hey,
You get html to communicate with your server using forms. Use the request to retrieve the submitted form data. All you would need to do is tell your bean what it is doing, how and with what.
Good luck -
Hi,
I have the following code for a javabean that queries the databases based on a parameter passed in a form.
import java.sql.*;
import java.io.*;
public class QueryBean {
// private String dbURL = "jdbc:odbc:Contacts4";
private String dbURL = "jdbc:odbc:africa";
private String dbDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
private Connection dbCon;
String Name = null;
public QueryBean() {
super();
public String getName() {
return this.Name;
public void setName(String tname) {
this.Name = tname;
public String doQuery() throws ClassNotFoundException, SQLException {
// Class.forName(dbDriver);
Class.forName(dbDriver);
dbCon = DriverManager.getConnection(dbURL,"sa","");
Statement s = dbCon.createStatement();
String sql = "SELECT * FROM Members WHERE Last_Name like '" + this.Name
+ "%' or Notes like '" +"%"+ this.Name
+ "%' or Company_Name like '" +"%"+ this.Name + "%'";
//System.out.println("sql : "+sql);
ResultSet rs = s.executeQuery(sql);
String rt = "";
while (rs.next()) {
rt = rt + "<tr> <td>" + rs.getString("Last_Name") + "</td>";
rt = rt + "<td>" + rs.getString("First_Name") + "</td>";
rt = rt + "<td>" + rs.getString("Address") + "</td>";
rt = rt + "<td>" + rs.getString("Phone") + "</td>";
rt = rt + "<td>" + rs.getString("Type");
rt = rt + "<td>" + " -> "+rs.getString("Notes") + "</td> </tr>";
dbCon.close();
return rt;
When I compile the code it is okay.
I have a form in which somebody enters the parameter:
<html>
<body>
This is the Query page.
<p>
<form method=post action="query2.jsp">
Name: <input type=text name=tname>
<br>
<input type=submit>
</form>
</body>
</html>
The action of the form is this:
<html>
<body>
<%@ page language="java" %>
<jsp:useBean id="queryBean" scope="request" class="QueryBean" />
<%
queryBean.setName(request.getParameter("tname"));
%>
The result of the query is:
<table>
<tr>
<th> Noms </th> <th> Pr�noms </th> <th> Adresses </th><th> T�l�phones
</th><th> Notes </th>
</tr>
<%= queryBean.doQuery() %>
</table>
<p>
</body>
</html>
When the form is submitted I get the following error:
Generated servlet error:
[javac] Compiling 1 source file
C:\Program Files\Apache Group\Tomcat 4.1\work\Standalone\localhost\japps\query2_jsp.java:44: cannot resolve symbol
symbol : class QueryBean
location: class org.apache.jsp.query2_jsp
QueryBean queryBean = null;
^
An error occurred at line: 3 in the jsp file: /query2.jsp
Generated servlet error:
C:\Program Files\Apache Group\Tomcat 4.1\work\Standalone\localhost\japps\query2_jsp.java:46: cannot resolve symbol
symbol : class QueryBean
location: class org.apache.jsp.query2_jsp
queryBean = (QueryBean) pageContext.getAttribute("queryBean", PageContext.REQUEST_SCOPE);
^
An error occurred at line: 3 in the jsp file: /query2.jsp
Generated servlet error:
C:\Program Files\Apache Group\Tomcat 4.1\work\Standalone\localhost\japps\query2_jsp.java:49: cannot resolve symbol
symbol : class QueryBean
location: class org.apache.jsp.query2_jsp
queryBean = (QueryBean) java.beans.Beans.instantiate(this.getClass().getClassLoader(), "QueryBean");
^
3 errors
If you've got any ideas on this.Like help me out.
CheersI actually found what the problem was, I simply had to put the class file in a package and everything worked out fine.Thanks for the input though.
Cheers -
JSP, JavaBeans and iPlanet 4.1- Unable to load JavaBean
I get the following error when trying to access a JavaBean from a JSP page. I have tried just about everything including using the <@page import /> in the JSP page.
I can get it to run perfectly in Tomcat 3.2 but it must run in iPlanet 4.1. I think the solution should be fairly simple I just can't find it.
Any help would be greatly appreciated.
Thanks.
The exception is as follows (thrown on running the generatePage.jsp linked from index.jsp).
[29/Nov/2001:16:50:23] info ( 1364): Internal Info: loading servlet /TechCom/generatePage.jsp
[29/Nov/2001:16:50:23] info ( 1364): JSP: JSP1x compiler threw exception
org.apache.jasper.JasperException: Unable to load class JspPageLoader
at org.apache.jasper.compiler.BeanRepository.getBeanType(BeanRepository.java:183)
at org.apache.jasper.compiler.GetPropertyGenerator.generate(GetPropertyGenerator.java:97)
at org.apache.jasper.compiler.JspParseEventListener$GeneratorWrapper.generate(JspParseEventListener.java:728)
at org.apache.jasper.compiler.JspParseEventListener.generateAll(JspParseEventListener.java:190)
at org.apache.jasper.compiler.JspParseEventListener.endPageProcessing(JspParseEventListener.java:159)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:141)
at com.netscape.server.http.servlet.NSServletEntity.load(NSServletEntity.java:214)
at com.netscape.server.http.servlet.NSServletEntity.(NSServletEntity.java:104)
at com.netscape.server.http.servlet.NSServletRunner.loadServlet(NSServletRunner.java:607)
at com.netscape.server.http.servlet.NSServletRunner.Service(NSServletRunner.java:357)
[29/Nov/2001:16:50:23] warning ( 1364): Unable to locate class: D:\Netscape\Server4\docs\TechCom (java.lang.ClassNotFoundException: D:\Netscape\Server4\docs\TechCom)
[29/Nov/2001:16:50:23] warning ( 1364): Internal error: Failed to load servlet (servlet=/TechCom/generatePage.jsp)To solve this problem you have to:
include <@page import /> tags importing the JavaBean to be used.
In the classpath of iPlanet include the directory in which your JavaBeans are placed.
Also in the classpath of iPlanet include the root directory of you web site containing the JSP's. this should then solve the problem. -
Error - '.' expected - while database insert thru JSP & javabeans & JDBC
I get the following error when i try to compile the below mentioned code in JDEVELOPER 10.1.2
Error : '.' expected
===================
have error in my code. I am trying to do a simple database insert program using javabeans and jsp. I get a value to be inserted in database through the jsp page in a text box and would like to be inserted into database using beans The connection to database and mysql query are in java file.
Here is the code.
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page language="Java" import="java.sql.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<html>
<head>
</head>
<body>
<form name="form1" action="beancode" method="POST">
Emp ID: <input type="text" name ="emplid"> <br><br><br>
<input type = "submit" value="Submit">
<jsp:useBean id="sampl" class="beancode" scope="page">
<jsp:setProperty name="sampl" property="*"/>
</jsp:useBean>
</form>
</body>
</html>
I know i might have made a mistake here in using the bean. Here is the java code which does the insert part.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
* @author Trainees
public class beancode
private String employid;
private Connection con = null;
private ResultSet rs = null;
private PreparedStatement st = null;
/** Creates a new instance of beancode */
public beancode()
try
Class.forName("org.gjt.mm.mysql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample?user=user&password=password");
catch(Exception e)
System.out.println(e.getMessage());
public void setemployid(String empid)
employid = empid;
public String getemployid()
return (employid);
public void insert()
try
String s1="insert into samp values('"+employid+"')";
st = con.prepareStatement(s1);
st.executeUpdate();
st.clearParameters();
st.close();
catch(Exception m)
}It's pretty hard to spot any errors the way it's currently formatted. But, you're trying to call the beancode when submitting your form, but the beancode isn't a servlet. Try to find a working example, run it, and then change it to implement your requirements.
The following example shows you have to use the jstl sql tags: http://www.oracle.com/technology/sample_code/tech/java/codesnippet/jsps/jstlsql.html. If you want to do an insert when a user submits a form, you need 2 pages. The first will contain your form, the second will insert the record.
(once you've got that running, look for some examples using an mvc framework, and how to use bind variables with jdbc) -
Please help with jsp and database!!
Hello,
i first created a jsp page and printed out the parameters of a user's username when they logged in. example, "Welcome user" and it worked fine...
i inserted a database into my site that validates the username and password, and ever since i did that in dreamweaver, when a user logs in sucessfully, it returns the jsp page like its supposed to, only that it says "Welcome null" instead of "Welcome John." pretty strange, huh!? can anyone please help? thanks!
here is the important part of the code to Login.jsp, and LoginSuccess.jsp: <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" %>
<%@ include file="Connections/Login.jsp" %>
<%
// *** Validate request to log in to this site.
String MM_LoginAction = request.getRequestURI();
if (request.getQueryString() != null && request.getQueryString().length() > 0) MM_LoginAction += "?" + request.getQueryString();
String MM_valUsername=request.getParameter("Username");
if (MM_valUsername != null) {
String MM_fldUserAuthorization="";
String MM_redirectLoginSuccess="LoginSuccess.jsp";
String MM_redirectLoginFailed="LoginFailure.jsp";
String MM_redirectLogin=MM_redirectLoginFailed;
Driver MM_driverUser = (Driver)Class.forName(MM_Login_DRIVER).newInstance();
Connection MM_connUser = DriverManager.getConnection(MM_Login_STRING,MM_Login_USERNAME,MM_Login_PASSWORD);
String MM_pSQL = "SELECT UserName, Password";
if (!MM_fldUserAuthorization.equals("")) MM_pSQL += "," + MM_fldUserAuthorization;
MM_pSQL += " FROM MemberInformation WHERE UserName=\'" + MM_valUsername.replace('\'', ' ') + "\' AND Password=\'" + request.getParameter("Password").toString().replace('\'', ' ') + "\'";
PreparedStatement MM_statementUser = MM_connUser.prepareStatement(MM_pSQL);
ResultSet MM_rsUser = MM_statementUser.executeQuery();
boolean MM_rsUser_isNotEmpty = MM_rsUser.next();
if (MM_rsUser_isNotEmpty) {
// username and password match - this is a valid user
session.putValue("MM_Username", MM_valUsername);
if (!MM_fldUserAuthorization.equals("")) {
session.putValue("MM_UserAuthorization", MM_rsUser.getString(MM_fldUserAuthorization).trim());
} else {
session.putValue("MM_UserAuthorization", "");
if ((request.getParameter("accessdenied") != null) && false) {
MM_redirectLoginSuccess = request.getParameter("accessdenied");
MM_redirectLogin=MM_redirectLoginSuccess;
MM_rsUser.close();
MM_connUser.close();
response.sendRedirect(response.encodeRedirectURL(MM_redirectLogin));
return;
%>
<form action="<%=MM_LoginAction%>" method="get" name="Login" id="Login">
<table width="55%" border="0">
<tr>
<td width="41%">Username </td>
<td width="59%"><input name="Username" type="text" id="Username" value="" size="25" maxlength="10"></td>
</tr>
<tr>
<td>Password </td>
<td><input name="Password" type="password" id="Password" value="" size="25" maxlength="10"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>And LoginSuccess.jsp where i want it to print out the "Welcome username
<%String Name=request.getParameter("Username");
out.println ("Welcome ");
out.println (Name); %><%@ page contentType="text/html; charset=iso-8859-1"
language="java" import="java.sql.*" %>
<%@ include file="Connections/Login.jsp" %>
<%
// *** Validate request to log in to this site.
String MM_LoginAction = request.getRequestURI();
if (request.getQueryString() != null &&
request.getQueryString().length() > 0) MM_LoginAction
+= "?" + request.getQueryString();
String
MM_valUsername=request.getParameter("Username");
if (MM_valUsername != null) {
String MM_fldUserAuthorization="";
String MM_redirectLoginSuccess="LoginSuccess.jsp";
String MM_redirectLoginFailed="LoginFailure.jsp";
String MM_redirectLogin=MM_redirectLoginFailed;
Driver MM_driverUser =
=
(Driver)Class.forName(MM_Login_DRIVER).newInstance();
Connection MM_connUser =
=
DriverManager.getConnection(MM_Login_STRING,MM_Login_US
RNAME,MM_Login_PASSWORD);
String MM_pSQL = "SELECT UserName, Password";
if (!MM_fldUserAuthorization.equals("")) MM_pSQL +=
= "," + MM_fldUserAuthorization;
MM_pSQL += " FROM MemberInformation WHERE
E UserName=\'" + MM_valUsername.replace('\'', ' ') +
"\' AND Password=\'" +
request.getParameter("Password").toString().replace('\'
, ' ') + "\'";
PreparedStatement MM_statementUser =
= MM_connUser.prepareStatement(MM_pSQL);
ResultSet MM_rsUser =
= MM_statementUser.executeQuery();
boolean MM_rsUser_isNotEmpty = MM_rsUser.next();
if (MM_rsUser_isNotEmpty) {
// username and password match - this is a valid
lid user
session.putValue("MM_Username", MM_valUsername);
if (!MM_fldUserAuthorization.equals("")) {
session.putValue("MM_UserAuthorization",
ion",
MM_rsUser.getString(MM_fldUserAuthorization).trim());
} else {
session.putValue("MM_UserAuthorization", "");
if ((request.getParameter("accessdenied") != null)
ll) && false) {
MM_redirectLoginSuccess =
ess = request.getParameter("accessdenied");
MM_redirectLogin=MM_redirectLoginSuccess;
MM_rsUser.close();
MM_connUser.close();
response.sendRedirect(response.encodeRedirectURL(MM_re
irectLogin));
return;
%>
<form action="<%=MM_LoginAction%>" method="get"
"get" name="Login" id="Login">
<table width="55%" border="0">
<tr>
<td width="41%">Username </td>
<td width="59%"><input name="Username"
="Username" type="text" id="Username" value=""
size="25" maxlength="10"></td>
</tr>
<tr>
<td>Password </td>
<td><input name="Password" type="password"
="password" id="Password" value="" size="25"
maxlength="10"></td>
</tr>
<tr>
<td>�</td>
<td><input type="submit" name="Submit"
me="Submit" value="Submit"></td>
</tr>
</table>
</form>
And LoginSuccess.jsp where i want it to print out the
"Welcome username
<%String Name=request.getParameter("Username");
out.println ("Welcome ");
out.println (Name); %>When the page is rediredted u r not passing the user name in the query string,so it is not availble in the query string for LoginSuccess page
Since u have added user in session user this
<%String Name=(String)session.getValue("MM_Username") ;%>
<% out.println ("Welcome ");
<% out.println (Name); %> -
What is the diffrence between a javabean and EJB
hi!
what is the diffrence between a javabean and entreprise jvaabeans! i mean which are the uitilization featires of eaxh one !i am seeking for a solution for my problem , in fact i ma trying to implement and develop an application with java that allows a certain range of IP adresses to be connected to a database server in order to extract the suitable data from the server .
let me explain mor ethe suitation , in fact what i am loking for is to use javabeans to grant my application much more consistence and pertinence : si i am asking if it could be possible to use javabeans in my case especially if i am not trying to developp a web application but a cleint /server one allowing some services.
The application is in fact dealing with a stock exchange market and what i am trying to do is to grant particilar registrated customers to have the informations that they need ( portofolio, currency's status, market indicators, .) also drawing some charts decribing rates, variations, and others specefic financial caracterestics .So , if we consider that this application is not a web application ( no HTTP request and no servers like apache or others ) how it is possible to use javabeans and not EJB to build the application? i mean what could be suitable and preferable to rely on and dvelop to ensure a good java application !!
if you need more details to help you find the answer for me don't hesitate to answer me back !!
Someone here gave me that answer
use RMI to code the services and (Updateable) Value Objects to pass the information between tiers.
RMI is an all-java distributed component framework (ie. EJB, CORBA, DCE/RPC, DCOM, etc.), that is very suitable for developing non-containerized multi-tier applications. Refer to the RMI trail in the Java Tutorial as a starting point for coding RMI solutions (http://java.sun.com/docs/books/tutorial/index.html). Under this scenario you would code the database access service as an RMI service (server-side). Client/server communication should be facilitated through the use of JavaBeans/classes that wrap the information being passed (customer information, portfolio details, market information, etc.) - these are refered to as 'Updateable Value Objects' (a design pattern). Graphing and charting would be handled in your client from the information received from the (RMI) server. GUI JavaBeans can be used to provide this functionality as well as other client-side services. There are numerous "shrink-wrapped" components for GUIs available on the market just peruse any Java magazine to find them.
but how comes? how can i do it !! and where can i find more information please about 'Updateable Value Object "
thanks -
How can I stop the execution on a JSP page and start it again
Hi
I am making a program that simulates how to manage transactions when accessing a database by using locks. I have run into a problem and I hope someone has the time to help me.
When a user does an update the transaction commits and releases its locks when the program executes
<%stmt.executeUpdate("commit!"); %>
I need to put a break in to stop the program executing this statement, to illustrate the lock is set correctly.
I have tried to put in an alert box but this does not prevent the rest of the java code being executed.
I have tried to use prompt boxes, JavaScript functions, but these functions cannot have any java code in them.
I have tried using the java.swing JOptionPane boxes but this didn?t work either
I have tried to get input from the user but I don?t know how to retrieve this data on the same page. (As far as I know you have to use submit and even refresh the page or retrieve it on the next page).
Does anyone know how I can stop the execution on a JSP page and start it again (on same page)
MetteI already have another client (Tomcat jsp application) running and it throws a SQLException correctly when I don�t put in a commit=true statement and don't close the database connection.
But the problem is how to get the code above to stop to illustrate I have set this lock.
I have tried to use the JOptionPane but because my program is running in a web browser I cannot use the JOptionPane dialog box.
I have tired using an alert box but it executes the commit statement before the alert box is dispayed. So this does not work
While (i < 2)
if( i==1)
%>alert(�The transactions commits when you press Ok�); <% //what it to stop execution here
else
stmt.executeUpdate(�commit�);
I am not using threads so I cannot use the sleep function.
I am using mysql and have already configured it to detect deadlocks and how long to wait for locks.
Thanks for your help
Mette -
Upload file in JSP with Oracle Database 10gR2
How to upload file with oracle database 10gR2??
i can't find how to upload..
i've tried to create a procedure in oracle and execute in netbeans but the file save in directory and then from directory save to database.
it means the file save in 2 location, in directory and database..
does anybody know how to save file direct from the JSP file into database without save in directory?
this is the procedure..
create or replace PROCEDURE load_file (
p_id number,
p_photo_name in varchar2) IS
src_file BFILE;
dst_file BLOB;
lgh_file BINARY_INTEGER;
BEGIN
src_file := bfilename('DIR_TEMP', p_photo_name);
-- insert a NULL record to lock
INSERT INTO temp_photo
*(id, photo_name, photo)*
VALUES
*(p_id , p_photo_name ,EMPTY_BLOB())*
RETURNING photo INTO dst_file;
-- lock record
SELECT photo
INTO dst_file
FROM temp_photo
WHERE id = p_id
AND photo_name = p_photo_name
FOR UPDATE;
-- open the file
dbms_lob.fileopen(src_file, dbms_lob.file_readonly);
-- determine length
lgh_file := dbms_lob.getlength(src_file);
-- read the file
dbms_lob.loadfromfile(dst_file, src_file, lgh_file);
-- update the blob field
UPDATE temp_photo
SET photo = dst_file
WHERE id = p_id
AND photo_name = p_photo_name;
-- close file
dbms_lob.fileclose(src_file);
END load_file;Well your Oracle procedure is designed to load a file, so that's what it does. If you want it to load from a data stream such as an upload, you need to rewrite it accordingly.
So far this is not a Java question at all. -
What is a javabean and how to compose it?
Q1:although have used many java class in jsp within tomcat, but i don't is it a standard javabean. I mean is any java class can be an javabean, or what is the different between javabean and java class.
for now i found some problem with 'javabean' used in jsp.
Q2:what is ther difference between use jsp:setProperty,jsp:getProperty and direct give value like 'myBean.variable=100'?
thanks!javabeans are standard classes but have :
- default constructor
- getter and setter methods
javabean can be used on custom tags, so no code on your jsp !
why don't directly use attributes ?
look this thread :
http://forum.java.sun.com/thread.jsp?forum=45&thread=314643
this is one, but it's not the only, reason.
Regards. -
Using Java Bean in JSP to show database record
I have links in my Tomcat container that if someone clicks on a specific link it should go to a Record page (Show.jsp) with all the values associated with a record from a database.
For example if someone clicks on a specific link like this:
LinkExample
it would take you to a jsp with database info for someone named Jones and show you his info:
Lastname = Jones
Firstname = Mike
City = San Diego
I would like to do this using a Java helper class and bean so I dont have any database connection or Java code in my JSP.
I created Java class file that has Database connection that works with a Java bean. I just dont know how to get the Show.jsp to work with the Java Bean and Java helper class file.
Here is what I have for Show.jsp and this is the part I have been working on the longest but cant get it to work because it doesnt seem to work with the database:<jsp:useBean id="user" class="num.UserDB"/>
//do I call getUser(lastname) here and if so how?
<jsp:setProperty name="user" property="*"/>
Last Name: <jsp:getProperty name="user" property="lastname"/><BR>
First Name: <jsp:getProperty name="user" property="firstname"/><BR>
City: <jsp:getProperty name="user" property="city"/><BR>My Java Helper class that compiles and connects to database:
package num;
import java.io.*;
import java.sql.*;
import java.util.*;
import num.User;
public class UserDB
public User getUser(String lastname)
User user = new User();
try
Class.forName...//database connection stuff here
ResultSet results = stmt.executeQuery("SELECT * from user where lastname = '" + lastname + "'");
if(results.next() == true)
results.next();
user.setLastname(results.getString("lastname"));
user.setFirstname(results.getString("firstname"));
user.setFirstname(results.getString("city"));
catch(Exception e)
System.out.println("Exception...");
return user;
}My Java Bean that compiles here:
package num;
public class User
private String firstname;
private String lastname;
private String city;
public User()
//no arg constructor
public User(String firstname, String lastname, String city)
this.lastname = lastname;
this.firstname = firstname;
this.city = city;
public String getLastname()
return lastname;
public void setLastname(String lastname)
this.lastname = lastname;
//more bean methods for all fields here
Sorry if I wasnt specific enough. I have a link that passes a value (field that is passed is called lastname) to a JSP where I want to show record info for that value that is passed.
My question is how do I show the database record info on Show.jsp for the lastname field value of Jones where I want to use a Java Bean and Database helper class in Show.jsp
Here is the message I get when I hit the link (LinkExample) and it goes to Show.jsp:
org.apache.jasper.JasperException: Cannot find any information on property 'lastname' in a bean of type 'num.UserDB'
.....My UserDB class:
public class UserDB
public User getUser(String lastname)
User user = new User();
try
Class.forName("org.gjt.mm.mysql.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/dbconnone?user=smitherson&password=abcdefg");
Statement stmt = conn.createStatement();
ResultSet results = stmt.executeQuery("SELECT * from user where lastname = '" + lastname + "'");
if(results.next() == true)
results.next();
user.setLastname(results.getString("lastname"));
user.setFirstname(results.getString("firstname"));
user.city(results.getString("city"));
catch(Exception e)
System.out.println("Exception..." + e);
return user;
}Bean class:
package num;
public class User
private String firstname;
private String lastname;
private String city;
public User()
//no arg constructor
public User(String firstname, String lastname, Sting city)
this.firstname = firstname;
this.lastname = lastname;
this.city = city;
public String getFirstname()
return firstname;
public void setFirstname(String firstname)
this.firstname = firstname;
public String getLastname()
return lastname;
public void setLastname(String lastname)
this.lastname = lastname;
public String getCity()
return city;
public void setCity(String city)
this.city = city;
-
JSP'S and Packages!!!!
I'm developing a Web application using Java and Oracle. The system administrator has set up a development instance on Websphere (I don't have admin rights to this server) called MEDS for my projecct. The directory where my jsp files are is: MEDS/MEDS.war/jsp/...jsp files. My Servlet files are in the following directory: MEDS/MEDS.war/WEB-INF/classes. I want to put my database connection string into 1 servlet file, create a package, and then include my servlets and jsp's into that package.
How can I create a package, let's say MEDSPACKAGE, and include my jsp files and servlets in that package? After I've created that package, what statement do I use in each of my jsp pages to include them in that package that I create?
Thank you in advance!!!!There are also tools that will make this easier for you (such as your IDE or Ant, but each will have a learning curve associated with them. Please, PLEASE take the time to read about the basics in the previous link I posted. You (and your admin) will thank you. :o)
§ -
JSP Servlet and convert the result set of an SQL Query To XML file
Hi all
I have a problem to export my SQL query is resulty into an XML file I had fixed my servlet and JSP so that i can display all the records into my database and that the goal .Now I want to get the result set into JSP so that i can create an XML file from that result set from the jsp code.
thisis my servlet which will call the jsp page and the jsp just behind it.
//this is the servlet
import java.io.*;
import java.lang.reflect.Array;
import java.sql.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.sql.*;
public *class *Campaign *extends *HttpServlet
*private* *final* *static* Logger +log+ = Logger.+getLogger+(Campaign.*class*.getName());
*private* *final* *static* String +DATASOURCE_NAME+ = "jdbc/SampleDB";
*private* DataSource _dataSource;
*public* *void* setDataSource(DataSource dataSource)
_dataSource = dataSource;
*public* DataSource getDataSource()
*return* _dataSource;
*public* *void* init()
*throws* ServletException
*if* (_dataSource == *null*) {
*try* {
Context env = (Context) *new* InitialContext().lookup("java:comp/env");
_dataSource = (DataSource) env.lookup(+DATASOURCE_NAME+);
*if* (_dataSource == *null*)
*throw* *new* ServletException("`" + +DATASOURCE_NAME+ + "' is an unknown DataSource");
} *catch* (NamingException e) {
*throw* *new* ServletException(e);
protected *void *doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
Connection conn = *null*;
*try* {
conn = getDataSource().getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select post_id,comments,postname from app.posts");
// out.println("Le résultat :<br>");
ArrayList <String> Lescomments= *new* ArrayList<String>();
ArrayList <String> Lesidentifiant = *new* ArrayList<String>();
ArrayList <String> Lesnoms = *new* ArrayList <String>();
*while* (rs.next()) {
Lescomments.add(rs.getString("comments"));
request.setAttribute("comments",Lescomments);
Lesidentifiant.add(rs.getString("post_id"));
request.setAttribute("id",Lesidentifiant);
Lesnoms.add(rs.getString("postname"));
request.setAttribute("nom",Lesnoms);
rs.close();
stmt.close();
*catch* (SQLException e) {
*finally* {
*try* {
*if* (conn != *null*)
conn.close();
*catch* (SQLException e) {
// les paramètres sont corrects - on envoie la page réponse
getServletContext().getRequestDispatcher("/Campaign.jsp").forward(request,response);
}///end of servlet
}///this is the jsp page called
<%@ page import="java.util.ArrayList" %>
<%
// on récupère les données
ArrayList nom=(ArrayList)request.getAttribute("nom");
ArrayList id=(ArrayList)request.getAttribute("id");
ArrayList comments=(ArrayList) request.getAttribute("comments");
%>
<html>
<head>
<title></title>
</head>
<body>
Liste des campagnes here i will create the xml file the problem is to display all rows
<hr>
<table>
<tr>
</tr>
<tr>
<td>Comment</td>
<td>
<%
for( int i=0;i<comments.size();i++){
out.print("<li>" + (String) comments.get(i) + "</li>\n");
}//for
%>
</tr>
<tr>
<td>nom</td>
<td>
<%
for( int i=0;i<nom.size();i++){
out.print("<li>" + (String) nom.get(i) + "</li>\n");
}//for
%>
</tr>
<tr>
<td>id</td>
<td>
<%
for( int i=0;i<id.size();i++){
out.print("<li>" + (String) id.get(i) + "</li>\n");
}//for
%>
</tr>
</table>
</body>
</html>
This is how i used to create an XML file in a JSP page only without JSP/SERVLET concept:
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%
// Identify a carriage return character for each output line
int iLf = 10;
char cLf = (*char*)iLf;
// Create a new empty binary file, which will content XML output
File outputFile = *new* File("C:\\Users\\user\\workspace1\\demo\\WebContent\\YourFileName.xml");
//outputFile.createNewFile();
FileWriter outfile = *new* FileWriter(outputFile);
// the header for XML file
outfile.write("<?xml version='1.0' encoding='ISO-8859-1'?>"+cLf);
try {
// Define connection string and make a connection to database
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/SAMPLE","app","app");
Statement stat = conn.createStatement();
// Create a recordset
ResultSet rset = stat.executeQuery("Select * From posts");
// Expecting at least one record
*if*( !rset.next() ) {
*throw* *new* IllegalArgumentException("No data found for the posts table");
outfile.write("<Table>"+cLf);
// Parse our recordset
// Parse our recordset
*while*(rset.next()) {
outfile.write("<posts>"+cLf);
outfile.write("<postname>" + rset.getString("postname") +"</postname>"+cLf);
outfile.write("<comments>" + rset.getString("comments") +"</comments>"+cLf);
outfile.write("</posts>"+cLf);
outfile.write("</Table>"+cLf);
// Everything must be closed
rset.close();
stat.close();
conn.close();
outfile.close();
catch( Exception er ) {
%>Please state your problem that you are having more clearly so we can help.
I looked at your code I here are a few things you might consider:
It looks like you are putting freely typed-in comments from end-users into an xml document.
The problem with this is that the user may enter characters in his text that have special meaning
to xml and will have to be escaped correctly. Some of these characters are less than character, greater than character and ampersand character.
You may also have a similiar problem displaying them on your JSP page since there may be special characters that JSP has.
You will have to read up on how to deal with these special characters (I dont remember what the rules are). I seem to recall
if you use CDATA in your xml, you dont have to deal with those characters (I may be wrong).
When you finish writing your code, test it by entering all keyboard characters to make sure they are processed, stored in the database,
and re-displayed correctly.
Also, it looks like you are putting business logic in your JSP page (creating an xml file).
The JSP page is for displaying data ONLY and submitting back to a servlet. Put all your business logic in the servlet. Putting business logic in JSP is considered bad coding and will cause you many hours of headache trying to debug it. Also note: java scriptlets in a JSP page are only run when the JSP page is compiled into a servlet by java. It does not run after its compiled and therefore you cant call java functions after the JSP page is displayed to the client. -
Using a single connection for jsp, servlets and classes
Hi! I'm building a web site that uses JSP, Servlets and some classes. I use database access in all my pages. I want to open a connection and use it for all the pages while the user is in my site, so I don't need to open a connection with every new jsp or servlet page. My software must be capable of connection with various databases, like SQLServer, Oracle, Informix, etc... so the solution must not be database (or OS or web server) dependant.
Can you help me with this? Some ideas, links, tips? I'll REALLY appreciate your help.
Regards,
Raul Medinause an initialiation servlet with pooled connection which can be accessed as sesssion object.
Abrar -
How to work with EJBs and database for a simple login application
Hi all :)
I am new in JSP,EJB and Servlets. I just wanted to develop a simple login application, using JSP+EJBand servlets. In some tutorial I found that the beans are already populatesd with database records. But will it be good logic to retrive all records into a bean and then search for a perticuler users data for authentication.
Can any one tell me me what is the best logic for doing so. :(
Thanx in advance.Himanshu.Shekhar wrote:
Hi all :)
I am new in JSP,EJB and Servlets. I just wanted to develop a simple login application, using JSP+EJBand servlets. In some tutorial I found that the beans are already populatesd with database records. But will it be good logic to retrive all records into a bean and then search for a perticuler users data for authentication.No. Let the database do the search. It's far more efficient.
%
Maybe you are looking for
-
Same material master in two company codes with batch management
Hi, There are two company codes in one client. In one batch management is already active. But in another company code batch management is not required. Is it possible to have batch management active in one company code and inactive in another company
-
ITunes says i need to authorize, but i already did!
So i recently got an iphone 4s, but I used to have an ipod touch. I got all my apps to transfer from the ipod to my iTunes library on my computer, but now I can't get SOME of them to transfer from the library to my new iphone. For example, when i try
-
I would like to make an SD card with my favorite pics on it for playing in a digital photo frame. Anybody know how to do this or is it not possible?
-
TS3297 I don't know my security questions how can I change them
How can I change my security questions
-
How to upload photos from iPad mini to Win PC
I would like to know the most simple way of uploading the photos stored in my iPad mini to my Windows XP PC. They do not have to be synced. Tx.