JSP/Servlets & XML - suggestion needed

Hi everyone,
I don't have any coding issues, I'm really just looking for some help on deciding how to go with a project I want to make. First off, I wrote a Java library that builds messages in a special format. I wanted to come up with a pretty frontend for it, so I decided I'd try my hand at a webapp since I've been interested in them for a while. So far my web app consists of jsps, servlets and my library.
At this point I'd like to add the ability for the webapp to store created messages in an XML file (read / write). The XML library I want to use is JAXB. I have it setup to read/write my XML file fine in a test servlet, however I'd like to implement this in a kind of "best practice" approach. So I'm looking for suggestions on how I should do this.
A few of my ideas:
1) Use a jsp page to call a "MessagesBean" which retrieves my data from my xml file. I could then format this nicely in the jsp page. The problem with this however is that I can't find any way to open a file relative to the webapp from within a Bean. ie. when I try to open "messages.xml", I can see from tomcat errors that it attempts to open it in tomcats bin folder (or if i run from within eclipse, eclipses bin folder). I know I could get around this by using an absolute path but I want this to be portable. Any suggestions?
2) To solve the above problem I found "getServletContext().getRealPath("")" in the Servlet API. Using this method I'm able to open my XML file relative to my webapp. The only issue I have here is that I'm now using a servlet to display the page, making it harder for me to format the output.
I'm very new to JSP/Servlets/etc so I really don't know how I should be doing this. I'm just trying to make sure I don't start out on the wrong foot. Can someone please give some suggestions on what I could do?
Cheers.

I suggested not putting business logic in the servlet, but instead instansiating a business logic object in the servlet and calling one of its functions to do the work.
There is nothing wrong with putting the business logic in the servlet on first try. Just later on, you might want to refactor the code to more conform to the above.
In your code, you mentioned that the MessagesBean in the JSP page doesnt seem to call the constructor. The <useBean> tag first looks to
see if the object is in request scope. If it is, it uses it (doesnt call constructor). If its not, it creates its own (calls constructor). You should always
have it in request scope ready for useBean to use.
I think this line:
<jsp:useBean id="messages" class="my.package.MessagesBean" />
should be changed to something like:
<jsp:useBean id="messages" class="my.package.MessagesBean" scope="request" />
The MessagesBean should only have get/set methods to get data out of its object (its a very simple object that holds data). None of its functions
should perform business logic such as hitting the database.
Therefore these items in your JSP page should be in the servlet or business logic:
messages.setPath( getServletContext().getRealPath("") ); // Pass in relative PATH
messages.processXML(); // Process XML file
While this should be in your JSP:
java.util.List<TEXT> TextFiles = messages.getTEXTFiles(); // Return a List of TEXT objects
Question: The JSP calls my Bean "MessagesBean". It then passes in the current relative path. This seems fairly hackish to me, is there a better way to give the relative path to my bean?
Answer: Hard code the relative path to the JSP page in the servlet or business logic. There is no need for the JSP page to pass its path back to the servlet or business logic. Your servlet
'knows' the path to all the JSP pages it needs to dispatch to.
The best way to learn MVC is to continually refactor your code until it looks more and more like MVC (separation of concerns).

