Stupid servlet problem!!!
Hi all,
I have a very stupid problem. I create and deploy simple servlet
(StupidServlet). In deployment descriptor I mapped it into
servlet/StupidServlet URL. Servlet is situated in MyWeb.war. I access it by
http://my-pc/NASApp/MyWeb/servlet/StupidServlet.
In init method I receive context (m_context = conf.getServletContext();)
In service method I make next things:
servletPathString = req.getServletPath();
realPathStub = m_context.getRealPath( "/" );
realPath = m_context.getRealPath( servletPathString );
And servlet prints results: servletPathString = /servlet/StupidServlet
realPathStub =
c:\iplanet\ias6\ias\APPS\MyApp\MyWeb\
realPath = null (!!!!!)
Could you describe me where my mistake. May be you have any ideas.
with regards,
Andrey Kirienko
Hi,
This is from the servlet 2.2 javadoc:
This method returns null if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive).
So, this method is unusefull when using war files.
Juan
Similar Messages
-
J_security_check servlet problems
Hi, we use forms based authentication in our web app and I've come across some bizarre behavior in j_security_check.
The problem is as follows: if a user goes to a form that is within our web application and sits on that form until their session times out, then decides to submit that form (triggering an HTTP POST), then iPlanet correctly displays the forms based login page. The problem hoewver is that after the user puts in their credentials and authenticates, iPlanet's j_security_check forgets where it was (the form page, call it foo.jsp for now) and it forgets where the data was being submitted to (we'll call it submitfoo.jsp for now). Furthermore the data is lost. What j_security_check ends up doing is somehow redirecting to the root of the web application, which in our case ends up displaying the stupid directory listing of our web app. We dont' have an index.html or index.jsp in our web app root and suppressing directory listings in iPlanet is not trivial (if someone knows how to do this reliably, apart from creating an index.html in all the directories i want suppressed, please let me know).
Soooo, does iPlanet consider this a bug with the j_security_check servlet used for form based authentication or is this a "feature" they offer? how can i as a developer get j_security_check to forward to a page other than what it decides?
Thanks,
RyanHi, we use forms based authentication in our web app and I've come across some bizarre behavior in j_security_check.
The problem is as follows: if a user goes to a form that is within our web application and sits on that form until their session times out, then decides to submit that form (triggering an HTTP POST), then iPlanet correctly displays the forms based login page. The problem hoewver is that after the user puts in their credentials and authenticates, iPlanet's j_security_check forgets where it was (the form page, call it foo.jsp for now) and it forgets where the data was being submitted to (we'll call it submitfoo.jsp for now). Furthermore the data is lost. What j_security_check ends up doing is somehow redirecting to the root of the web application, which in our case ends up displaying the stupid directory listing of our web app. We dont' have an index.html or index.jsp in our web app root and suppressing directory listings in iPlanet is not trivial (if someone knows how to do this reliably, apart from creating an index.html in all the directories i want suppressed, please let me know).
Soooo, does iPlanet consider this a bug with the j_security_check servlet used for form based authentication or is this a "feature" they offer? how can i as a developer get j_security_check to forward to a page other than what it decides?
Thanks,
Ryan -
WLS 5.1 sp8 servlet problems
Ok. I must be just plain stupid..... :-(
My environment:
Win2K advanced server
IIS 5.0
WLS 5.1 sp8
jdk 1.3
standard install directories. The only changes were to use the 1.3 jdk.
I can get jsps to run out of the /public_html/ directory. I've configured
iisproxy to proxy .jhtml, .jsp, and .svlt file extensions ( the .svlt for
servlets :-) ).
The server runs, the console runs, everything seems to be Ok, except, I
can't figure out how to run even the example SnoopServlet. The
weblogic.properties file has the examples registered defaulted.
I also get an evaluation period over on the cloudscape database, when the
server is starting up. So even the BigTel app has problems with the
database.
I also get that same missing javai.dll on startup. It does jump to the
interpreter though. I've seen the explanation on the javai.dll and can
accept that it will be fixed in sp9. I don't understand the cloudscape
thing. And for the life of me I can't figure out how to get the SnoopServlet
to run.
I'm running the version of WLS 5.1 that comes with Visual Cafe EE 4.0. and
have patched it up to sp8.
I thought that by adding the .svlt extension that the iisproxy would call
the Servlet. As in:
http://localhost/SnoopServlet.svlt would call the SnoopServlet from the
examples.
Any help would be appreciated.
GeorgeHi George,
Are you having fun yet? :-)
George Smith wrote:
Ok. I must be just plain stupid..... :-(
My environment:
Win2K advanced server
IIS 5.0
WLS 5.1 sp8
jdk 1.3
standard install directories. The only changes were to use the 1.3 jdk.
I can get jsps to run out of the /public_html/ directory. I've configured
iisproxy to proxy .jhtml, .jsp, and .svlt file extensions ( the .svlt for
servlets :-) ).
The server runs, the console runs, everything seems to be Ok, except, I
can't figure out how to run even the example SnoopServlet. The
weblogic.properties file has the examples registered defaulted.The registeration in the weblogic.properties file looks like this:
weblogic.httpd.register.snoop=examples.servlets.SnoopServlet
You can access it directly using the URL
http://myweblogic.machine.name:7001/snoop
In order to get IIS to proxy this appropriately, you need to specify the .svlt
extension to the URL. However, the above registration does not use this
extension so WLS will not find the servlet if append the extension. Therefore,
you need to do one of the following (but not both):
1.) Change your servlet registration to look like this:
weblogic.httpd.register.snoop.svlt=examples.servlets.SnoopServlet
2.) Change your IIS configuration to proxy by path. For example, configure IIS
to proxy all URLs with /weblogic using the WLForwardPath parameter and the
PathTrim parameter value of /weblogic. This will allow you to enter the
following URL in the browser:
http://myweblogic.machine.name:7001/weblogic/snoop
IIS will forward this because of the /weblogic but it will trim the URL to
/snoop before forwarding it to WLS (allowing WLS to find the servlet registered
with weblogic.httpd.register.snoop=examples.servlets.SnoopServlet).
I also get an evaluation period over on the cloudscape database, when the
server is starting up. So even the BigTel app has problems with the
database.Download and install the Cloudscape updater from the WebLogic 5.1.0 Service Pack
area.
I also get that same missing javai.dll on startup. It does jump to the
interpreter though. I've seen the explanation on the javai.dll and can
accept that it will be fixed in sp9. I don't understand the cloudscape
thing. And for the life of me I can't figure out how to get the SnoopServlet
to run.Hmm... I thought that the reason for the javai.dll thing was because you were
picking up a different version of some JDK files (javai.dll is from JDK 1.1.x).
I'm running the version of WLS 5.1 that comes with Visual Cafe EE 4.0. and
have patched it up to sp8.
I thought that by adding the .svlt extension that the iisproxy would call
the Servlet. As in:
http://localhost/SnoopServlet.svlt would call the SnoopServlet from the
examples.
Any help would be appreciated.
GeorgeHope this helps,
Robert -
Mildet connect to oracle DB using servlet problem ,help please
hi guys i have a problem am tring to connect my midlet to databse through midlet but i don`t know what is the problem so far the midlet already connect to my servlet url but the servlet cant read the parameters to open the connection for database
my servlet code
* To change this template, choose Tools | Templates
* and open the template in the editor.
import java.io.*;
import java.net.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.text.*;
* @author freddy
public class getconnection extends HttpServlet {
Statement statement;
ResultSet rs=null;
String bstr=null;
String bstr1=null;
String bstr2=null;
public void init()
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet getConnection</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet getConnection at " + request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
doPost(request,response);
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
DataInputStream in = new DataInputStream(
(InputStream)request.getInputStream());
String sid = in.readUTF();
String user = in.readUTF();
String pwd = in.readUTF();
// "jdbc:oracle:thin:@localhost:1521"+": "+sid
String message = message = "Name:"+bstr+" telephone:"+bstr1+" burthday:"+bstr2;
try {
connect(sid,user, pwd);
message += "100 ok connected";
} catch (Throwable t) {
message += "200 " + t.toString();
response.setContentType("text/plain");
response.setContentLength(message.length());
PrintWriter out = response.getWriter();
out.println(message);
in.close();
out.close();
out.flush();
private void connect(String sid, String user,String pwd)
throws Exception {
// Establish a JDBC connection to the MYSQL database server.
//Class.forName("org.gjt.mm.mysql.Driver");
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:"+sid,user,pwd);
System.out.print("connected");
try{
statement =conn.createStatement();
rs=statement.executeQuery(" Select*from WOH.P_DEMGRAPHICS where P_ID='P1000 '");
catch(SQLException e)
System.err.print(e);
try{
while (rs.next()) {
bstr=rs.getString(2);
bstr1=rs.getString(3);
bstr2=rs.getString(4);
statement.close();
catch (SQLException e) {
//bstr += e.toString();
System.err.println(e);
System.exit(1);
// Establish a JDBC connection to the Oracle database server.
//DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
//Connection conn = DriverManager.getConnection(
// "jdbc:oracle:thin:@localhost:1521:"+db,user,pwd);
// Establish a JDBC connection to the SQL database server.
//Class.forName("net.sourceforge.jtds.jdbc.Driver");
//Connection conn = DriverManager.getConnection(
// "jdbc:jtds:sqlserver://localhost:1433/"+db,user,pwd);
* Returns a short description of the servlet.
public String getServletInfo() {
return "Short description";
// </editor-fold>
}Midlet code
* To change this template, choose Tools | Templates
* and open the template in the editor.
import java.io.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
* @author freddy
public class testOrcl extends MIDlet implements CommandListener {
protected String url;
private String username;
private Display display;
private Command exit = new Command("EXIT", Command.EXIT, 1);;
private Command connect = new Command("Connect", Command.SCREEN, 1);
private TextField tb;
private Form menu;
private TextField tb1;
private TextField tb2;
DB db;
public testOrcl() throws Exception
display=Display.getDisplay(this);
url="http://localhost:8084/getConnection/getconnection";
public void startApp() {
displayMenu();
public void displayMenu()
menu= new Form("connect");
tb = new TextField("Please input database: ","",30,
TextField.ANY );
tb1 = new TextField("Please input username: ","",30,
TextField.ANY);
tb2 = new TextField("Please input password: ","",30,
TextField.PASSWORD);
menu.append(tb);
menu.append(tb1);
menu.append(tb2);
menu.addCommand(exit);
menu.addCommand(connect);
menu.setCommandListener(this);
display.setCurrent(menu);
public void pauseApp() {
public void destroyApp(boolean unconditional) { }
public void commandAction(Command command, Displayable screen) {
if (command == exit) {
destroyApp(false);
notifyDestroyed();
} else if (command == connect) {
db = new DB(this);
db.start();
db.connectDb(tb.getString(),tb1.getString(),tb2.getString());
* To change this template, choose Tools | Templates
* and open the template in the editor.
import java.io.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.lang.*;
* @author freddy
public class DB implements Runnable {
testOrcl midlet;
private Display display;
String sid;
String user;
String pwd;
public DB( testOrcl midlet)
this.midlet=midlet;
display=Display.getDisplay(midlet);
public void start()
Thread t = new Thread(this);
t.start();
public void run()
StringBuffer sb = new StringBuffer();
try {
HttpConnection c = (HttpConnection) Connector.open(midlet.url);
c.setRequestProperty(
"User-Agent","Profile/MIDP-2.1, Configuration/CLDC-1.1");
c.setRequestProperty("Content-Language","en-US");
c.setRequestMethod(HttpConnection.POST);
DataOutputStream os =
(DataOutputStream)c.openDataOutputStream();
os.writeUTF(sid.trim());
os.writeUTF(user.trim());
os.writeUTF(pwd.trim());
os.flush();
os.close();
// Get the response from the servlet page.
DataInputStream is =(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
showAlert(sb.toString());
is.close();
c.close();
} catch (Exception e) {
showAlert(e.getMessage());
/* This method takes input from user like db,user and pwd and pass
to servlet */
public void connectDb(String sid,String user,String pwd) {
this.sid = sid;
this.user = user;
this.pwd = pwd;
/* Display Error On screen*/
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
Comment out process request or rewrite & move it to a position after you read the parameters and connect to the db. Decide where you want to write to the output stream. Also, you have some superfluous casting.
I take it that you are using netbeans? If you debug and step through the code you will get an idea of the flow. The steps should be, midlet connects with POST, doPost is called, server reads parameters, server opens connection, executes query, releases/closes connection, and writes a response to the midlet.
Some notes about the connect method; The scope of rs may cause problems. It is unlike you will have a valid result set if you have a problem with create statement or execute. Take a look at connection pooling and be mindful how the connections are opened, used, and closed; put all the important cleanup operations in a finally. Remove system.exit from your servlet. Actually I would suggest limiting the scope of all your vars;
If you store the username, password, and sid on the midlet, you may have trouble updating the installation base if you need to change the values for any reason. Also, you have clients which contain your database u/p, susceptible to snooping and decompilation. Use the servlet to abstract the db from the client. And use a datasource (with connection pooling) for obtaining connections to db. -
Servlet problem: (Shay Shmeltzer / Steve Muench / Frank Nimphius)
Dear sirs... (Shay Shmeltzer / Steve Muench / Frank Nimphius)
I hope you can give me an answer.
I created an ADF UIX application using JDeveloper 10.1.2. I have created a servlet to download files. my problem is that it works just fine using jdeveloper, while when deployed into oracle application server it causes errors.i am calling this servlet by storing filename and data in the session, then sending redirect request to the browser.
the servlet code is:
package view;
import java.io.OutputStream;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.PrintWriter;
import java.io.IOException;
public class FileDownload extends HttpServlet
public void init(ServletConfig config) throws ServletException
super.init(config);
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
try
String DownloadFileName=(String) request.getSession().getAttribute("downloadfilename");
byte data[]=(byte []) request.getSession().getAttribute("downloadfiledata");
if (DownloadFileName==null)
return;
request.getSession().removeAttribute("downloadfilename");
request.getSession().removeAttribute("downloadfiledata");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename="+DownloadFileName);
response.setContentLength(data.length);
OutputStream OS=response.getOutputStream();
OS.write(data);
catch (Exception e)
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
try
String DownloadFileName=(String) request.getSession().getAttribute("downloadfilename");
byte data[]=(byte []) request.getSession().getAttribute("downloadfiledata");
if (DownloadFileName==null)
return;
request.getSession().removeAttribute("downloadfilename");
request.getSession().removeAttribute("downloadfiledata");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename="+DownloadFileName);
response.setContentLength(data.length);
OutputStream OS=response.getOutputStream();
OS.write(data);
catch (Exception e)
and the error is :
java.lang.IllegalStateException: Response has already been committed
at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.0.2)].server.http.EvermindHttpServletResponse.resetBuffer(EvermindHttpServletResponse.java:1902)
at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.0.2)].server.http.ServletRequestDispatcher.forward(ServletRequestDispatcher.java:213)
this error is stored in the log file. if i am running this code from JDeveloper I can download the files using either FireFox or Internet Explorer without any error.
but if i am running this code using Oracle Application Server 10g Realse 2, i can not download the files using either FireFox or IE.
so i created another solution, instead of redirecting from a datapage into the servlet, i put the following code in a data page as follows:
public void onDownload(DataActionContext ctx)
String DownloadFileName=getfilename();
byte data[]=getdata();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename="+DownloadFileName);
response.setContentLength(data.length);
OutputStream OS=response.getOutputStream();
OS.write(data);
OS.flash();
this time the application works fine when deployed into Oracle Application Server if you use FireFox, but if you use IE, it causes problem, i can not save the file or view it.
what is the problem?
how can i fix this?
i am certin that the second method is not correct and it should not be used.
thanks for everyone in advance
best regardsDear Sir...
Thanks alot for your replay
regarding the reset method. Itried it and it does not give any good.
I discovered the following problem:
If you are redirecting from with struts dataaction page to the servlet, you get the error
Otherwise if you called the servlet from directly or redirected to a servlet from within a servlet, you get no problem.
can any one help me please??
Is it possible that the problem is in IE itself? The file is downloaded perfectly fine with firefox(but the error log still appear)?
best regards -
Need urgent help on file download servlet problem in Internet Explore
I have trouble to make my download servlet work in Internet Explore. I have gone through all the previous postings and done some research on the internet, but still can't figure out the solution. <br>
I have a jsp page called "download.jsp" which contains a URL to download a file from the server, and I wrote a servlet (called DownloadServlet) to look up the corresponding file from the database based on the URL and write the file to the HTTP output to send it back to the browser. <br>
the URL in download.jsp is coded like <a href="/download/<%= currentDoc.doc_id %>/<%= currentDoc.name %>">on the browser, it will be sth like , the number 87 is my internal unique number for a file, and "myfile.doc" is the real document name. <br>
in my web.xml, "/download/" is mapped to DownloadServlet <br>
the downloadServlet.java looks like
tem_name = ... //read DB for file name
// set content type
if ( tmp_name.endsWith(".doc")) {
response.setContentType("application/msword");
else if ( tmp_name.endsWith(".pdf")){
response.setContentType("application/pdf");
else if ( tmp_name.endsWith(".ppt")){
response.setContentType("application/vnd.ms-powerpoint");
else if ( tmp_name.endsWith(".xls")){
response.setContentType("application/vnd.ms-excel");
else {
response.setContentType("application/download");
// set HTTP header
response.setHeader("Content-Disposition",
"attachment; filename=\""+tmp_name+"\"");
OutputStream os = response.getOutputStream();
//read local file and write back to browser
int i;
while ((i = is.read()) != -1) {
os.write (i);
os.flush();
Everything works fine in Netscape 7.0, when I click on the link, Netscape prompts me to choose "open using Word" or "save this file to disk". That's exactly the behavior I want. <br>
However in IE 5.50, the behavior is VERY STRANGE.
First, when I click on the URL, the popup window asks me to "open the file from its current location" or "save the file to disk". It also says "You have chosen to download a file from this location, ...(some url).. from localhost"
(1) If I choose "save the file to disk", it will save the rendered "download.jsp" (ie, the currect page with URL I just clicked, which isn't what I want).
(2)But if I choose "open the file from its current location", the 2nd popup window replaces the 1st, which also has the "Open ..." and "Save.." options, but it says "You have chosen to download a file from this location, MYFILE.doc from localhost". (notice it shows the correct file name now)
(3) If I choose "Save..." on the 2nd window, IE will save the correct file which is "myfile.doc"; if I choose "Open ...", a 3rd replaces the 2nd window, and they look the same, and when I choose "Open..." on the 3rd window, IE will use Word to open it.
any ideas?
</a>Did you find a solution to this problem? I've been wrestling with the same issues for the past six months. Nothing I try seems to work. I've tried setting the contentLength(), inline vs. attachments, different write algorythms, etc. I don't get the suggestion to rename the servlet to a pdf file.
-
Hi,
This question may sound a little bit stupid but i 'm new with HTML and servlets...
I am trying to do the following:
I have a FORM: <FORM NAME=\"form\">
in which there is a button:
<INPUT TYPE="BUTTON" NAME="searchSession" VALUE="Search" onClick="openWindow('searchSession');">
openWindow is a java script in which a new window is created:
newWindow = window.open('http://"+hostName+":8080/servlet/be.abis.presentation.EnrolmentServlet', 'Select Session', 'menubar,scrollbars,resizable,width=628,height=333');
in the servlet (EnrolementServlet) the request will be forwarded to a specific servlet. This happens through the following code:
if(request.getParameter("searchSession") != null){
requestDispatcher = getServletConfig().getServletContext().getRequestDispatcher("http://"+hostName+":8080/servlet/be.abis.presentation.SearchSessionServlet");
}else if(request.getParameter("ok") != null){
enrolmentBean.saveEnrolment();
}else{
createForm(request, response);
if(requestDispatcher != null){
requestDispatcher.forward(request, response);
what i do not understand is why the request is never forwarded to: http://"+hostName+":8080/servlet/be.abis.presentation.SearchSessionServlet
I 'll rally be thankful if someone could help me out of heren
thnx
PS: Session here has nothing to do with HTTPSessionI am doing the same thing and it do work.
my Javascript looks like following
function OpenNewWindow(url,title)
window.open(url, title, "width=650,height=400,status=yes,resizable=yes,toolbar=yes,status=yes,scrollbars=yes,location=yes,screenX=0,left=0,screenY=0,top=0");
Make sure your host name is right.
Hope this help!! -
Servlets - problem with session
Hi there ppl,
I have a login servlet which is called form a link in a static html page. The doGet() method is as below:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException
HttpSession session = public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException
HttpSession session = request.getSession(false);
RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
response.setContentType("text/html");
//PrintWriter out = response.getWriter();
if(session != null){
//display members page(with users name as a welcome)
System.out.println("in login servletb");
else{
System.out.println("in login servlet");
request.setAttribute("membersName", "adom");
rd.forward(request, response);
//out.close();
RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
if(session != null){
//display members page(with users name as a welcome)
System.out.println("session exists");
else{
System.out.println("session not exisit");
request.setAttribute("membersName", "adom");
rd.forward(request, response);
Problem is when i click on the link in the html page it goes into tthe else statement and displays the login.jsp page fine. But when i click bak on the browser and then click the link agian it goes into the if statemtn..as if a session exists. But why does a session exisit???...if i use request.getSession(false) this shouldnt create a session if one doent already exists so where is this mysterious session being created??
any ideas would be greatly appreaciated
Mycallyer i do need the session because in my doPost() method of the servlet i create a session once the user logs on with there login/pass. The doGet() method is only to direct the person to the login page. But i want to check for the session in the doGet() incase they have already login in...if so direct them to the main page rather than to the login page agian.
I stuffed up the code in my previous post...everything compiles and works fine apart from the fact that a session is created when it shouldnt be. I did a test println with session.getCreationTime() and it was created the same time the servlet was initial called. However im not sure if it was created by my servlet or if the broswer somehow had something to do with it....hmm is a worry.
Heres the code again...hopefully a bit neater for u :D
public void doGet(HttpServletRequest request, HttpServletResponse reponse)throws ServletException, java.io.IOException{
HttpSession session = request.getSession(false);
RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
if(session != null){
//display members page(with users name as a welcome)
System.out.println("session exists");
else{
System.out.println("no session");
request.setAttribute("membersName", "adom");
rd.forward(request, response);
thanks agian :) -
Import my own class into servlet problem
Hello, everyone.. I fail to import java classes that i create myself into the servlet. I wonder what is the problem. I would feel grateful if anyone can solve my problem. I noe that if it is in the package let say myclass , C:\jakarta-tomcat-4.1.29\webapps\lis\WEB-INF\classes\myclass. It will be
package myclass;
import myclass.*;
But, I put all my class file into below directory not in a package.
C:\jakarta-tomcat-4.1.29\webapps\lis\WEB-INF\classes
and i wish to include let say DBManager.class file into Login.class file which in in the same directory as above. What is the correct code i should put? Thanks for anyone who willing to help me out ~You don't need to import classes from the same package. They are automatically available in the same namespace. Just use them.
package myclasses;
import myclasses.*; // this line does nothing
import myctherclasses.*; // this line is necessary to use classes from another package.Having said that though, it is always preferable to put your classes in a package. Classes in the "unnamed" package are not guarunteed to be available anymore.
Particularly servlet classes which are not in a package aren't found by Tomcat.
In short: always put your classes into packages.
Cheers,
evnafets -
Calling servlet problem in iPlanet web server.
Hello, friends.
I have installed iPlanet web server 6.0. After installation I am using the default virtual server only. Thus, for all testing pages also, I use the default Document Root only (C:\iplanet\servers\docs\testsite) (I think, here "docs" is the default document root, right? If I am wrong, please correct me). I have got 2 JSP pages and 1 servlet. I put the JSP pages, into "testsite" folder and put the servlet into a folder called "myservlets" (C:iplanet\servers\docs\myservlets).
The jsp1.jsp page calls the servlet.class and in return the servlet redirects to jsp2.jsp page.
My question is: what paths should I use in jsp1.jsp file and in servlet.class file?
Thanks in Advance for all your help,
~ NiravThere is a major security breach in authenticating
iPlanet Web Server 6.0 SP3 and SP4 using Sun ONE
Directory Server. Using a valid user id, any
password except null string would allow user access
the restricted resources. iPlanet Web Server 6.0 SP5
and 4.1 SP12 worked fine with similar configuration.Did you get an answer for this?
We are having the exact same problems with our iPlanet Web server 6.0 SP3.
thank you. -
Hi,
I am trying to write a servlet to do a simple query against a database, however I am getting an "ERROR 405 - Resource not allowed".
I am getting nothing appearing in my webservers or the jdbc log, so I don't have a stack trace to show you all.
Any help would be appreaciated!!
Code Below (certain data removed for security):
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.sql.ResultSet.*;
import java.util.*;
import java.util.Arrays;
public class Mitch extends HttpServlet
private Connection connection;
private Statement statement;
public static ArrayList Array = new ArrayList();
public void init( ServletConfig config ) throws ServletException
try
String username = "xxxxxxx";
String password = "xxxxxxx";
Class.forName("com.ibm.db2.jcc.DB2Driver");
String dbURL = "jdbc:db2://IP ADDRESS AND PORT/DIR";
Properties conProps = new Properties();
conProps.setProperty( "user", username );
conProps.setProperty( "password", password );
connection = DriverManager.getConnection( dbURL, conProps );
statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
catch( Exception exception )
exception.printStackTrace();
throw new UnavailableException( exception.getMessage() );
}//end init
protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
out.println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n" );
out.println( "<HTML>\n<HEAD>" );
String sqlQuery;
try
sqlQuery = "SELECT h5_cpu_usr FROM ps_h5_cpu_fs_ap1 WHERE h5_dttm_stamp BETWEEN '2005-2-20 00:00:00.00000' AND '2005-2-20 23:00:00.000000'";
ResultSet resultSet = statement.executeQuery( sqlQuery );
out.println( "<TITLE> Servlet DB Test by Mitch </TITLE>" );
out.println( "</HEAD>" );
out.println( "<BODY>" );
out.println( "<P>This is a test to connect to a database, execute a simple SELECT and display the results below." );
out.println( "<br>\n<br>" );
Integer intObject;
while ( resultSet.next() )
intObject = new Integer( resultSet.getInt( 1 ) );
Array.add( intObject );
resultSet.close();
for( int i = 0; i < Array.size(); i++)
out.println(Array.get(i));
out.close();
}//end try
catch ( SQLException sqlEx )
sqlEx.printStackTrace();
out.println( "<TITLE>ERROR</TITLE>" );
out.println( "<HEAD>" );
out.println( "<BODY><P>An error occurred.<br>Contact Mitch!" );
out.println( "</P></BODY></HTML>" );
out.close();
}//doPost end
public void destroy()
try
statement.close();
connection.close();
catch( SQLException sqlEx )
sqlEx.printStackTrace();
}//end destroy
}//end Class
Thank you both for your replies
1. Yes I did.
2 See below
I found some sample code that I adapted to my code. I removed the init( ) method and used a doGet ( ) to call my doPost ( ) method.
The servlet now works!
Except for one thing...
It doesn't seem to be threading!
I did a simple test where two different users attempted to use the servlet at the same time, the results simply added to each other. The current query I am doing is one that returns approximately 100 rows and 1 column of 2-digit integers.
For example:
User 1 runs the servlet, output is:
12 45 56 66 65 23 06 03 34 56 78
User 2 runs the servlet after User 1, output is:
12 45 56 66 65 23 06 03 34 56 78 12 45 56 66 65 23 06 03 34 56 78
User 1 runs servlet again, after User 2, output is:
12 45 56 66 65 23 06 03 34 56 78 12 45 56 66 65 23 06 03 34 56 78 12 45 56 66 65 23 06 03 34 56 78
I hope this illustrates my problem clearly.
Also, I checked the database to see how many connections were open -- the servlet opens a NEW connection for EVERY query. These connections do not die until I kill my WebApp (WebLogic). It truely is a messy situation.
Any help would be appreaciated for this servlet newbie.
Thanks in advance.
New Code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.sql.ResultSet.*;
import java.util.*;
import java.util.Arrays;
public class Mitch extends HttpServlet
public static ArrayList Array = new ArrayList();
Connection connection;
Statement statement;
String username = "xxxxxxx";
String password = "xxxxxxx";
protected synchronized void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
doPost ( request, response );
protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
//HttpSession session = request.getSession(true);
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
out.println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n" );
out.println( "<HTML>\n<HEAD>" );
String sqlQuery;
//if(session.isNew())
try
Class.forName("com.ibm.db2.jcc.DB2Driver");
String dbURL = "jdbc:db2://xx.xx.xx.xx:yyyyy/zzzzzzz";
connection = DriverManager.getConnection( dbURL, username, password );
statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
sqlQuery = "SELECT h5_cpu_usr FROM ps_h5_cpu_fs_ap1 WHERE h5_dttm_stamp BETWEEN '2005-2-20 00:00:00.00000' AND '2005-2-20 23:00:00.000000'";
ResultSet resultSet = statement.executeQuery( sqlQuery );
out.println( "<TITLE> Servlet DB Test by Mitch </TITLE>" );
out.println( "</HEAD>" );
out.println( "<BODY>" );
out.println( "<P>This is a test to connect to a database, execute a simple SELECT and display the results below." );
out.println( "<br>\n<br>" );
Integer intObject;
while ( resultSet.next() )
intObject = new Integer( resultSet.getInt( 1 ) );
Array.add( intObject );
resultSet.close();
for( int i = 0; i < Array.size(); i++)
out.println(Array.get(i));
out.close();
}//end try
catch ( SQLException sqlEx )
sqlEx.printStackTrace();
out.println( "<TITLE>ERROR</TITLE>" );
out.println( "<HEAD>" );
out.println( "<BODY><P>An error occurred.<br>Contact Mitch!" );
out.println( "</P></BODY></HTML>" );
out.close();
catch( Exception exception )
exception.printStackTrace();
throw new UnavailableException( exception.getMessage() );
//else
// out.println( "<h1>This indicates an old session</h1>" );
}//doPost end
public void destroy()
try
statement.close();
connection.close();
catch( SQLException sqlEx )
sqlEx.printStackTrace();
}//end destroy
}//end Class
-
WLS 7.0 sp2 - Servlet Problems with SOAP messages
I'm using Weblogic 7.0 SP2 and trying to create a Servlet to receive SOAP wrapped
XML messages. I'm getting the following error. Is this a problem with WLS7.0sp2's
support of JAXM? The System.out.println's indicate I have successfully received
the incoming SOAP request and then successfully formatted the SOAP response, but
upon returning saving the response it appears to blow up. Does anyone have any
suggestions?
I need to do the following in a servlet:
- receive an incoming SOAP request with an embedded XML message
- perform some processing
- return a SOAP response with an embedded XML message
Should I be using JAXM? Or can I do this same task easily with JAX-RPC?
<Feb 24, 2004 4:10:42 PM AST> <Error> <HTTP> <101017> <[ServletContext(id=260434
7,name=isd.war,context-path=)] Root cause of ServletException
java.lang.Error: NYI
at weblogic.webservice.core.soap.SOAPMessageImpl.saveRequired(SOAPMessag
eImpl.java:360)
at javax.xml.messaging.JAXMServlet.doPost(Unknown Source)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run
(ServletStubImpl.java:1058)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
pl.java:401)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
pl.java:306)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationActio
n.run(WebAppServletContext.java:5445)
at weblogic.security.service.SecurityServiceManager.runAs(SecurityServic
eManager.java:780)
at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppSe
rvletContext.java:3105)
at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestIm
pl.java:2588)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:213)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:189)
>
I've stripped the code down so that all it does is verifies the incoming SOAP/XML
request and creates a hard-coded response... be gentle... I'm a novice at this
import javax.xml.soap.*;
import javax.servlet.*;
import javax.servlet.http.*;
// import javax.xml.transform.*;
import java.util.*;
import java.io.*;
public class RegisterServlet extends HttpServlet
static MessageFactory fac = null;
static
try
fac = MessageFactory.newInstance();
catch (Exception ex)
ex.printStackTrace();
public void init(ServletConfig servletConfig) throws ServletException
super.init(servletConfig);
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException
try
System.out.println("** Note: doPost() Entering req = " + req);
// Get all the headers from the HTTP request
MimeHeaders headers = getHeaders(req);
// Get the body of the HTTP request
InputStream is = req.getInputStream();
// Now internalize the contents of a HTTP request
// and create a SOAPMessage
SOAPMessage msg = fac.createMessage(headers, is);
System.out.println("** Note: doPost() Step A");
SOAPMessage reply = null;
reply = onMessage(msg);
System.out.println("** Note: doPost() Step B reply = " + reply);
if (reply != null)
* Need to call saveChanges because we're
* going to use the MimeHeaders to set HTTP
* response information. These MimeHeaders
* are generated as part of the save.
if (reply.saveRequired())
System.out.println("** Note: doPost() Step C reply.saveRequired()");
reply.saveChanges();
resp.setStatus(HttpServletResponse.SC_OK);
putHeaders(reply.getMimeHeaders(), resp);
// Write out the message on the response stream
OutputStream os = resp.getOutputStream();
System.out.println("** Note: doPost() Step D os = " + os);
reply.writeTo(os);
os.flush();
else
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
catch (Exception ex)
throw new ServletException("** Error: SAAJ POST failed: " + ex.getMessage());
static MimeHeaders getHeaders(HttpServletRequest req)
Enumeration enum = req.getHeaderNames();
MimeHeaders headers = new MimeHeaders();
while (enum.hasMoreElements())
String headerName = (String)enum.nextElement();
String headerValue = req.getHeader(headerName);
StringTokenizer values =
new StringTokenizer(headerValue, ",");
while (values.hasMoreTokens())
headers.addHeader(headerName,
values.nextToken().trim());
return headers;
static void putHeaders(MimeHeaders headers, HttpServletResponse res)
Iterator it = headers.getAllHeaders();
while (it.hasNext())
MimeHeader header = (MimeHeader)it.next();
String[] values = headers.getHeader(header.getName());
if (values.length == 1)
res.setHeader(header.getName(),
header.getValue());
else
StringBuffer concat = new StringBuffer();
int i = 0;
while (i < values.length)
if (i != 0)
concat.append(',');
concat.append(values[i++]);
res.setHeader(header.getName(), concat.toString());
// This is the application code for handling the message.
public SOAPMessage onMessage(SOAPMessage message)
SOAPMessage replymsg = null;
try
System.out.println("** Note: OnMessage() Entering msg = " + message);
//Extract the ComputerPart element from request message and add to reply SOAP
message.
SOAPEnvelope reqse = message.getSOAPPart().getEnvelope();
SOAPBody reqsb = reqse.getBody();
//System.out.println("** Note: OnMessage() Step B");
System.out.println("** Note: OnMessage () Step A Soap Request Message Body = "
+ reqsb);
//Create a reply mesage from the msgFactory of JAXMServlet
System.out.println("** Note: OnMessage () Step B");
replymsg = fac.createMessage();
SOAPPart sp = replymsg.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
SOAPBody sb = se.getBody();
System.out.println("** Note: OnMessage () Step C Soap Reply Before Message Body
= " + sb);
se.getBody().addBodyElement(se.createName("RegisterResponse")).addChildElement(se.createName("ErrorCode")).addTextNode("000");
System.out.println("** Note: OnMessage () Step D Soap Reply After Message Body
= " + sb);
replymsg.saveChanges();
System.out.println("** Note: OnMessage() Exiting replymsg = " + (replymsg));
catch (Exception ex)
ex.printStackTrace();
return replymsg;
Michael,
I got the same error on WLS8.1/Win2K professional and apache FOP (old version).
After digging into the WLS code and FOP(old version). i found the conflict happens
on
the "org.xml.sax.parser" system property. In WLS code, they hard coded like the
following when startup weblogic server:
System.setProperty("org.xml.sax.parser", "weblogic.xml.jaxp.RegistryParser");
But the FOP code try to use the "org.xml.sax.parser" system property to find the
sax parser then conlict happens.
Here is the response from BEA support :
"I consulted with our developers regarding the question of whether we can change
the hard-coded value for the java system property: org.xml.sax.parser by using
a configuration parameter and I found that unfortunately there is no specific
setting to change the value. As you had mentioned in your note the org.xml.sax.parser
system property can be changed programmatically in your application code."
I solve my problem by using newer apache FOP (it never use the system property:org.xml.sax.parser
any more) and XML Registy for WLS8.1.
Good luck.
David Liu
Point2 Technologies Inc.
"p_michael" <[email protected]> wrote:
>
Help.
When we migrated from WLS 6.1 to WLS 7.0 SP2 when encountered a problem
with XML
parsing that did not previously exist.
We get the error "weblogic.xml.jaxp.RegistryParser is not a SAX driver".
What does this mean? And, what should we do about it.
p_michael -
Servlet Problem with Back Button on IE
Hello All:
This is a weird problem I am facing on IE.
I have a servlet which is invoked by the doGet() method. This servlet
has a FORM which has few fields. One of the field has a hyperlink which
makes a window.open() call for Onclick. This pop-up allows a user to
search for some value. The result of the search is displayed in a
SELECT box. Based on the value selected in this SELECT box, the field
in the servlet that called this pop-up gets populated. After this is
done, I close this pop-up & click on the proceed button of the FORM
(using POST) which takes us to another servlet. Then when I click on
the back button, the fields on the form which were populated are gone.
I have made the following analysis:
(i) On clicking the back button, a request is sent to the server.
(ii) It works on FireFox & not on IE
(iii) If I do not use the hyperlink to bring the pop-up, and then I
click on proceed and then back, the fields do not vanish.
(iv) I tried using http://www.google.com to the call on window.open().
Does not help
(v) The very action of using pop-up by clicking on it causes this
problem
(vi) I tried replacing the hyperlink with a button. It did not work.
Any help or tips in this regard would be helpful.
Thanks in advance.
MaheshI dont know how you can post on the back button, and am a bit confused as to why you need to go back, you would normally want to go forwards :).
What I would do is have the same servlet handle both cases.
I would make 1 servlet SUBMIT TO ITSELF.
You may have to pass an additional parameter to indicate whether this is the initial / first request, or a subsequent request where the servlet has re-submitted back to itself.
If you want to disable the back button you can use javaScript
<script language="JavaScript" type="text/JavaScript">
<!--
javascript:window.history.forward(-1);
-->
</script>
I used this when I found that users could use the back button and re-submit when I didnt want them to, kind of the opposite of your problem! -
Why do we run into stupid basic problems with firefox?
I have jre1.6_u31 installed on a Windows 7 and the brilliant
firefox keep tell me that I've to install the jre_1.6_u29 missing plugin when I try to run an applet...a simple applet!! The plugin doesn't appear on add-ons manager then i use "check your plugins" and the stupid response is: "For your safety, Firefox has disabled your outdated version of Java. Please upgrade to the latest version."
Running an applet is basic! Why are u making new versions when older ones are better? I' m sick of running into this stupid problems with firefox! Everything works on ie, chrome and safari but not on Firefox!
I' m sick of trying to solve firefox basic problems!
We have a site that has one thousand ore more visits per day...and we only have troubles with firefox! What do I tell the costumers? I' m not going to give them solutions difficult and confusing as usually your solutions are! They are common people not developers as me...they just want the things to work! I gave up and the solution that I give to them now is to stop using firefox and uninstall it. And people ask I chrome is becoming the second most used browser...here is your answer...
I' m a developer and I've to develop I don't have the time patiente to trying solving basic firefox problems. If you don't know how to solve the problems then stop developing this and save us the headaches.Have you updated Java lately? You say you have jre1.6_u31 installed, but "Java(TM) Platform SE 6 U31" is not showing in the Plugins submitted with your question (click "More system details" to the right of your original question post). To enable, Add-ons > Plugins, and enable the item.
If your OS is 64-bit and you have 32-bit browsers (Firefox) and 64-bit browsers installed, then you need to install both the 32-bit and 64-bit versions of Java.
*See --> https://www.java.com/en/download/faq/java_win64bit.xml
'''Older versions of Java blocked in Firefox''' --> https://addons.mozilla.org/en-US/firefox/blocked/p80 <br />
'''Using/Updating Java''' --> [https://support.mozilla.org/en-US/kb/Using%20the%20Java%20plugin%20with%20Firefox#w_installing-or-updating-java Installing or Updating Java in Firefox] <br />
'''Unblocking Java''' --> https://support.mozilla.org/en-US/kb/unblocking-java-plugin
'''If this reply solves your problem, please click "Solved It" next to this reply when <u>signed-in</u> to the forum.''' -
Hello,
I have servlet in my web application module, and I try to make RFC call, within it. I use com.sap.mw.jco.*.
I compile it but when run the server respond with
Application error occurs during processing the request.
Details: java.lang.NoClassDefFoundError: com/sap/mw/jco/JCO The ID of this error is
Exception id: [000C763FB7EE00390000001F000007E800043A148A45F9B4
I think that I should packaged the jco lib in my war and make it available to servlet, but how can I do this ?
Thank for any help.Hello,
Thanks a lot Maksim, Bhavik, you helped me.
I try to make a reference and now the library ClassNotFound error is gone.
But now I have a next problem with RFC call, I also wrote it to post (Webdynpro VS. Java Servlet). I have a code in which I make RFC call. When I embed this code into regular Java aplication and run, it will return results as I expect. (of course I must run it with jco lib .jar in classpath). But when I run it on my servlet, I got an exception with message: "'mshost' missing"
I don't know what this supposed to mean, because I run the mentioned application, also from PC where I have j2ee engine installed and it work.
If you can please help.
(and thank for your help again (Maksim, Bhavik))
Maybe you are looking for
-
Will Yosemite address the Mavericks problem in connecting to smb servers?
-
How can I enable self capitalization of the pronoun "I" when using my Mac Pro?
I'm trying to see how to enable self-capitalization for the pronoun "I". This would be helpful when starting a sentence and/or when using the pronoun within a sentence. I tried system preferences and substitutions, but that will only work with words
-
GoldenGate ADD SCHEMATRANDATA and Patch 10423000
Hi, I want to enable supplemental logging just for a certain schema, so I issued: GGSCI> ADD SCHEMATRANDATA MySchema The response was: ERROR OGG-01783 Cannot verify existence of table function that is required to enable schema level supplemental logg
-
Rule Bases Check and CTP Settings
Dear Experts, I want to run Rule based ATP and CTP together in the system. As far as i know the system of each of these are typicAl and i am not able to run both together. Please guide me for any settings to be maintained to run the same. Thanks
-
No status assigned to version 0 in FM area MFMA . Message No FMCU
Hi Gurus, Have been doing the setting of Fund management / Budget. Need advice for 3 issues in this regard. Issue No. 1 - Is it possible to create period-wise budget in ECC 6.00 ? Issue No 2 : I selected the standard version of 0 in "OF21" - Define