|
David is right, this is too much to start with. You need to start with just JSPs or just JDBC.
But you could try this:
<%@ page language="java" import="java.sql.*" pageEncoding="ISO-8859-1"%>
<%@ page import="com.avanza.test1.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
</head>
<body>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
TestDB1 aa=new TestDB1();
aa.connect();
aa.display();
%>
</body>
</html>
|
|
|
|
|
That still doesn't work because the display() method directs the output to System.out, i.e. the console. In order to appear in the final web page it would need to be directed to the JSP output stream (there are a number of ways to do this).
The best thing to do is to find a beginner's JSP tutorial and start from there.
|
|
|
|
|
import java.io.IOException;
import java.sql.*;
import javax.servlet.http.*;
import oracle.jdbc.*;
public class TestDB1 extends HttpServlet
{
private static final long serialVersionUID = -1L;
private Connection con;
private PreparedStatement ps;
private ResultSet rs;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
try {
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:xe","system","admin");
ps = con.prepareStatement("select * from details");
rs = ps.executeQuery();
int count = 0;
while(rs.next())
{
response.getWriter().write("Name :: "+rs.getString(1)+" , Age :: "+rs.getString(2)+" , Phone No :: "+rs.getString(3)+"<br>");
count++;
}
response.getWriter().write(count+" records selected...");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Good luck
|
|
|
|
|
Thanx a lot for spending ur valuable time 2 help me out.. well i hav started reading Beginers Jsp book on Wrox publication its really helpful 2 understd.. Thanx again 4 ur advice..
Cheers,
Thashif
|
|
|
|
|
Sir,
I want to create a download manager as a part of my academic project. The code which I used is listed below.During the execution of this pgm, i faced a pblm . I can't able to download the url .Moreover , after downloding the url, I want to save it in a local directory.Can u help me for doing that.
Download.java
import java.io.*;
import java.net.*;
import java.util.*;
// This class downloads a file from a URL.
class Download extends Observable implements Runnable {
// Max size of download buffer.
private static final int MAX_BUFFER_SIZE = 1024;
// These are the status names.
public static final String STATUSES[] = {"Downloading",
"Paused", "Complete", "Cancelled", "Error"};
// These are the status codes.
public static final int DOWNLOADING = 0;
public static final int PAUSED = 1;
public static final int COMPLETE = 2;
public static final int CANCELLED = 3;
public static final int ERROR = 4;
private URL url; // download URL
private int size; // size of download in bytes
private int downloaded; // number of bytes downloaded
private int status; // current status of download
// Constructor for Download.
public Download(URL url) {
this.url = url;
size = -1;
downloaded = 0;
status = DOWNLOADING;
// Begin the download.
download();
}
// Get this download's URL.
public String getUrl() {
return url.toString();
}
// Get this download's size.
public int getSize() {
return size;
}
// Get this download's progress.
public float getProgress() {
return ((float) downloaded / size) * 100;
}
// Get this download's status.
public int getStatus() {
return status;
}
// Pause this download.
public void pause() {
status = PAUSED;
stateChanged();
}
// Resume this download.
public void resume() {
status = DOWNLOADING;
stateChanged();
download();
}
// Cancel this download.
public void cancel() {
status = CANCELLED;
stateChanged();
}
// Mark this download as having an error.
private void error() {
status = ERROR;
stateChanged();
}
// Start or resume downloading.
private void download() {
Thread thread = new Thread(this);
thread.start();
}
// Get file name portion of URL.
private String getFileName(URL url) {
String fileName = url.getFile();
return fileName.substring(fileName.lastIndexOf('/') + 1);
}
// Download file.
public void run() {
RandomAccessFile file = null;
InputStream stream = null;
try {
// Open connection to URL.
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
// Specify what portion of file to download.
connection.setRequestProperty("Range",
"bytes=" + downloaded + "-");
// Connect to server.
connection.connect();
// Make sure response code is in the 200 range.
if (connection.getResponseCode() / 100 != 2) {
error();
}
// Check for valid content length.
int contentLength = connection.getContentLength();
if (contentLength < 1) {
error();
}
/* Set the size for this download if it
hasn't been already set. */
if (size == -1) {
size = contentLength;
stateChanged();
}
// Open file and seek to the end of it.
file = new RandomAccessFile(getFileName(url), "rw");
file.seek(downloaded);
stream = connection.getInputStream();
while (status == DOWNLOADING) {
/* Size buffer according to how much of the
file is left to download. */
byte buffer[];
if (size - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[size - downloaded];
}
// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1)
break;
// Write buffer to file.
file.write(buffer, 0, read);
downloaded += read;
stateChanged();
}
/* Change status to complete if this point was
reached because downloading has finished. */
if (status == DOWNLOADING) {
status = COMPLETE;
stateChanged();
}
} catch (Exception e) {
error();
} finally {
// Close file.
if (file != null) {
try {
file.close();
} catch (Exception e) {}
}
// Close connection to server.
if (stream != null) {
try {
stream.close();
} catch (Exception e) {}
}
}
}
// Notify observers that this download's status has changed.
private void stateChanged() {
setChanged();
notifyObservers();
}
}
DownloadManager.java
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
// The Download Manager.
public class DownloadManager extends JFrame
implements Observer {
// Add download text field.
private JTextField addTextField;
// Download table's data model.
private DownloadsTableModel tableModel;
// Table listing downloads.
private JTable table;
// These are the buttons for managing the selected download.
private JButton pauseButton, resumeButton;
private JButton cancelButton, clearButton;
// Currently selected download.
private Download selectedDownload;
// Flag for whether or not table selection is being cleared.
private boolean clearing;
// Constructor for Download Manager.
public DownloadManager() {
// Set application title.
setTitle("Download Manager");
// Set window size.
setSize(640, 480);
// Handle window closing events.
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
actionExit();
}
});
// Set up file menu.
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenuItem fileExitMenuItem = new JMenuItem("Exit",
KeyEvent.VK_X);
fileExitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionExit();
}
});
fileMenu.add(fileExitMenuItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
// Set up add panel.
JPanel addPanel = new JPanel();
addTextField = new JTextField(30);
addPanel.add(addTextField);
JButton addButton = new JButton("Add Download");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionAdd();
}
});
addPanel.add(addButton);
// Set up Downloads table.
tableModel = new DownloadsTableModel();
table = new JTable(tableModel);
table.getSelectionModel().addListSelectionListener(new
ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
tableSelectionChanged();
}
});
// Allow only one row at a time to be selected.
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// Set up ProgressBar as renderer for progress column.
ProgressRenderer renderer = new ProgressRenderer(0, 100);
renderer.setStringPainted(true); // show progress text
table.setDefaultRenderer(JProgressBar.class, renderer);
// Set table's row height large enough to fit JProgressBar.
table.setRowHeight(
(int) renderer.getPreferredSize().getHeight());
// Set up downloads panel.
JPanel downloadsPanel = new JPanel();
downloadsPanel.setBorder(
BorderFactory.createTitledBorder("Downloads"));
downloadsPanel.setLayout(new BorderLayout());
downloadsPanel.add(new JScrollPane(table),
BorderLayout.CENTER);
// Set up buttons panel.
JPanel buttonsPanel = new JPanel();
pauseButton = new JButton("Pause");
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionPause();
}
});
pauseButton.setEnabled(false);
buttonsPanel.add(pauseButton);
resumeButton = new JButton("Resume");
resumeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionResume();
}
});
resumeButton.setEnabled(false);
buttonsPanel.add(resumeButton);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionCancel();
}
});
cancelButton.setEnabled(false);
buttonsPanel.add(cancelButton);
clearButton = new JButton("Clear");
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionClear();
}
});
clearButton.setEnabled(false);
buttonsPanel.add(clearButton);
// Add panels to display.
getContentPane().setLayout(new BorderLayout());
getContentPane().add(addPanel, BorderLayout.NORTH);
getContentPane().add(downloadsPanel, BorderLayout.CENTER);
getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
}
// Exit this program.
private void actionExit() {
System.exit(0);
}
// Add a new download.
private void actionAdd() {
URL verifiedUrl = verifyUrl(addTextField.getText());
if (verifiedUrl != null) {
tableModel.addDownload(new Download(verifiedUrl));
addTextField.setText(""); // reset add text field
} else {
JOptionPane.showMessageDialog(this,
"Invalid Download URL", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// Verify download URL.
private URL verifyUrl(String url) {
// Only allow HTTP URLs.
if (!url.toLowerCase().startsWith("http://"))
return null;
// Verify format of URL.
URL verifiedUrl = null;
try {
verifiedUrl = new URL(url);
} catch (Exception e) {
return null;
}
// Make sure URL specifies a file.
if (verifiedUrl.getFile().length() < 2)
return null;
return verifiedUrl;
}
// Called when table row selection changes.
private void tableSelectionChanged() {
/* Unregister from receiving notifications
from the last selected download. */
if (selectedDownload != null)
selectedDownload.deleteObserver(DownloadManager.this);
/* If not in the middle of clearing a download,
set the selected download and register to
receive notifications from it. */
if (!clearing) {
selectedDownload =
tableModel.getDownload(table.getSelectedRow());
selectedDownload.addObserver(DownloadManager.this);
updateButtons();
}
}
// Pause the selected download.
private void actionPause() {
selectedDownload.pause();
updateButtons();
}
// Resume the selected download.
private void actionResume() {
selectedDownload.resume();
updateButtons();
}
// Cancel the selected download.
private void actionCancel() {
selectedDownload.cancel();
updateButtons();
}
// Clear the selected download.
private void actionClear() {
clearing = true;
tableModel.clearDownload(table.getSelectedRow());
clearing = false;
selectedDownload = null;
updateButtons();
}
/* Update each button's state based off of the
currently selected download's status. */
private void updateButtons() {
if (selectedDownload != null) {
int status = selectedDownload.getStatus();
switch (status) {
case Download.DOWNLOADING:
pauseButton.setEnabled(true);
resumeButton.setEnabled(false);
cancelButton.setEnabled(true);
clearButton.setEnabled(false);
break;
case Download.PAUSED:
pauseButton.setEnabled(false);
resumeButton.setEnabled(true);
cancelButton.setEnabled(true);
clearButton.setEnabled(false);
break;
case Download.ERROR:
pauseButton.setEnabled(false);
resumeButton.setEnabled(true);
cancelButton.setEnabled(false);
clearButton.setEnabled(true);
break;
default: // COMPLETE or CANCELLED
pauseButton.setEnabled(false);
resumeButton.setEnabled(false);
cancelButton.setEnabled(false);
clearButton.setEnabled(true);
}
} else {
// No download is selected in table.
pauseButton.setEnabled(false);
resumeButton.setEnabled(false);
cancelButton.setEnabled(false);
clearButton.setEnabled(false);
}
}
/* Update is called when a Download notifies its
observers of any changes. */
public void update(Observable o, Object arg) {
// Update buttons if the selected download has changed.
if (selectedDownload != null && selectedDownload.equals(o))
updateButtons();
}
// Run the Download Manager.
public static void main(String[] args) {
DownloadManager manager = new DownloadManager();
manager.show();
}
}
DownloadTableModel.java
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
// This class manages the download table's data.
class DownloadsTableModel extends AbstractTableModel
implements Observer {
// These are the names for the table's columns.
private static final String[] columnNames = {"URL", "Size",
"Progress", "Status"};
// These are the classes for each column's values.
private static final Class[] columnClasses = {String.class,
String.class, JProgressBar.class, String.class};
// The table's list of downloads.
private ArrayList downloadList = new ArrayList();
// Add a new download to the table.
public void addDownload(Download download) {
// Register to be notified when the download changes.
download.addObserver(this);
downloadList.add(download);
// Fire table row insertion notification to table.
fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
}
// Get a download for the specified row.
public Download getDownload(int row) {
return (Download) downloadList.get(row);
}
// Remove a download from the list.
public void clearDownload(int row) {
downloadList.remove(row);
// Fire table row deletion notification to table.
fireTableRowsDeleted(row, row);
}
// Get table's column count.
public int getColumnCount() {
return columnNames.length;
}
// Get a column's name.
public String getColumnName(int col) {
return columnNames[col];
}
// Get a column's class.
public Class getColumnClass(int col) {
return columnClasses[col];
}
// Get table's row count.
public int getRowCount() {
return downloadList.size();
}
// Get value for a specific row and column combination.
public Object getValueAt(int row, int col) {
Download download = (Download) downloadList.get(row);
switch (col) {
case 0: // URL
return download.getUrl();
case 1: // Size
int size = download.getSize();
return (size == -1) ? "" : Integer.toString(size);
case 2: // Progress
return new Float(download.getProgress());
case 3: // Status
return Download.STATUSES[download.getStatus()];
}
return "";
}
/* Update is called when a Download notifies its
observers of any changes */
public void update(Observable o, Object arg) {
int index = downloadList.indexOf(o);
// Fire table row update notification to table.
fireTableRowsUpdated(index, index);
}
}
ProgressRenderer.java
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
// This class renders a JProgressBar in a table cell.
class ProgressRenderer extends JProgressBar
implements TableCellRenderer {
// Constructor for ProgressRenderer.
public ProgressRenderer(int min, int max) {
super(min, max);
}
/* Returns this JProgressBar as the renderer
for the given table cell. */
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
// Set JProgressBar's percent complete value.
setValue((int) ((Float) value).floatValue());
return this;
}
}
regards
Soumya
|
|
|
|
|
Why a new thread? This should be on your previous thread.
What is going wrong? I have no idea.
You need to format your code, use the <PRE> tag by clicking 'code block' above.
Do not post your entire project, just post the code were you think the problem is.
Debug it.
Give an example like:
Entered http://www.example.com and msgbox shows 'Invalid URL'.
Panic, Chaos, Destruction.
My work here is done.
|
|
|
|
|
hai,
While executing DownloadManager, an error is occured.ie when i give http://www.google.com the error message "invalid url " is displayaed. But i can able to download by specifiying the field name eg: http://www.nexegen.net/index.html. Wat is the pblm occured?
|
|
|
|
|
I want to download the url and save it in to a local directory as a part of my academic project, by using java(core java). But i am unable to download URL. Can u help me for doing that?
Regards
Soumya
|
|
|
|
|
First of all, URL means universal resource locator. I think you are refering to the content of an URL.
Now, what have you tried? I'll give you a clue, The Java Books[^] has a whole section on URL's.
- read
- practice
- understand
Panic, Chaos, Destruction.
My work here is done.
|
|
|
|
|
Here is a small example of how you would obtain the content
URL myURL = new URL("http://bla");
HttpURLConnection connection = (HttpURLConnection)myURL.openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
StringBuffer response = new StringBuffer(connection.getContentLength());
if(connection.getResponseCode() != 200 ) {
}
else {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = in.readLine()) != null) {
response.append(line);
}
}
in.close();
connection.disconnect();
|
|
|
|
|
Don't tell me!
Panic, Chaos, Destruction.
My work here is done.
|
|
|
|
|
hi.
ı will do the programme with java but my programme
must be code one to one check in row and error row's copy the new folder
|
|
|
|
|
Sorry, you are making no sense here.
0. You want to write a java program?
1. Reads in rows from a file?
2. Checks for /some condition/?
3. Writes what to new folder?
Please clarify what it is you are trying to do. State what you tried. Finally, ask for help with a specific problem. We are not in the habbit here of handing out code, so show some effort.
Panic, Chaos, Destruction.
My work here is done.
|
|
|
|
|
hi there, i have to develop an application where have a method that modify heavily one class instance and it take a lot of resources. I think that a good idea to solve it create a new object with new data something like :
public class A extend abstractclass {
//// data .... bla bla bla
A() {
//constructor ... bla bla bla
}
public void famousmet(blablabla) {
// i would like to work anything like:
this = new A(blablabla);
}
But this don't work.
How can i do it? is it possible? thanks.
|
|
|
|
|
Can you learn to format your code, it makes it readable:
public class A extend abstractclass {
A() {
}
public void famousmet(blablabla) {
this = new A(blablabla);
}
}
You cannot assign anything to this , it represents the current instance of the class.
A similar approach would be to create a new copy of the class and return it to the caller. Would this work:
public A copyAndReturn(blahblah) {
A copy = new A();
copy.variable = this.variable;
...
return copy;
}
Panic, Chaos, Destruction.
My work here is done.
|
|
|
|
|
Hello,
in my app I am extensively using JTree and building nodes with DefaultMutableTreeNode . But I didn't found the setToolTipText method in DefaultMutableTreeNode to tooltip its content, except this[^] article to do the same.
Any shorter idea, or already similar existing object within standard packages?
Kujtim
|
|
|
|
|
I think that looks a pretty tidy and simple solution.
You have the class ToolTipTreeCellRenderer , so use it as the renderer for your trees. Decide on an interface for the tool tip text, make sure your nodes support and use it.
Panic, Chaos, Destruction.
My work here is done.
|
|
|
|
|
How to round this 106.19999999999999 number like 106.20 by using java script?
|
|
|
|
|
udch wrote: java script
That's not Java
Anyway you could just do Math.round[^](106.19999999999999 * 100) / 100
|
|
|
|
|
Hi all,
I want to animate 2D images, specially face;
My scenario is i should draw contours of face around the image, on next key frame i should change the shapes of contour. When i animate i get the face in the image should animate accordingly.
It is something like morphing, but in morphing we have 2 images. In my scenario i have one image.
If i conclude i want some thing like this http://www.youtube.com/watch?v=ed_HAJGJfeQ[^]
I want to do it programatically, to create Talking Pictures.
I know you all guys are specialist into such kind of things. Please guide me how to full fill my scenario.
Thanks in advance.
Please do it as early as possible.
Nazar Hussain
|
|
|
|
|
Identical question on the C# forum, could the two be related?
Panic, Chaos, Destruction.
My work here is done.
|
|
|
|
|
I posted on two forums, so if any guru of Java or C# could help me.
|
|
|
|
|
Is the question Java or C#? If one or other, then in belongs in just the one.
Cross posts are very distracting, as you can see, a lot of pouple go to multiple forums and seeing the same post is just not accepted.
Please, only post a question in the one, most relevant, place. if you are not sure you are posting in the righ forum, say so up front and you will be directed, politely, to the correct forum.
Panic, Chaos, Destruction.
My work here is done.
|
|
|
|
|
Ok. Thanks for your guidance. I will never post same question on multiple forums.
Regards
Nazar
|
|
|
|
|
hi, im new to java.
regarding string array, is there a way to do string index.??
example:
String[] arr = null;
arr["name"]="myname";
arr["age"]="myage";
arr["gender"]="mygender";
The reason to my question is because im creating a class user. the variables will be private. i would need to get and set these variables, therefore creating a set of get() and set() function for each variable. If i can do the above method, i would simply need one set of get() and set() function.
hope thats not too confusing.
Thanks.
modified on Saturday, July 25, 2009 7:12 AM
|
|
|
|
|