Similar Messages

  • Best way to see changes done to jsps/servlets/ejb/xmls in EAR

    I am using iPlanet app server with iPlanet web server. Everytime i make any change jsp/servlet/ejb i have to redeploy whole ear application again. This takes a long time. Even when i use the "iasdeploy redployapp " command to deploy, it takes same amount of time as it takes for the orignal deployment.
    So Is there any way to decrease the amount of the time it needs for me to re-deploy the applications when slight changes are made to application. I would really be thankful to anybody who can help me.

    Hi,
    I am facing this problem with a simple EAR file also. It does not contain any EJBs.
    It has just JSPs, XML, and JAVA Classes.
    The file size is about 481Kb.
    Earlier this used to get deployed using the "iasdeploy" command within 1 minute.
    Now it is taking more than 5 minutes to deploy the EAR file.
    I am using the following command :
    iasdeploy deployapp -verbose XYZ.ear
    The same holds true for the "iasdeploy removeapp -verbose XYZ.ear" also.
    Please help.
    Thanks,
    Samar

  • JSP Servlet and convert the result set of an SQL Query To XML file

    Hi all
    I have a problem to export my SQL query is resulty into an XML file I had fixed my servlet and JSP so that i can display all the records into my database and that the goal .Now I want to get the result set into JSP so that i can create an XML file from that result set from the jsp code.
    thisis my servlet which will call the jsp page and the jsp just behind it.
    //this is the servlet
    import java.io.*;
    import java.lang.reflect.Array;
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.naming.*;
    import javax.sql.*;
    public *class *Campaign *extends *HttpServlet
    *private* *final* *static* Logger +log+ = Logger.+getLogger+(Campaign.*class*.getName());
    *private* *final* *static* String +DATASOURCE_NAME+ = "jdbc/SampleDB";
    *private* DataSource _dataSource;
    *public* *void* setDataSource(DataSource dataSource)
    _dataSource = dataSource;
    *public* DataSource getDataSource()
    *return* _dataSource;
    *public* *void* init()
    *throws* ServletException
    *if* (_dataSource == *null*) {
    *try* {
    Context env = (Context) *new* InitialContext().lookup("java:comp/env");
    _dataSource = (DataSource) env.lookup(+DATASOURCE_NAME+);
    *if* (_dataSource == *null*)
    *throw* *new* ServletException("`" + +DATASOURCE_NAME+ + "' is an unknown DataSource");
    } *catch* (NamingException e) {
    *throw* *new* ServletException(e);
    protected *void *doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    Connection conn = *null*;
    *try* {
    conn = getDataSource().getConnection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select post_id,comments,postname from app.posts");
    // out.println("Le r&eacute;sultat :<br>");
    ArrayList <String> Lescomments= *new* ArrayList<String>();
    ArrayList <String> Lesidentifiant = *new* ArrayList<String>();
    ArrayList <String> Lesnoms = *new* ArrayList <String>();
    *while* (rs.next()) {
    Lescomments.add(rs.getString("comments"));
    request.setAttribute("comments",Lescomments);
    Lesidentifiant.add(rs.getString("post_id"));
    request.setAttribute("id",Lesidentifiant);
    Lesnoms.add(rs.getString("postname"));
    request.setAttribute("nom",Lesnoms);
    rs.close();
    stmt.close();
    *catch* (SQLException e) {
    *finally* {
    *try* {
    *if* (conn != *null*)
    conn.close();
    *catch* (SQLException e) {
    // les param&egrave;tres sont corrects - on envoie la page r&eacute;ponse
    getServletContext().getRequestDispatcher("/Campaign.jsp").forward(request,response);
    }///end of servlet
    }///this is the jsp page called
    <%@ page import="java.util.ArrayList" %>
    <%
    // on r&eacute;cup&egrave;re les donn&eacute;es
    ArrayList nom=(ArrayList)request.getAttribute("nom");
    ArrayList id=(ArrayList)request.getAttribute("id");
    ArrayList comments=(ArrayList) request.getAttribute("comments");
    %>
    <html>
    <head>
    <title></title>
    </head>
    <body>
    Liste des campagnes here i will create the xml file the problem is to display all rows
    <hr>
    <table>
    <tr>
    </tr>
    <tr>
    <td>Comment</td>
    <td>
    <%
    for( int i=0;i<comments.size();i++){
    out.print("<li>" + (String) comments.get(i) + "</li>\n");
    }//for
    %>
    </tr>
    <tr>
    <td>nom</td>
    <td>
    <%
    for( int i=0;i<nom.size();i++){
    out.print("<li>" + (String) nom.get(i) + "</li>\n");
    }//for
    %>
    </tr>
    <tr>
    <td>id</td>
    <td>
    <%
    for( int i=0;i<id.size();i++){
    out.print("<li>" + (String) id.get(i) + "</li>\n");
    }//for
    %>
    </tr>
    </table>
    </body>
    </html>
    This is how i used to create an XML file in a JSP page only without JSP/SERVLET concept:
    <%@ page import="java.sql.*" %>
    <%@ page import="java.io.*" %>
    <%
    // Identify a carriage return character for each output line
    int iLf = 10;
    char cLf = (*char*)iLf;
    // Create a new empty binary file, which will content XML output
    File outputFile = *new* File("C:\\Users\\user\\workspace1\\demo\\WebContent\\YourFileName.xml");
    //outputFile.createNewFile();
    FileWriter outfile = *new* FileWriter(outputFile);
    // the header for XML file
    outfile.write("<?xml version='1.0' encoding='ISO-8859-1'?>"+cLf);
    try {
    // Define connection string and make a connection to database
    Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/SAMPLE","app","app");
    Statement stat = conn.createStatement();
    // Create a recordset
    ResultSet rset = stat.executeQuery("Select * From posts");
    // Expecting at least one record
    *if*( !rset.next() ) {
    *throw* *new* IllegalArgumentException("No data found for the posts table");
    outfile.write("<Table>"+cLf);
    // Parse our recordset
    // Parse our recordset
    *while*(rset.next()) {
    outfile.write("<posts>"+cLf);
    outfile.write("<postname>" + rset.getString("postname") +"</postname>"+cLf);
    outfile.write("<comments>" + rset.getString("comments") +"</comments>"+cLf);
    outfile.write("</posts>"+cLf);
    outfile.write("</Table>"+cLf);
    // Everything must be closed
    rset.close();
    stat.close();
    conn.close();
    outfile.close();
    catch( Exception er ) {
    %>

    Please state your problem that you are having more clearly so we can help.
    I looked at your code I here are a few things you might consider:
    It looks like you are putting freely typed-in comments from end-users into an xml document.
    The problem with this is that the user may enter characters in his text that have special meaning
    to xml and will have to be escaped correctly. Some of these characters are less than character, greater than character and ampersand character.
    You may also have a similiar problem displaying them on your JSP page since there may be special characters that JSP has.
    You will have to read up on how to deal with these special characters (I dont remember what the rules are). I seem to recall
    if you use CDATA in your xml, you dont have to deal with those characters (I may be wrong).
    When you finish writing your code, test it by entering all keyboard characters to make sure they are processed, stored in the database,
    and re-displayed correctly.
    Also, it looks like you are putting business logic in your JSP page (creating an xml file).
    The JSP page is for displaying data ONLY and submitting back to a servlet. Put all your business logic in the servlet. Putting business logic in JSP is considered bad coding and will cause you many hours of headache trying to debug it. Also note: java scriptlets in a JSP page are only run when the JSP page is compiled into a servlet by java. It does not run after its compiled and therefore you cant call java functions after the JSP page is displayed to the client.

  • Why do I need JSP, Servlets, JSF?

    I want to design web pages in HTML and Javascript and use EJBs to handle business logic. That's it. I don't want to learn another API (ie JSP, Servlets, ...) for designing web pages. Is there a way I can access EJBs from Javascript using XML-based messaging or some other means? JSP seems like a waste.

    Hi,
    JSP is just like HTML mix with JAVA codes. You can mix it with servlets, as you can use servlets to access methods within your EJB. You can call a servlet from within your JSP. Use your JSP as presentation and use the servlets to get data from the EJB and pass it on to your presentation to display it to user. I am not sure of any other way. If you are trying to use Java application server as your server. Then, you have to follow the rules. Otherwise, use another technology such as HTML with ASP or even .NET. So you may have to install IIS as the server. OK
    eve

  • Ias support for EJB, JSP/servlets,JDBC, connection pooling, XML, SOAP, load balancing etc

    Please let me know where I can find more information regarding iPlanet usage/deployment/configuring/tuning etc for support of technologies - like EJB, JSP/servlets, JDBC, connection pooling, XML, load balancing, JDBC & Transactions
    (I have already read the 'Getting Started with the iPlanet Application Server' part five and six - http://developer.iplanet.com/appserver/testdrive/partfive.jsp and partsix.jsp)(I am using the ias testdrive version).

    Hi,
    It's difficult to explain unless the J2EE architecture is understood. Also, explaining things like load balancing, Transactions, tuning, are bit vague and could blow the disk space of this site.
    To get started, the best way is to test the sample applications and the best part is you don't require internet connection to follow each steps. Install iWS and iAS, open browser, type in http://hostname:port/ias-samples/index.html. You can find links to the sample applications bundled. Please follow the steps given on deploying the application. This will enable you to a higher level.
    Regards
    Ganesh .R
    Developer Technical Support
    Sun Microsystems
    http://www.sun.com/developers/support

  • Session timing in jsp/servlets

    Hi all..!
    I have a small problem..Plz help me..
    We are developing an application in JSP, Servlets on Linux Platform. Here, the default session time set is 30 mins. But I need to extend it by another 15 mins.. i.e., my session should be set to atleast 45 mins..
    I can do it using the setMaxInactiveInterval(int interval). which sets the amount of time that the session will remain active between requests
    before expiring and the int getMaxInactiveInterval() , Which will return the length of time that the session will remain active between requests before
    expiring.
    Through the above method,I can set the session time. But the version of Servlets I have on my system is 2.0 JAR. and The above mentioned methods work only for servlets version 2.1 and above..
    Could U plz suggest a way where I can set the session time for the version of servlets I have?? Plz help me with the solution in servlet/jsp.
    This is quite urgent. Plz try and help me.
    Thanx and regards
    Aparna

    Hi Aparna,
    It seems that u can't set and get the Session timing in servlet 2.0, because the setMaxInactiveInterval() and getMaxInactiveInterval() methods are being introduced only in 2.1.
    But One thing u can try out. Use getLastAccessedTime() method, which will return the last time that a client sent a request for that session. After that u can easily calculate the inactive time. Hope it will work.
    ragards,
    Atanu
    Hi all..!
    I have a small problem..Plz help me..
    We are developing an application in JSP, Servlets on
    Linux Platform. Here, the default session time set is
    30 mins. But I need to extend it by another 15 mins..
    i.e., my session should be set to atleast 45 mins..
    I can do it using the setMaxInactiveInterval(int
    interval). which sets the amount of time that the
    session will remain active between requests
    before expiring and the int getMaxInactiveInterval()
    , Which will return the length of time that the
    session will remain active between requests before
    expiring.
    Through the above method,I can set the session time.
    But the version of Servlets I have on my system is 2.0
    JAR. and The above mentioned methods work only for
    servlets version 2.1 and above..
    Could U plz suggest a way where I can set the session
    time for the version of servlets I have?? Plz help me
    with the solution in servlet/jsp.
    This is quite urgent. Plz try and help me.
    Thanx and regards
    Aparna

  • Sample jsp servlet bean (MVC) code

    We want to look into the JSP/Servlet/Bean area for our next project. We wish to understand the technology and as such want to hand build simple applications, and as such do not want to use JDeveloper just yet.
    We have searched and searched for suitable material but cannot anywhere find a sample application that :
    A. Lists contents of a databse table
    B. Each item in trhe list is a link to a page that allows that item, to be edited.
    C. A new item can be added.
    D. Uses the MVC model of JSP/Servlet and bean (preferably with no custom tags)
    There are examples that are too simplistic and do not cover the whole picture. Having spent over 100 GBP on books lately, only to be disappointed with the examples provided, we need to see some sample code.
    The samples provided by Oracle are too simplistic. They should really have provided ones built around the EMP and DEPT tables.
    Anyone know where we can get hold of this sample code.

    At the risk of sounding really dumb the examples are just too complex. There does not appear to be anywhere on the web where I can find a simple JSP/servlet/bean example of the type I described. There is enouigh material describing each individual component, but what I need is an example to cement the ideas, but the ones suggested are too much for a newbie. Even the much vaunted Pet Store thingy causes my eyes to glaze over.
    I dont expect anyone to have written something with my exact requirements, but surely to goodness there must be something that:
    1. On entry presents a search form on a table (e.g. EMP)
    2. On submission list all rows in EMp matchiung the criteria.
    3. The user can either click the link 'Edit' which opens up a form dispalying the row allowing the user to edit and save the changes, or click the 'New' button to show a blank form to create a new EMP.
    All this via a Controller servlet, with the database logic handled by a java bean, and all the presentation done via JSP.
    To me this is the most obvious and instructive example of this technology, but after days of trawling the web, and looking through a number of books, I cannot find such a thing.
    CGI with Perl DBI/DBD was a breeze to work with compared to this stuff ..... maybe ASP with SQL/Server would be a more fruitful use of time.

  • JSP - Servlet - Please help

    Hi:
    Can any one suggest me the code for the following scenerio, Am new to jsp-Servlet....
    I need to give an EMPNAME in a Textbox on clicking GO button from my JSP page, a servlet must process thei query and display the output of that employee details back to that JSP page..
    Please help me out with some code snippets...
    Regards,

    The sun's site provides a detailed introduction to JDBC. or
    have to google for JDBC and once you've understood the JDBC concept, then you could progress from there. There is no simple way of doing what you asked.
    You will need a database, though you could use MS Access. But you still need the JDBC.

  • Clean URLs with JSP/Servlet

    Hello. I've found some information on how to setup clean URLs for php, but none for JSP/servlet. Hopefully some one can help. Here's what I mean by 'clean URL':
    http://mydomain/employee.jsp?employeeID=1232
    becomes
    http://mydomain/employee/1232
    And, in that second example, the container would dispatch all requests for /employee* to some JSP/servlet. I don't care if the 'clean URL' has to have an extension or not (e.g. mydomain/employee.jsp/1232) although I would prefer to also remove the JSP extension.
    Additionally (if some one has experience with this need): how do I then access the final part of the URL supplied by the client? In other words, how would 1232 be available to the destination JSP/servlet? Does the container convert it into a parameter, i.e.:
    1) client sends request for "mydomain/employee/1232"
    2) container delegates request to "mydomain/employee.jsp?1232"
    Finally (sorry about the length), I don't have access to top-level config files for this site (it's personal use, although I'm pretty familiar with java APIs from my job), so, ideally, I'd like a .htaccess level solution, where the container can just re-route to a JSP.
    If any one has some suggestions, I'd GREATLY appreciate it. Thanks for your time. Take care.

    ...Just occurred to me- this hosting company is NOT using Tomcat. They use resin.
    Thanks.

  • Java, JSP, Servlet....!!!!????Can you help me?

    Hi all,
    Now I want to use Java (JSP, Bean, Servlet and EJB) for programming (application/web/internet/database). Which architects I should use?
    JSP --> Database.
    JSP --> Beans --> Database.
    Servlet --> Database.
    JSP & Servlet --> Database
    JSP & EJB --> Database...
    Can I use COM/DCOM such as ASP pages?
    And which databases (SQL Server, Oracle, Access, DB...) I should use? Which web servers (Jrun, JWS, Apache, JWS, Orion...)?
    Are there some stuff on Internet relate to this topic (some samples)?
    Thanks so much.

    Hi all,
    Now I want to use Java (JSP, Bean, Servlet and EJB)
    for programming (application/web/internet/database).
    Which architects I should use?you can use the Model-View-Controller or MVC model.
    Model = JavaBeans --> for your business logic/process
    View = JSP --> for your presentation like HTML
    Controller = Servlet --> as your router or dispatcher of the JSPs.
    And which databases (SQL Server, Oracle, Access,
    DB...) I should use? for large business applications that would require security, optimization, etc., i suggest that you go for a good dbase and i'm referring to Oracle, SQL Server, Sybase, Informix, and the likes. But, if you're going to do simple application, MS Access can do the job. Since it comes with MS Office installation, you'll not find it any harder to configure your dbase.
    Which web servers (Jrun, JWS, Apache, JWS, Orion...)?you can use the following apache, IIS, Websphere, etc...
    don't forget that you also need an application server. say, tomcat application server and apache web server.

  • Include new feature where user can get JSP as XML model or normal HTML

    Hi Creator Team,
    I request you guys to include the below specified feature in future updates.
    Currently, creator is supporting to generate JSPS in XML formats. No doubt this is good feature.
    But some times we may require JSP in which we may not in need of well formed HTML page.
    Because all Designeres and developers are may not aware of XML features and nodoubt they will face the problem in coding or designing.
    It is not necessary that a developer/designer need to accustom the features currently supported. He/She may expect more easier access in studio creator.
    I understand that we can include JSPs into project taht are not well formed. But at the same time it is almost difficult to him/her to design the page (drag/drop process which is main feature of Studio Creator)
    I request and suggest to include both options so that it will become easy for developers/designers to use this good product

    Has this feature been incorporated in the latest SJSC 2 release? I too think that this will be more easier to adapt to as a newbie. Moreover, I haven't found anything on this front anywhere else in the forums or in the technical documentations. Other way around could be to provide decent tutorials on using JSP in XML syntax. I am currently using J2EE tutorial (June 2005 release) to learn this technology.
    I would be glad if someone could point out a decent resource on this front.
    Thanks in advance,
    Dev

  • JSP Servlet JDBC connection

    Below is the code for handling login.
    However I am new to servlets, and I am wondering is the code below correct?
    Can anyone give me some advice if it is not correct?
    package gcd;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import com.mysql.jdbc.*;
    public class LoginHandler extends HttpServlet
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    //Load the driver
    Class.forName("com.mysql.jdbc.Driver");
    //Get a connection to the database
    java.sql.Connection connection=java.sql.DriverManager.getConnection("jdbc:mysql://localhost/gcdBB_db");
    //Create a statement object
    java.sql.Statement statement = connection.createStatement();
    Enumeration parameters = request.getParameterNames();
    if(parameters.hasMoreElements())
    // Get the user's account number, and password
    String username = req.getParameter("username");
    String password = req.getParameter("password");
    statement.executeUpdate("INSERT INTO users (username,password) VALUES ('"+username+"','"+password+"')");
    // Check the name and password for validity
    if (!allowUser(username, password))
    out.println("<HTML><HEAD><TITLE>Access Denied</TITLE></HEAD>");
    out.println("<BODY>Your login and password are invalid.<BR>");
    out.println("You may want to <A HREF=\"Login.jsp\">try again</A>");
    out.println("</BODY></HTML>");
    else
    // Valid login. Make a note in the session object.
    HttpSession session = req.getSession();
    session.setAttribute("logon.isDone", account); // just a marker object
    // Try redirecting the client to the page he first tried to access
    try
    String target = (String) session.getAttribute("login.target");
    if (target != null)
    res.sendRedirect(target);
    return;
    catch (Exception ignored) { }
    // Couldn't redirect to the target. Redirect to the site's home page.
    res.sendRedirect("/");
    protected boolean allowUser(String username, String password)
    return true; // trust everyone
    }

    I made the following changes as suggested, to the LoginHandlaer code.
    I also want to ask about the code for ProtectedResources. Do I need to inlude anything in the program. Will I need to include code for the JDBC connection?
    Are the 2 java servlets below correct, as I want JSP-Servlet-JSP operation for login? I can also include the code for Login.jsp if requested?
    PS: I am using Tomcat 3.1 as my server.
    package gcd;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import com.mysql.jdbc.*;
    public class LoginHandler extends HttpServlet
         public void doPost(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
                   response.setContentType("text/jsp");
              PrintWriter out = response.getWriter();
              try
                   //Load the driver
                   Class.forName("com.mysql.jdbc.Driver");
                        //Get a connection to the database
                        java.sql.Connection connection=java.sql.DriverManager.getConnection("jdbc:mysql://localhost/gcdBB_db");
                        //Create a statement object
                        java.sql.Statement statement = connection.createStatement();
                        Enumeration parameters = request.getParameterNames();
                        // Get the user's username, and password
                        String username = request.getParameter("username");
                        String password = request.getParameter("password");
                        statement.executeUpdate("INSERT INTO users (username,password) VALUES ('"+username+"','"+password+"')");
                   // Check the username and password for validity
                   if (!allowUser(username, password))
                        out.println("<HTML><HEAD><TITLE>Access Denied</TITLE></HEAD>");
                        out.println("<BODY>Your login and password are invalid.<BR>");
                        out.println("You may want to <A HREF=\"Login.jsp\">try again</A>");
                        out.println("</BODY></HTML>");
                   else
                        // Valid login. Make a note in the session object.
                        HttpSession session = request.getSession();
                        session.setAttribute("logon.isDone", username); // just a marker object
                        // Try redirecting the client to the page he first tried to access
                        try
                             String target = (String) session.getAttribute("login.target");
                             if (target != null)
                                  response.sendRedirect(target);
                                  return;
                        catch (Exception ignored) { }
                             // Couldn't redirect to the target. Redirect to the site's home page.
                             response.sendRedirect(request.getContextPath() + "http://localhost:8080/jsp/gcdBB");
                   catch (ClassNotFoundException e)
                        out.println("Could not load database driver: " + e.getMessage());
                   catch(SQLException e)
                        out.println("SQLException caught: " + e.getMessage());
         protected boolean allowUser(String username, String password)
              return true; // trust everyone
    package gcd;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import com.mysql.jdbc.*;
    public class ProtectedResources extends HttpServlet
         public void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
              response.setContentType("text/plain");
              PrintWriter out = response.getWriter();
              // Get the session
              HttpSession session = request.getSession();
              // Does the session indicate this user already logged in?
              Object done = session.getAttribute("logon.isDone"); // marker object
              if (done == null)
                   // No logon.isDone means he hasn't logged in.
                   // Save the request URL as the true target and redirect to the login page.
                   session.setAttribute("login.target",
                   HttpUtils.getRequestURL(request).toString());
                   response.sendRedirect(request.getContextPath() + "http://localhost:8080/jsp/gcdBB/Login.jsp");
                   return;
              // If we get here, the user has logged in and can see the bulletin boards
              out.println("The GCD Computing Bulletin Board awaits you!");
    Any help would be greatly appreciated!

  • Sample JSP&Servlet application required?

    hey all
    iam new to jsp&servlets
    i did read some tutorials about the basics
    and i want any link to a tutorial or a project that uses both jsp&servlets
    any help?

    At the risk of sounding really dumb the examples are just too complex. There does not appear to be anywhere on the web where I can find a simple JSP/servlet/bean example of the type I described. There is enouigh material describing each individual component, but what I need is an example to cement the ideas, but the ones suggested are too much for a newbie. Even the much vaunted Pet Store thingy causes my eyes to glaze over.
    I dont expect anyone to have written something with my exact requirements, but surely to goodness there must be something that:
    1. On entry presents a search form on a table (e.g. EMP)
    2. On submission list all rows in EMp matchiung the criteria.
    3. The user can either click the link 'Edit' which opens up a form dispalying the row allowing the user to edit and save the changes, or click the 'New' button to show a blank form to create a new EMP.
    All this via a Controller servlet, with the database logic handled by a java bean, and all the presentation done via JSP.
    To me this is the most obvious and instructive example of this technology, but after days of trawling the web, and looking through a number of books, I cannot find such a thing.
    CGI with Perl DBI/DBD was a breeze to work with compared to this stuff ..... maybe ASP with SQL/Server would be a more fruitful use of time.

  • How can i display data on tha same page in jsp/servlet

    Hello friend,
    I am storing 50 items in a dataBase. i ve two buttons/links name previous and next. i ve to display 10 items each time in the same page when i click next button and the revrese for previous. through JSP/Servlet.
    Any suggestions will be appreciated.
    chintan anand

    I'm not sure this is the best practice... try to add the item in the arraylist, then when u click next button, add 10 to the counter. subtract if it is a previous button. thats it!
    ex..
    for(int x=counter;x<=arraylist.lenght();x++)
    ....print item here......
    }

  • Using JSP/Servlet to write Word Document to BLOB

    Hi
    I need some help pls
    When I use a normal class with a main method, it loads the word document into a blob and I can read this 100%.Stunning.
    With a JSP/Servlet I cannot get the document out again. The "format" seems to be lost.
    Any ideas,help greatly appreciated:
    Here is the Main class that works:
    package mypackage1;
    import java.io.OutputStream;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.PrintWriter;
    import java.io.IOException;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileReader;
    import java.io.FileNotFoundException;
    import java.io.Writer;
    import java.sql.Connection;
    import oracle.jdbc.*;
    import oracle.jdbc.OracleResultSet;
    import oracle.sql.BLOB;
    import org.apache.log4j.Logger;
    import Util_Connect.DataBase;
    public class TestLOB
    //static final Logger logger = Logger.getLogger("test");
    public TestLOB()
    public static void main(String args[])
    TestLOB testLOB = new TestLOB();
    testLOB.TestLOBInsert("c:\\my_data\\callcenterpilot.doc");
    public void TestLOBInsert(String fileName)
    Connection conn = getConnection("wizard");
    BLOB blob = null;
    try
    conn.setAutoCommit(false);
    String cmd = "SELECT * FROM so_cs.testlob WHERE docno = 1 FOR UPDATE";
    PreparedStatement pstmt = conn.prepareStatement(cmd);
    ResultSet rset = pstmt.executeQuery(cmd);
    rset.next();
    blob = ((OracleResultSet)rset).getBLOB(2);
    File binaryFile = new File(fileName);
    System.out.println("Document length = " + binaryFile.length());
    FileInputStream instream = new FileInputStream(binaryFile);
    OutputStream outstream = blob.getBinaryOutputStream();
    int size = blob.getBufferSize();
    byte[] buffer = new byte[size];
    int length = -1;
    while ((length = instream.read(buffer)) != -1)
    outstream.write(buffer, 0, length);
    instream.close();
    outstream.close();
    conn.commit();
    closeConnection(conn);
    catch (Exception ex)
    System.out.println("Error =- > "+ex.toString());
    private Connection getConnection(String dataBase)
    Connection conn = null;
    try
    DriverManager.registerDriver(new OracleDriver());
    conn = DriverManager.getConnection("jdbc:oracle:thin:@oraclu5:1600:dwz110","so_cs","so_cs");
    catch (Exception ex)
    System.out.println("Error getting conn"+ex.toString());
    return conn;
    private void closeConnection(Connection conn)
    if (conn != null)
    try
    conn.close();
    catch (Exception se)
    System.out.println("Error closing connection in get last imei"+se.toString());
    Works fine:
    Here is the display servlet: Works when main class inserts file
    package mypackage1;
    import java.io.InputStream;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.PrintWriter;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileReader;
    import java.io.FileNotFoundException;
    import java.io.Writer;
    import java.sql.Connection;
    import oracle.jdbc.*;
    import oracle.jdbc.OracleResultSet;
    import oracle.sql.BLOB;
    import org.apache.log4j.Logger;
    import Util_Connect.DataBase;
    public class DisplayLOB extends HttpServlet
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
    static final Logger logger = Logger.getLogger(DisplayLOB.class);
    public void init(ServletConfig config) throws ServletException
    super.init(config);
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    //response.setContentType(CONTENT_TYPE);
    //PrintWriter out = response.getWriter();
    Connection conn = null;
    PreparedStatement pstmt = null;
    try
    conn = getConnection("wizard");
    //out.println("<html>");
    //out.println("<head><title>DisplayLOB</title></head>");
    //out.println("<body>");
    //out.println("<p>The servlet has received a POST. This is the reply.</p>");
    InputStream is=null;
    oracle.sql.BLOB blob=null;
    response.setContentType("application/msword");
    //response.setContentType("audio/mpeg");
    OutputStream os = response.getOutputStream();
    String term = "1";
    String query = "SELECT docdetail FROM testlob WHERE docno = 1";
    pstmt = conn.prepareStatement(query);
    ResultSet rs = pstmt.executeQuery();
    while (rs.next())
    blob=((OracleResultSet)rs).getBLOB(1);
    is=blob.getBinaryStream();
    int pos=0;
    int length=0;
    byte[] b = new byte[blob.getChunkSize()];
    while((length=is.read(b))!= -1)
    pos+=length;
    os.write(b);
    }//try
    catch (Exception se)
    se.printStackTrace();
    finally
    try
    pstmt.close();
    catch (Exception ex)
    System.out.println("Error closing pstmt "+ex.toString());
    //out.println("</body></html>");
    //out.close();
    private Connection getConnection(String dataBase)
    Connection conn = null;
    try
    conn = DataBase.getPoolConnection(dataBase);
    catch (Exception se)
    logger.fatal("Error getting connection: ",se);
    return conn;
    private void closeConnection(Connection conn)
    if (conn != null)
    try
    conn.close();
    catch (Exception se)
    logger.error("Error closing connection in get last imei",se);
    Here is JSP/Servlet
    <%@ page import="org.apache.log4j.*"%>
    <%@ page contentType="text/html; charset=ISO-8859-1" %>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>untitled</title>
    <title>Wizard SMS Interface</title>
    <link rel='stylesheet' type='text/css' href='main1.css'>
    <script language='JavaScript' src='copyright.js'></script>
    </head>
    <pre>
    <%
    //HTTP 1.1
    response.setHeader("Cache-Control","no-cache");
    //HTTP 1.0
    response.setHeader("Pragma","no-cache");
    //prevents caching at the proxy server
    response.setDateHeader ("Expires", 0);
    Logger logger = Logger.getLogger("co.za.mtn.wizard.administration.admin01.jsp");
    %>
    </pre>
    <body>
    <FORM ACTION="/WizardAdministration/uploadfile"
    METHOD="POST"
    ENCTYPE="multipart/form-data">
    <INPUT TYPE="FILE" NAME="example">
    <INPUT TYPE="SUBMIT" NAME="button" VALUE="Upload">
    </FORM>
    </body>
    </html>
    <font> <b>Copyright &copy;
    <script>
    var LMDate = new Date( document.lastModified );
    year = LMDate.getYear();
    document.write(display(year));
    </script>
    Mobile Telephone Networks.
    <p align="left"><i><b><font face="Georgia, Times New Roman, Times, serif" size="1"></font></b></i></p>
    package co.za.mtn.wizard.admin;
    import java.io.InputStream;
    import java.util.Enumeration;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.PrintWriter;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileReader;
    import java.io.FileNotFoundException;
    import java.io.Writer;
    import java.sql.Connection;
    import oracle.jdbc.OracleResultSet;
    import oracle.sql.BLOB;
    import org.apache.log4j.Logger;
    import Util_Connect.DataBase;
    public class UploadFile extends HttpServlet
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
    //static final Logger logger = Logger.getLogger(UploadFile.class);
    public void init(ServletConfig config) throws ServletException
    super.init(config);
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    String headerName = null;
    Enumeration en = request.getHeaderNames();
    try
    while ( en.hasMoreElements() )
    Object ob = en.nextElement();
    headerName = ob.toString();
    System.out.println("Value for headerNAme is >"+headerName+"<");
    String aaa = request.getHeader(headerName);
    System.out.println("Value for aa is >"+aaa+"<");
    catch (Exception ex)
    System.out.println("Error in extracting request headers"+ex.toString());
    Connection conn = getConnection("wizard");
    BLOB blob = null;
    try
    conn.setAutoCommit(false);
    String cmd = "SELECT * FROM so_cs.testlob WHERE docno = 1 FOR UPDATE";
    PreparedStatement pstmt = conn.prepareStatement(cmd);
    ResultSet rset = pstmt.executeQuery(cmd);
    rset.next();
    blob = ((OracleResultSet)rset).getBLOB(2);
    //File binaryFile = new File("h:\\callcenterpilot.doc");
    //System.out.println("Document length = " + binaryFile.length());
    //FileInputStream instream = new FileInputStream(binaryFile);
    response.setHeader("Content-Type","application/vnd.ms-word");
    String contentType = request.getContentType();
    System.out.println("Content type received in servlet is >"+contentType+"<");
    ServletInputStream instream = request.getInputStream();
    OutputStream outstream = blob.getBinaryOutputStream();
    int size = blob.getBufferSize();
    byte[] buffer = new byte[size];
    int length = -1;
    while ((length = instream.read(buffer)) != -1)
    outstream.write(buffer, 0, length);
    instream.close();
    outstream.close();
    conn.commit();
    closeConnection(conn);
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    catch (Exception ex)
    System.out.println("Error =- > "+ex.toString());
    //out.println("</body></html>");
    //out.close();
    private Connection getConnection(String dataBase)
    Connection conn = null;
    try
    conn = DataBase.getPoolConnection(dataBase);
    catch (Exception se)
    System.err.println("Error getting connection: "+se.toString());
    return conn;
    private void closeConnection(Connection conn)
    if (conn != null)
    try
    conn.close();
    catch (Exception se)
    System.err.println("Error closing connection in get last imei"+se.toString());
    This is what the display servlet is showing when the JSP/Servlet insert the document
    -----------------------------7d31422224030e
    Content-Disposition: form-data; name="example"; filename="H:\(your name) Skills Matrix.doc"
    Content-Type: application/msword
    �� ࡱ � > ��     � � ���� � � ���������������������
    Tks
    Andre

    hello,
    there are multiple documents out there, describing the oracle reports server setup. try doc.oracle.com for documentation.
    also it is part of the online-documentation.
    you need to install 9iAS enterprise edition. the server is pre-configured and will listen to the url http://yourserver/dev60cgi/rwcgi60.exe
    passing only this url you will get a help-screen, describing the syntax.
    regards,
    the oracle reports team

Maybe you are looking for

  • Is it possible to use Jdeveloper with Other Sql Server using JDBC-ODBC bri

    I have been able to successfully establish connection with Sql server Using JDBC-ODBC bridge, but when i run the application and perform some operations such as insert the following errors occur: (oracle.jbo.SQLStmtException) JBO-27122: SQL error dur

  • Msi Vga Bios Downloads

    http://www.mvktech.net/download.php this is a listing of many manufacturers vga bios' if this has been posted before....please excuse me!

  • I have old Adobe AI 10 and Photoshop etc... Upgrade?

    I have old Adobe AI 10 and Photoshop etc... Getting a new Mac, can I get a discount or upgrade on the purchase/upgrade of my software?

  • How to make pages a graphics layout program

    In the earlier version og Pages, you used to beable to choos wheater you wanted to use the program as a wordprosesser or a graphics layout program. How do you make this desigation in the new version of Pages.

  • Extended Receiver & Extended  Interface Determination

    Hi Experts, Can any tell me what is Extended Receiver & Extended  Interface Determination. And the Difference between Standard Receiver & Standard Interface Determination. were to use Extended Receiver & Extended  Interface Determination. Thanks in a