HelloWorld servlet help !
Hi,
I compiled the simple HelloWorld.java and put it under /jakata-install-dir/webapps/webapp1/WEB-INF/classes/HelloWorld.class
Then, started the tomcat and this
http://localhost:8080/webapp1/servlet/HelloWorld
gave 404 error ??? file not found ???
Pls help. thanks.
P
I agree tomcat is fussy !!!
Yes, the webapps/examples/WEB-INF/classes works, but
I want to create a new application name say webapp1 to replace the name of "examples" above, then it failed !
I guess there must be some configuration needed to add a new application name after /install-dir/webapps/ ?
Moreover, I can't even log into administration page without the username and password. Cant found them ?!
P
Similar Messages
-
Help noob! HelloWorld Servlet
Using Windows & Sun Java System Application Server Platform Edition 9.0_01
I just would like to get such result:
http://localhost:8080/HelloWorld?name=MYNAME
Where HelloWorld is my simple servlet displays MYNAME
HelloWorld.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello extends HttpServlet
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name = req.getParameter("name");
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
out.println("<BODY>");
out.println("Hello, " + name);
out.println("</BODY></HTML>");
I have compiled it and get HelloWorld.class
Then I've copied that calss file to autodeploy folder.
Few minutes later I logged onto the Admin Page and saw that my Web Module appears in Applications -> Web Applications.
I'm trying http://localhost:8080/HelloWorld?name=MYNAME
"HTTP Status 404 - The requested resource () is not available."
I'm trying http://localhost:8080/HelloWorld
and getting just to /HelloWorld/ directory
"Directory Listing For /"
So, what am I doing wrong?
How to access my servlet?jaikiran, thanks for youe reply
I wish web.xml would be auto created after autodeploy..
But it didn't.
So I've created it myself and put to:
\domains\domain1\applications\j2ee-modules\HelloWorld\WEB-INF
<web-app>
<display-name>heelo</display-name>
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>
And I still getting the contents of direcory.... :(
I've got a feeling that I'm not doing autodeploy correctly...
Maybe there is some tutorial for hand-compiled classes wicha are being autodeployed? :oops: -
Beginner's Stuff - HelloWorld Servlet
Here's my net to nothing DD.
<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
</web-app>
The WebApp Name is Hello
Whatever I do (hostname:port/Hello/HelloWorld or hostname:port/Hello/servlet/HelloWorld
- This one run fine on Tomcat), I keep getting 404.
What Wrong ??? Somebody help before I go crazy.
Thanx.
You need to have a
<servlet-mapping>
<servlet-name>servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
see http://e-docs.bea.com/ for details :)
"Lindsay Chap" <[email protected]> wrote:
>
>Here's my net to nothing DD.
>
><?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE web-app
> PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
> "http://java.sun.com/dtd/web-app_2_3.dtd">
>
><web-app>
> <servlet>
> <servlet-name>HelloWorld</servlet-name>
> <servlet-class>HelloWorldServlet</servlet-class>
> </servlet>
></web-app>
>
>The WebApp Name is Hello
>Whatever I do (hostname:port/Hello/HelloWorld or hostname:port/Hello/servlet/HelloWorld
>- This one run fine on Tomcat), I keep getting 404.
>
>What Wrong ??? Somebody help before I go crazy.
>
>Thanx.
-
Just can't run HELLOWORLD servlet on Tomcat!
Hi there, I worked with servlets all summer long and now I'm getting back to build one, and I'm totally confused... My problem's there :
I try to run a simple HelloWorld servlet on Tomcat 4.1, and I get a 404 Error - Not found
Well, here's the structure of my web application, contained in simpleservlet.war :
WEB-APP
-web.xml
-CLASSES
-servlet.class
-LIB
-servlet.jar
Here's now the content of the web.xml file :
<web-app>
<servlet>
<servlet-name>serv</servlet-name>
<servlet-class>servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>serv</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
AND FINALLY here's how I invoke my servlet, I TRIED :
http://localhost:1977/servlet/test
AND ALSO
http://localhost:1977/test
AND BANG, I GET "ERROR 404 - NOT FOUND"
A little help would be appreciated A LOT, well it's not supposed to be a hard problem... and by the way, I'm using port :1977, the problem's not there though.
regards, PierreHi,
First try http://localhost:1977 and see if you are getting Tomcat. As you said, this is not a problem. So, you should get the index.html of the Tomcat. Now, click on the one of the example. From the Address Bar, you will know the path of this example. Try putting your page at that location and then run.
This should work.
-- Ashish. -
Jdbc-servlet help!!!!!!!!
excuse my english.
hey folks, i got this problem:
i`m trying to do a simple servlet that`s throw a html with a result, but i always got this error:
java.lang.NullPointerException
at ConsultaServlet.doPost(ConsultaServlet.java:45)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
THIS IS THE CODE I HAVE:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HolaServlet extends HttpServlet {
private Connection con;
private PrintWriter out;
private Statement stmt;
public void init(ServletConfig conf)
throws ServletException {
super.init(conf);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con =DriverManager.getConnection("jdbc:odbc:MS Access Database");
}catch(Exception e) {
System.err.println(e);
public void service(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
try {
out = res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title> Sample JDBC Servlet Demo" +
"</title>");
out.println("</head>");
out.println("<body>");
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from empleados");
out.println("<UL>");
while(rs.next()) {
out.println("<LI>" + rs.getString("nombre"));
out.println("</UL>");
rs.close();
stmt.close();
} catch(SQLException e) {
out.println("An SQL Exception was thrown.");
} catch(IOException e) {
System.err.println("An IOException was thrown.");
out.println("</body>");
out.println("</html>");
out.close();
public void destroy(){
try{
con.close();
}catch(SQLException e) {
Can someone tell me what i`m doing wrong.
THANK.Hi,
I have intalled the Javawebserver2.0
Its been installed on C:\javawebserver2.0.
After this I have set the autoexec.bat path as
PATH C:\WINDOWS;C:\WINDOWS\COMMAND;C:\ORAWIN95\bin;c:\Oracle\Ora81\bin;"C:\ProgramFiles\Oracle\jre\1.1.7\bin";c:\j2sdk1.4.2_04\bin;c:\JavaWebServer2.0\bin;c:\Jsdk2.0\bin
rem - By Windows 98 Network for Netware Upgrade - c:\windows\odihlp.exe
set classpath=.;c:\j2dsk1.4.2_04\jre\lib;c:\j2dsdk1.4.2_04\lib;c:\j2sdk1.4.2_04\bin;c:\JavaWebServer2.0\lib;c:\Jsdk2.0\lib
rem -;c:\jsdk2.1\src ;c:\jsdk2.1\lib;c:\Jsdk2.0\src
After doing this I wrote my first servlet program in the servlets directory of javawebserver2.0 saved and when I went to compile its not compiling throwing an error showing that it is unable to locate all the servlet packages. So in I thought might be there are 2 things one is either I have not imported javax.servlet.* and javax.servlet.httpServlet.* package, but I had included it, the next thing was to check the autoexec.bat path. I included in that javawebserver2.0 path. Now first I am not able to compile the servlet program. Can you help me with it.
I had downloaded jsdk2 from net and have given its path also in the autoexec but nothing is happening. I am using the following package to write and develop Java programs "j2sdk1.4.2_04". Can you explain to where I am going wrong. Please its a bit urgent.
Following is the program:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class helloWorld extends HttpServlet
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head><Title>Hello World</title></head>");
out.println("<body><big>Hello World</big>");
out.println("</body>");
out.println("</html>");
Help!!!!!!!! -
Running HelloWorld Servlet--Tomcat 4.1
Dear Sir,
With most humble submission I would like to inform you that I have recently downloaded Tomcat 4.1 from http://jakarta.apache.org/ and installed it on Windows 98. I am using jdk1.3
I am an amateur for Java Servlets. I am following the instructions given in the book "Java Servlet Programming" by O'reilly and according to this book I have to store my class files(I tried with HelloWorld.class) in the dir server_root/webapps/root/web-inf/classes dir. but when i called it from microsoft internet explorer 5.0(the browser i am using currently) using the URL http://localhost:8080/servlet/HelloWorld
I get the 404 error.
I also tried to call a static file (.html) by storing it in the dir server_root/webapps/root(according to the book) and i get the proper output but not in case of .class file. Even the example codes provided with the server do not run.
Please help me to fix out my problem.
Thanking you in anticipation,
Yours sincerely
roopeshHi:
1)You need set classpath
2) do you open your Tomcat?
Thank -
HelloWorld servlet sample code
I followed simple deployment in readme file, but not sure how to run it, please have a directory structure that will help me to understand <path-to-servlet>/<sample directory>/.
I also try to deploy it from WAR Deployment to OC4J using Standard J2EE way, I think it misses the input files to create archive file in "jar -cvfM HelloWorld.war" command.Hi,
Please have a look at the sample applications hosted at http://www.oracle.com/technology/sample_code/tech/java/servlets/index.html.
Hope this helps. -
Hi,
I recently wanted to try my hands on servlets.
I downloaded the eclipse J2EE ST (jst). I copied all the plugins and feature in to eclipse.
I created a Dynamic Web Project > New J2EE Project
Then I created a servlet HelloWorld.java, Now in the eclipse environment I keep getting this problem message
The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files HelloWorld.java EDaFS_Web/JavaSource line 1 April 7, 2005 12:13:50 PM
I can compile it at the prompt and the servlet does work in
localhost:8080/EDaFS_Web/HelloWorld
But I would like to remove this error.
Thanx in advance
Venkyi am having the follwoing error... pls any one help me
net.sf.jasperreports.engine.JRException: Errors were encountered when compiling report expressions class file:
1. The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files
public class report1_1195628974_967 extends JREvaluator
<--------->
1 errors
at net.sf.jasperreports.engine.design.JRAbstractCompiler.compileReport(JRAbstractCompiler.java:193)
at net.sf.jasperreports.engine.design.JRDefaultCompiler.compileReport(JRDefaultCompiler.java:105)
at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:212)
at com.amslogic.reports.BolReports.doGet(BolReports.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
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:585)
at org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:243)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
at org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:272)
at org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:161)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:245)
at org.apache.catalina.core.ApplicationFilterChain.access$0(ApplicationFilterChain.java:177)
at org.apache.catalina.core.ApplicationFilterChain$1.run(ApplicationFilterChain.java:156)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:152)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:152)
at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:118)
at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:929)
at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:160)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705)
at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:577)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:595) -
Retrieving cell values from html in servlet - help!
Dear all,
I've got a table. I want to put links in each cell box. No problem. However I want to know when i've moved to my link what number cell the link came from. This is proving to be a big problem.
Here is what i've tried:
writer.println("<TR><TH bgcolor=\"brown\">Brown<TD id=1><li>
<a href=BookingFromScreen>1</a></li></TD>" +
"<TD name = \"id\" value = \"2\"><li><a href=BookingFromScreen>2</a></li></TD>".. etc...
then picking the id's up in BookingFromScreen like this:
String cell = request.getParameter("id");
String cellNo= request.getParameter("value");
System.out.println("this is the cell parameter: " +cell);
System.out.println("this is the cell Number: " +cellNo);
Object cell1 = request.getAttribute("id");
String cell2 = (String)cell1;
System.out.println("this may work: "+cell2);
neither of these ways work, once link has been clicked all the information about that cell is lost, can anyone pleeeeeeeeeease tell me why this isn't working? both are in the doGet methods of their respective servlets if thats any help....
thank you
Jen Cjust use
writer.println("<TR><TH bgcolor=\"brown\">Brown<TD id=1><li>
<a href=BookingFromScreen?id=1>1</a></li></TD>" +
"<TD name = \"id\" value = \"2\"><li><a href=BookingFromScreen?id=2>2</a></li></TD>"also you should be using a jsp for this -
Trying to create object of a class within servlet - help!!
I have created and compiled the following classes within
C:\bea\wlserver6.1\config\mydomain\applications\DefaultWebApp\WEB-INF\classes
1)LoginServlet
2)LoginManager
3)I have LoginServlet trying to create an object of type LoginManager, very simple,
but I get the following errors:
Cannot resolve symbol: LoginManager lm = new LoginManager();
^
Cannot resolve symbol: LoginManager lm = new LoginManager();
^
4)I have the .java and .class files located within the same directory, so I don't
see what's wrong here??? HELP!
LoginManager looks like:
public class LoginManager {
public boolean authenticateUser(String username, String password){
boolean status = false;
//simple code for string matching
return status;
LoginServlet looks like:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class LoginServlet extends HttpServlet {
// Constructors
// Variables
public static final String CONTENT_TYPE = "text/html";
public boolean LOGIN_STATUS;
// Methods
public void service (HttpServletRequest req, HttpServletResponse res)
throws IOException {
String username = "";
String password = "";
LoginManager lm = new LoginManager();
username = req.getParameter("username");
password = req.getParameter("password");
LOGIN_STATUS = lm.authenticateUser(username, password);
res.setContentType(CONTENT_TYPE);
PrintWriter out = res.getWriter();
out.println("<html><head><title>Hello World</title></head>" +
"<body>Hello! Your login status is " + LOGIN_STATUS +
"</body>" +
"</html>");
public void init (ServletConfig config) throws ServletException {
super.init(config);Do you have . in the CLASSPATH when compiling your servlet?
ron <[email protected]> wrote:
I have created and compiled the following classes within
C:\bea\wlserver6.1\config\mydomain\applications\DefaultWebApp\WEB-INF\classes
1)LoginServlet
2)LoginManager
3)I have LoginServlet trying to create an object of type LoginManager, very simple,
but I get the following errors:
Cannot resolve symbol: LoginManager lm = new LoginManager();
^
Cannot resolve symbol: LoginManager lm = new LoginManager();
^
4)I have the .java and .class files located within the same directory, so I don't
see what's wrong here??? HELP!
LoginManager looks like:
public class LoginManager {
public boolean authenticateUser(String username, String password){
boolean status = false;
//simple code for string matching
return status;
LoginServlet looks like:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class LoginServlet extends HttpServlet {
// Constructors
// Variables
public static final String CONTENT_TYPE = "text/html";
public boolean LOGIN_STATUS;
// Methods
public void service (HttpServletRequest req, HttpServletResponse res)
throws IOException {
String username = "";
String password = "";
LoginManager lm = new LoginManager();
username = req.getParameter("username");
password = req.getParameter("password");
LOGIN_STATUS = lm.authenticateUser(username, password);
res.setContentType(CONTENT_TYPE);
PrintWriter out = res.getWriter();
out.println("<html><head><title>Hello World</title></head>" +
"<body>Hello! Your login status is " + LOGIN_STATUS +
"</body>" +
"</html>");
public void init (ServletConfig config) throws ServletException {
super.init(config);
Dimitri -
Sending a file from Applet to servlet HELP me Please
Sorry, i have the problem this is my code Applet & Servlet but it seems working asynchronously if you have some ideas please reply me i send bytes on outputstream but the inputstream of servlet receive nothing bytes but write my system.out.print on screen server:
Applet:
URL servletURL = new URL(codebase, "/InviaFile/servlet/Ricevi");
HttpURLConnection urlConnection = (HttpURLConnection) servletURL.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
urlConnection.setRequestProperty("Content-length", String.valueOf(100));
urlConnection.connect();
if(urlConnection.HTTP_BAD_REQUEST == HttpURLConnection.HTTP_BAD_REQUEST){
/*System.out.println("Cattiva Richiesta: "+urlConnection.getContentEncoding());
System.out.println("Tipo di metodo: "+urlConnection.getRequestMethod());
System.out.println("Tipo di Risposta: "+urlConnection.getResponseCode());
System.out.println("Tipo di messaggio: "+urlConnection.getResponseMessage());
System.out.println("Tipo di contenuto: "+urlConnection.getContentType());
System.out.println("Tipo di lunghezza contenuto: "+urlConnection.getContentLength());
System.out.println("Tipo di doinput: "+urlConnection.getDoInput());
System.out.println("Tipo di doouput: "+urlConnection.getDoOutput());
System.out.println("Tipo di URL: "+urlConnection.getURL());
System.out.println("Tipo di propriet� richiesta: "+urlConnection.getRequestProperty("Content-Type"));
System.out.println("Entra if");
DataOutputStream dout = new DataOutputStream(urlConnection.getOutputStream());
InputStream is = urlConnection.getInputStream();
if(ritornaFile("C:/Ms.tif", dout))System.out.println("Finita lettura");
dout.close();
urlConnection.disconnect();
System.out.println("Fine Applet");
}catch(Exception e) { System.err.println(e.getMessage());e.printStackTrace();}
public boolean ritornaFile(String file, OutputStream ots)throws Exception{
FileInputStream f = null;
try{
f = new FileInputStream(file);
byte[] buf = new byte[4 * 1024];
int byteLetti;
while((byteLetti = f.read()) != -1){ots.writeByte(buf, 0, byteLetti);ots.flush();
while((byteLetti = f.read()) != -1){ots.write(byteLetti);ots.flush();
System.out.println("byteLetti= "+byteLetti);
return true;
}catch(Exception ex){
System.err.println(ex.getMessage());
return false;
}finally{
if(f != null)f.close();
Servlet:
HttpSession ses = request.getSession(true);
System.out.println("Passa servlet "+request.getMethod());
System.out.println("Passa servlet "+ses.getId());
ServletInputStream servletinputstream = request.getInputStream();
DataInputStream dis = new DataInputStream(request.getInputStream());
int c = dis.available();
System.out.println("c="+c);
//ServletOutputStream servletoutputstream
//response.getOutputStream();
response.setContentType("application/octet-stream");
System.out.println("URI= "+request.getRequestURI());
System.out.println("pathTranslated: "+request.getPathTranslated());
System.out.println("RemoteUser: "+request.getRemoteUser());
System.out.println("UserInRole: "+String.valueOf(request.isUserInRole("")));
System.out.println("pathInfo: "+request.getPathInfo());
System.out.println("Protocollo: "+request.getProtocol());
System.out.println("RemoteAddr:"+request.getRemoteAddr());
System.out.println("RemoteHost:"+request.getRemoteHost());
System.out.println("SessionID:"+request.getRequestedSessionId());
System.out.println("Schema:"+request.getScheme());
System.out.println("SeesionValido:"+String.valueOf(request.isRequestedSessionIdValid()));
System.out.println("FromURL:"+String.valueOf(request.isRequestedSessionIdFromURL()));
int i = request.getContentLength();
System.out.println("i: "+i);
ritornaFile(servletinputstream, "C:"+File.separator+"Pluto.tif");
System.out.println("GetMimeType= "+getServletContext().getMimeType("Ms.tif"));
InputStream is = request.getInputStream();
int in = is.available();
System.out.println("Legge dallo stream in="+in);
DataInputStream diss = new DataInputStream(servletinputstream);
int ins = diss.read();
System.out.println("Legge dallo stream ins="+ins);
int disins = diss.available();
System.out.println("Legge dallo stream disins="+disins);
is.close();
System.out.println("Fine Servlet");
catch(Exception exception) {
System.out.println("IOException occured in the Server: " + exception.getMessage());exception.printStackTrace();
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
processRequest(request, response);
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
processRequest(request, response);
/** Returns a short description of the servlet.
public String getServletInfo() {
return "Short description";
public void ritornaFile(InputStream its, String fileDest )throws Exception{
FileOutputStream f = null;
try{
f = new FileOutputStream(fileDest);
byte[] buf = new byte[2 * 1024];
int byteLetti;
while((byteLetti = its.read()) != -1){
f.write(buf, 0, byteLetti);
f.flush();
System.out.println("Byteletti="+byteLetti);
}catch(Exception ex){
System.err.println(ex.getMessage());
}finally{
if(f != null)f.close();Hi all,
Can anyone help me.I am trying to send an audio file from a applet to servlet with HTTP method(no raw sockets), also the servlet shld be able to save the file on the server.Any suggestions welcome.USing audiostream class from javax.sound.sampled.
The part of applet code which calls servlet is :
URL url = new URL("http://" + host + "/" + context + "/servlet/UserUpdateWorkLogAudio?userid=" + userId.replace(' ', '+') + "&FileName=" + filename.replace(' ', '+'));
URLConnection myConnection = url.openConnection();
myConnection.setUseCaches(false);
myConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
myConnection.connect();
out = new BufferedOutputStream(myConnection.getOutputStream());
AudioSystem.write(audioInputStream, fileType,out); // IS THIS RIGHT APPROACH?
************************end of applet code**********************
************************servlet code******************************
try
{BufferedInputStream in = new BufferedInputStream(request.getInputStream());
????????What code shld i write here to get the audio file stream
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
*********************************************end***********************
Thanks
Joe. -
WAP/Servlet help is needed URGENT!!!
I've wrote this little wap-application, which update the library loans via mobile phones. I don't know why my login doesn't work properly (it gives error-messages in any cases). I believe I did everything right.
Can anyone PLEASE help me finding my mistakes!? I give all my dukes for working version of mine application.
This are my codes:
Servlet-class
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;
public class Uusinta extends HttpServlet {
Connection conn;
String TUNNUS = "2000000112222";
String user = null;
boolean yhteys = false;
static String [] otsikko = {
"<?xml version=\"1.0\" encoding=\"utf-8\"?>",
"<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.3//EN\" \"http://www.wapforum.org/DTD/wml13.dtd\"> " ,
"<wml>" ,
"<!-- Possible <head> elements here. --> " ,
"<template>" ,
"<do type=\"accept\" label=\"Ok\" name=\"back\" >" ,
"<prev/>" ,
"</do>" ,
"</template>" ,
"<card id=\"welcome\" title=\"WAP-kirjasto\" newcontext=\"true\">" ,
"<do type=\"accept\" name=\"back\"><noop/>" ,
"</do>" ,
"<p align=\"center\"><strong>TERVETULOA</strong></p>",
"<p><br/>Kirjastokortin numero:<br/>" ,
"<input type=\"text\" name=\"numero\" size=\"11\" format=\"*N\" maxlength=\"13\"/><br/>" ,
"Salasana:<br/>" ,
"<input type=\"text\" name=\"salasana\" size=\"4\" format=\"*N\" maxlength=\"4\"/><br/>" ,
"<a href=\"skripti.wmls#Login('$(numero)','$(salasana)','kayttaja')\">Sisaan </a></p>" ,
"</card>" ,
"<card id=\"loginError\">" ,
"<do type=\"prev\" label=\"Back\">" ,
"<go href=\"#welcome\"/>" ,
"</do>" ,
"<p align=\"center\"><br/>Korttinumero tai salasana on vaara.</p>" ,
"</card>" ,
"<card id=\"lainat\" newcontext=\"true\">" ,
"<do type=\"accept\" name=\"back\"><noop/>" ,
"</do>" ,
"<do type=\"options\" label=\"Lopeta\">" ,
"<go href=\"#goodbye\"/>" ,
"</do>" ,
"<p><b>Lainatut kirjat:</b></p><p> " ,
"<select name=\"item\" title=\"Lista\">"};
static String [] r2 = {
"</select>" ,
"<br/><a href=\"skripti.wmls#uusiNide('$(item)','valittu')\">Uusi valittu</a><br/>" ,
"<a href=\"skripti.wmls#uusiKaikki()\">Uusi kaikki</a></p>" ,
"</card>" ,
"<card id=\"virhe\">" ,
"<p>Kirjan uusiminen ei onnistunut. Yritä uudelleen.</p>" ,
"</card>" ,
"<card id=\"uusittu\">" ,
"<do type=\"prev\" label=\"Back\">",
" <go href=\"#lainat\"/>",
"</do>",
"<p align=\"center\"><br/>Kirja on uusittu.</p>" ,
"</card>" ,
"<card id=\"virheet\">" ,
"<p>Kirjojen uusiminen ei onnistunut. Yritä uudelleen.</p>" ,
"</card>" ,
"<card id=\"uusitut\">" ,
"<do type=\"prev\" label=\"Back\">",
" <go href=\"#goodbye\"/>",
"</do>",
"<p align=\"center\"><br/>Kirjat on uusittu.</p>" ,
"</card>" ,
"<card id=\"goodbye\" newcontext=\"true\">" ,
"<do type=\"accept\" name=\"back\"><noop/>" ,
"</do>" ,
"<p align=\"center\"><br/>Kiitos k�ynnist�. Ja tervetuloa uudelleen.</p>" ,
"</card>" ,
"</wml>"};
private void teeWML(PrintWriter out)
Statement stmt;
ResultSet result;
boolean ok = false;
for (int i = 0; i <otsikko.length;i++)
out.println(otsikko);
if(yhteys)
try {
stmt= conn.createStatement();
result = stmt.executeQuery("Select * FROM lainat l join kirja k on l.nide = k.nide where tunnus = '"+this.user+"'");
int cnt = 1;
while(result.next())
ok = true;
String nimi ="";
if(result.getString("nimi").length() > 8)
nimi = result.getString("nimi").substring(0,8) + "...";
else
nimi = result.getString("nimi");
out.println("<option value=\""+result.getString("l.nide")+"\">"+nimi+":"
result.getString("erapaiva")"</option>");
result.close();
stmt.close();
}catch (SQLException ex) {
System.out.println ("\nSQLException:");
while (ex != null) {
System.out.println ("SQLState: "+ ex.getSQLState());
System.out.println ("Message: "+ ex.getMessage());
System.out.println ("Vendor: "+ ex.getErrorCode());
ex = ex.getNextException();
else
out.println("<option value=\"0\">nothing</option>");
for (int i = 0; i <r2.length;i++)
out.println(r2[i]);
out.close();
private void uusiNide(PrintWriter out, String nide)
Statement stmt;
ResultSet result;
boolean ok=false;
try {
stmt= conn.createStatement();
result = stmt.executeQuery("Select nide from lainat where tunnus='"+user+"' ");
int cnt = 1;
while(result.next())
ok = true;
result.close();
stmt.close();
if(ok)
String pvm = getPvm();
stmt = conn.createStatement();
int a = stmt.executeUpdate("update lainat set erapaiva='"+pvm+"' where tunnus='"+user+"' AND nide='"+nide+"'");
}catch (SQLException ex) {
System.out.println ("\nSQLException:");
while (ex != null) {
System.out.println ("SQLState: "+ ex.getSQLState());
System.out.println ("Message: "+ ex.getMessage());
System.out.println ("Vendor: "+ ex.getErrorCode());
ex = ex.getNextException();
if(ok) {
out.println("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">");
out.println("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"><title>koe</title></head><body><p>OKnide</p></body></html>");
private void uusiKaikkiNiteet(PrintWriter out)
Statement stmt;
ResultSet result;
boolean ok=false;
//t�h�n tulee viel� korttinumero
try {
String pvm = getPvm();
stmt = conn.createStatement();
int a = stmt.executeUpdate("update lainat set erapaiva='"+pvm+"' where tunnus='"+user+"'");
}catch (SQLException ex) {
System.out.println ("\nSQLException:");
while (ex != null) {
System.out.println ("SQLState: "+ ex.getSQLState());
System.out.println ("Message: "+ ex.getMessage());
System.out.println ("Vendor: "+ ex.getErrorCode());
ex = ex.getNextException();
if(ok) {
out.println("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">");
out.println("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"><title>koe</title></head><body><p>OKKaikki</p></body></html>");
private void tarkKayttaja(PrintWriter out, String kayttaja, String password)
Statement stmt;
ResultSet result;
boolean ok=false;
String nimi = null;
if(user !=null && password !=null)
int salasana = Integer.parseInt(password);
try {
stmt= conn.createStatement();
result = stmt.executeQuery("Select * from kortti where numero='"+kayttaja+"' and salasana="+salasana);
while(result.next())
ok = true;
nimi = result.getString("nimi");
}catch (SQLException ex) {
System.out.println ("\nSQLException:");
while (ex != null) {
System.out.println ("SQLState: "+ ex.getSQLState());
System.out.println ("Message: "+ ex.getMessage());
System.out.println ("Vendor: "+ ex.getErrorCode());
ex = ex.getNextException();
if(ok) {
this.user= kayttaja;
yhteys = true;
//teeWML(out);
out.println("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">");
out.println("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"><title>koe</title></head><body><p>OK</p></body></html>");
//out.close();
teeWML(out);
public void init(ServletConfig cfg) throws ServletException
try{
Driver d = (Driver)Class.forName("com.mysql.jdbc.Driver").newInstance();
String sCon = "jdbc:mysql://localhost/kirjasto?user=oppilas&password=oppix";
conn = DriverManager.getConnection(sCon);
}catch(Exception e){
System.out.println ("Exception: "+ e.getMessage());
throw new ServletException(e.getMessage());
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
PrintWriter out = null;
String kutsu = req.getParameter("toiminto");
String uusinta = req.getParameter("uusinta");
String password = req.getParameter("password");
String kayttaja = req.getParameter("user");
if (kutsu == null) {
res.setContentType("text/vnd.wap.wml");
out = res.getWriter();
tarkKayttaja(out, null, null);
if(kutsu.equalsIgnoreCase("login")) {
res.setContentType("text/html");
out = res.getWriter();
tarkKayttaja(out, kayttaja, password);
if(kutsu.equalsIgnoreCase("uusi")) {
res.setContentType("text/html");
out = res.getWriter();
uusiNide(out, uusinta);
if(kutsu.equalsIgnoreCase("uusiKaikki")){
res.setContentType("text/html");
out = res.getWriter();
uusiKaikkiNiteet(out);
public void destroy()
try{
conn.close();
}catch(SQLException e){
System.out.println ("\nSQLException:");
System.out.println ("SQLState: "+e.getSQLState());
System.out.println ("Message: "+ e.getMessage());
System.out.println ("Vendor: "+ e.getErrorCode());
public String getPvm()
Calendar x = Calendar.getInstance();
x.add(Calendar.DATE, 30);
int Day = x.get(Calendar.DAY_OF_YEAR);
Day = Day+30;
x.set(Calendar.DAY_OF_YEAR, Day);
int monthDue = x.get(Calendar.MONTH);
int dayOfMonthDue = x.get(Calendar.DAY_OF_MONTH);
int yearDue = x.get(Calendar.YEAR);
System.out.println(yearDue+"-"+monthDue+"-"+dayOfMonthDue);
return (yearDue+"-"+monthDue+"-"+dayOfMonthDue);
skriptit.wmls
extern function uusiNide(prmIn,valittu) {
var str, result, okInd, pInd;
str = "http://localhost:8080/kirjasto/loans?toiminto=uusi&uusinta=" +URL.escapeString(prmIn);
var load = URL.loadString(str,"text/html");
okInd =String.find(load, "OKnide");
if( okInd != -1 ) {
result = WMLBrowser.setVar(valittu, prmIn);
WMLBrowser.go("#uusittu");
else {
WMLBrowser.go("#virhe");
return "";
extern function uusiKaikki() {
var str, result, okInd, pInd, val, valittu;
str = "http://localhost:8080/kirjasto/loans?toiminto=uusiKaikki&uusinta=";
var load = URL.loadString(str,"text/html");
okInd =String.find(load, "OKKaikki");
if( okInd != -1 ) {
WMLBrowser.go("#uusitut");
else {
WMLBrowser.go("#virheet");
return "";
extern function Login(prmNum, prmPass, kayttaja) {
var str, result, okInd, pInd, pos, nimi;
str = "http://localhost:8080/kirjasto/loans?toiminto=login&user="+URL.escapeString(prmNum)+"&password="+URL.escapeString(prmPass);
var load = URL.loadString(str,"text/html");
okInd =String.find(load, "OK");
if( okInd != -1 ) {
pos = String.find(load, "</p");
nimi = String.subString(load,(okInd + 7), (pos - okInd -7));
result = WMLBrowser.setVar(kayttaja, nimi);
WMLBrowser.go("#lainat");
else {
WMLBrowser.go("#loginError");
return "";
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN'
'http://java.sun.com/j2ee/dtds/web-app_2_3.dtd'>
<web-app>
<display-name>Verkkopizzeria</display-name>
<servlet>
<servlet-name>Vastaa</servlet-name>
<servlet-class>Vastaa</servlet-class>
</servlet>
<servlet>
<servlet-name>Uusinta</servlet-name>
<servlet-class>Uusinta</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Vastaa</servlet-name>
<url-pattern>/vastaa</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Uusinta</servlet-name>
<url-pattern>/loans</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
DB create and inserts
create table kortti(
numero char(13) not null,
nimi char(25),
osoite char(25),
postinro int(5),
puhelin char(15),
salasana int(4),
primary key(numero)
create table kirja(
nide char(10) not null,
nimi char(25) not null,
tekija char(25) not null,
vuosi int(4) not null,
primary key(nide)
create table lainat(
tunnus char(13) not null,
nide char(10) not null,
erapaiva date not null,
primary key (tunnus, nide),
foreign key (tunnus) references kortti,
foreign key (nide) references kirja );
insert into kortti
(numero, nimi, osoite, postinro, puhelin, salasana)
values
('2000000112222', 'Aku Ankka', 'Akunkatu 11', 00980, '0401231234', 2222);
insert into kortti
(numero, nimi, osoite, postinro, puhelin, salasana)
values
('2000000113333', 'Roope Set�', 'Mikonkatu 11', 00100, '0405552223', 3333);
insert into kortti
(numero, nimi, osoite, postinro, puhelin, salasana)
values
('2000000114444', 'Mikki Hiiri', 'Kissankuja 5', 00930, '04009876545', 4444);
insert into kortti
(numero, nimi, osoite, postinro, puhelin, salasana)
values
('2000000115555', 'Ville Vallaton', 'Mestarinrinne 4', 00310, '0952223335', 5555);
insert into kirja
(nide, nimi, tekija, vuosi)
values
('1111-85555','Wap', 'Pekka Niskanen', 2000);
insert into kirja
(nide, nimi, tekija, vuosi)
values
('1111-45345','Java 2', 'Pekka Niskanen', 2002);
insert into kirja
(nide, nimi, tekija, vuosi)
values
('1111-64648','J�rki ja tunteet', 'Jane Austin', 1998);
insert into kirja
(nide, nimi, tekija, vuosi)
values
('1111-15671','Rikos ja rangastus', 'Leo Tolstoy', 1998);
insert into kirja
(nide, nimi, tekija, vuosi)
values
('1111-85554','Inside Wap', 'Pekka Niskanen', 2002);
insert into lainat
(tunnus, nide, erapaiva)
values
('2000000112222', '1111-85555', '2004-5-01-11');
insert into lainat
(tunnus, nide, erapaiva)
values
('2000000112222', '1111-45345', '2004-5-01-11');
insert into lainat
(tunnus, nide, erapaiva)
values
('2000000112222', '1111-64648', '2004-5-01-12');
insert into lainat
(tunnus, nide, erapaiva)
values
('2000000113333', '1111-85554', '2004-5-01-11');
insert into lainat
(tunnus, nide, erapaiva)
values
('2000000114444', '1111-15671', '2004-5-01-12');So many things wrong with this post... from [url http://www.catb.org/~esr/faqs/smart-questions.html#urgent]How to Ask Questions the Smart Way:
Don't flag your question as ?Urgent?, even if it is for you
That's your problem, not ours. Claiming urgency is very likely to be counter-productive: most hackers will simply delete such messages as rude and selfish attempts to elicit immediate and special attention.
There is one semi-exception. It can be worth mentioning if you're using the program in some high-profile place, one that the hackers will get excited about; in such a case, if you're under time pressure, and you say so politely, people may get interested enough to answer faster.
This is a very risky thing to do, however, because the hackers' metric for what is exciting probably differ from yours. Posting from the International Space Station would qualify, for example, but posting on behalf of a feel-good charitable or political cause would almost certainly not. In fact, posting ?Urgent: Help me save the fuzzy baby seals!? will reliably get you shunned or flamed even by hackers who think fuzzy baby seals are important.
If you find this mysterious, re-read the rest of this how-to repeatedly until you understand it before posting anything at all.
Be precise and informative about your problem
Describe the symptoms of your problem or bug carefully and clearly.
Describe the environment in which it occurs (machine, OS, application, whatever). Provide your vendor's distribution and release level (e.g.: ?Fedora Core 1?, ?Slackware 9.1?, etc.).
Describe the research you did to try and understand the problem before you asked the question.
Describe the diagnostic steps you took to try and pin down the problem yourself before you asked the question.
Describe any recent changes in your computer or software configuration that might be relevant.
Do the best you can to anticipate the questions a hacker will ask, and to answer them in advance in your request for help.
Simon Tatham has written an excellent essay entitled How to Report Bugs Effectively. I strongly recommend that you read it.
Volume is not precision
You need to be precise and informative. This end is not served by simply dumping huge volumes of code or data into a help request. If you have a large, complicated test case that is breaking a program, try to trim it and make it as small as possible.
This is useful for at least three reasons. One: being seen to invest effort in simplifying the question makes it more likely that you'll get an answer, Two: simplifying the question makes it more likely you'll get a useful answer. Three: In the process of refining your bug report, you may develop a fix or workaround yourself
And from [url http://www.thejword.com]The J Word:
Code Tags
When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read. -
How can i use my helloworld servlet in apache-tomcat-mod_jk?
hi
i copied
helloworld.java helloworld.class
to
jakarta-tomcat-3.3.1/webapps/examples/WEB-INF/classes
i can use example servlets in that directory by accessing localhost/examples/servlets
and click links..(but if i type them in browser address bar, they dont' work either)
what setting am i missing?
thank youi didn't touch web.xml server.xml at all..
i got this with logs files
/usr/local/apache/logs/error_log
[Thu Jul 25 14:14:00 2002] [notice] Apache/1.3.26 (Unix) PHP/4.1.2 mod_jk/1.1.0 configured -- resuming normal operations
[Thu Jul 25 14:14:00 2002] [notice] Accept mutex: sysvsem (Default: sysvsem)
[Thu Jul 25 14:19:19 2002] [notice] caught SIGTERM, shutting down
[root@beautifulmind logs]#
[root@beautifulmind logs]# cat mod_jk.log
how does the link to jsp/servelt works and, not direct typing at address bar?
mod_jk.conf
<IfModule !mod_jk.c>
LoadModule jk_module libexec/mod_jk.so
</IfModule>
JkWorkersFile "/usr/local/jakarta-tomcat-3.3.1/conf/jk/workers.properties"
JkLogFile "/usr/local/jakarta-tomcat-3.3.1/logs/mod_jk.log"
JkLogLevel emerg
<Directory "/usr/local/jakarta-tomcat-3.3.1/webapps/examples">
Options Indexes FollowSymLinks
</Directory>
JkMount /admin ajp13
JkMount /admin/* ajp13
JkMount /examples ajp13
JkMount /examples/* ajp13
#added by eugene
JkMount /examples/servlet/* ajp13
#added by eugene
httpd.conf
Include /usr/local/jakarta-tomcat-3.3.1/conf/auto/mod_jk.con -
Servlet help....
I need some help trying to decipher some client/server code. The server has a servlet class, but I don't understand how that is exactly called. The client is a stand alone application, not webbased. Any ideas how the servlet is started?
I know the client application uses threads also. Let me know if more information is needed.java_fan_69 wrote:
In the client code, there is a line of code in the run() method of a thread:
int responseCode = getClient().executeMethod(method);where getClient() is just a method that creates an HttpClient and method is a PostMethod.
The servlet I have is called DirServlet.The client is not instantiating the servlet. It is sending an HTTP request over a network socket to an address. When the server, which is listening on the socket, sees the request, it directs the request to the servlet it has running on its end. The servlet executes some code, and sends back a response over the network. -
How to authenticate a Servlet-- HELP!!!!!!!!
I have a Java client that try to contact with a servlet using a user and a password.
I know that the authentication is correct, because the message "User OK" (showed
below) appear, but I don't know what to do now to obtain an UrlConnection with
the servlet.
Every time a do conn = url.openConnection(), I obtain this exception:
java.io.FileNotFoundException: http://localhost:80/myappp/server
Please, help me!!!!!!!
The code is:
try{
URL url = new URL("http://"+ host+":"+port+"/myapp/server");
Environment env = new Environment();
env.setProviderUrl("t3://localhost:80/myapp/server");
env.setSecurityPrincipal("system");
env.setSecurityCredentials("password");
Subject s = new Subject();
Context ctx = null;
ctx = env.getInitialContext();
Authenticate.authenticate(env, s);
ctx.lookup("");
System.out.println("User OK");
conn = url.openConnection();
catch (Exception e)
{System.out.println("User not authenticated :" + e.toString();}
Thank you very much,
IvanNo, well not how you've described it.
Instead Do your implementation as a bean, then use that bean in your servlet and in your 'class' (application/applet).
Maybe you are looking for
-
How do i set up my macbook pro to display on my Vizio flat screen TV
Just purchased a new MacBook Pro and i was curious about what Components i need to purchase to set it up, thanks!
-
File Upload extension that doesn't time out?!
Can anyone recommend a good File Upload utility that won't time out on a shared server? Ideally ASP/VBScript. Restrictions on our shared server mean that we only have 15 seconds to execute a script. My concern is that this just isn't going to be poss
-
Spool to pdf -not coming corectly
Hi, i'm trying to convert spool to pdf, i've set adobe pdf as default printer, PDf is geting generated but all Values & text to right side are getting truncated/cut. suppose if text is excise duty it is coming as excise du Pl suggest
-
why does a standalone program created in Labview 8.5 try connecting to the internet when the program only reads data through the serial port? Firewalls object to progams that contact the internet without permission. The created program is not perform
-
Why my Itunes is not shuffling songs all time?
After shuffling three or four songs from different albums, my Itunes will keep playing songs on shuffle mode from one album before going to the rest of my library. My Itunes is 10.6.3 version.