XML,servlets and websphere?

I am working on a project that is using websphere 3.5 as the application server, from a login page I call a servlet (SiteController) what I want to do is read in system specific values (such as jsp file address, database connectivity info, etc) from an XML file. Can anyone tell me what I should be doing to achieve this, please!!!!!

There are a number of options;
1. Use a DOM parser e.g. Xerces (http://xml.apache.org/xerces2-j/index.html) and figure out how to traverse to the info you kneed.
2. Use Castor XML (http://castor.exolab.org/) to build a set of Java classes (need a schema for your config file) which are much easier to manipulate in java. Though this requires you to re-build the classes if the schema changes. You still need a parser - Castor by default requires Xerces.
3. Event better might be to use Struts (http://jakarta.apache.org/struts/index.html) which has its own config file which supports jsp/JDBC connections etc, It also has a 'SiteController' servlet called ActionServlet which acts as the control point for the whole application.
I'm currently using a mixture of 2 & 3 for a WAS4 prototype.
There are white papers and tutorials on 2 & 3 on the IBM web site (Developer Works).
http://www-106.ibm.com/developerworks/library/x-bindcastor/index.html
http://www-106.ibm.com/developerworks/library/j-strutstiles.html
http://www-106.ibm.com/developerworks/library/j-struts/index.html
amongst others.
HH

Similar Messages

  • 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.

  • Extending EP6 with own Servlet and URL /irj/MyServlet

    Hello,
    I am working on a migration of a Servlet from IBM WebSphere Portal 5.0 to SAP EP6.0. The Servlet is an extension to the Portal and is manually deployd and not with an ear or war file.
    Is it possible to extend the portal with my own servlet accessible with "/irj/MyServlet"?
    I tried to copy the jars to one of the directories
    server0\apps\sap.com\irj\servlet_jsp\irj\root\WEB-INF\lib
    server0\apps\sap.com\irj\servlet_jsp\irj\root\WEB-INF\portal\lib
    server0\apps\sap.com\irj\servlet_jsp\irj\root\WEB-INF\portal\system\lib
    and added my Servlet to the web deployment descripter
    server0\apps\sap.com\irj\servlet_jsp\irj\root\WEB-INF\web.xml
         <servlet>
              <servlet-name>MyServlet</servlet-name>
              <display-name>MyServlet</display-name>
              <servlet-class>com.mycompany.MyServlet</servlet-class>
              <init-param>
                   <param-name>ServletMode</param-name>
                   <param-value>normal</param-value>
              </init-param>
            <load-on-startup>1</load-on-startup>
         </servlet>
          <servlet-mapping>
             <servlet-name>MyServlet</servlet-name>
             <url-pattern>/MyServlet/*</url-pattern>
          </servlet-mapping>
    I also tried to modify the jar file in the same manner
    server0\apps\sap.com\irj\servlet_jsp\irj\epbc.war
    All this does not work.
    Does somebody has experience with extending the SAP EP6 portal?
    Greetings, Bernd.

    Maybe its  possible, but it is not recommended to do so.
    However it does not make to much sense.
    Just run your servlet as a portal compoent with an entry as native-Servlet in the pc descriptor.
    Thats a 5 minute trip.

  • Servlets in Websphere - Please help!!!

    Can anybody please tell me this info
    * Where exactly does Websphere start looking for servlet when url is typed and webpage requested.
    * Any info you know about logs, error logs etc - where should I look for them in Websphere
    * What kind of steps should be taken care of when upgrading Websphere
    * Any book/ website u know that can tell me info about the above things - I just want more info/some basic info about internal stuff in Websphere - not what I see on the console.
    Thanks in Advance.

    * this is like with all J2EE compliant application servers defined in the web.xml. In that file, you define your servlets and a servlet mapping. This servlet mapping is the link between the URL-type and the servlet; eg:
    <web-app id="WebApp_1">
    <display-name>Example</display-name>
    <description>Example servlet</description>
    <servlet id="servletmapping">
    <servlet-name>servletmapping</servlet-name>
    <servlet-class>com.something.MyServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping id="examplemapping">
    <servlet-name>servletmapping</servlet-name>
    <url-pattern>*.myservlet</url-pattern>
    </servlet-mapping>
    </web-app>
    * all logs are located in the ../Webspeher/AppServer/logs folder
    * Upgrading websphere from?
    * It speeks a bit for itself, the best website for this is www.ibm.com/websphere (you can also find some good docs for making j2ee applications using websphere on that url)

  • Form Authentication Servlet  and MD5

    Dear forum,
    I have the following servlet to authenticate a user via form. If you go to the root url you get the login html and the authentication works fine but if the user knows the url of a specific html just by typing the url gives access to the page without going through the authentication. The website is composed of htmls and servlets. How can I force the authentication for the htmls and the servlets. I included at the bottom how I added the Login servlet to the web.xml. I suspect that the servlet definition in the web.xml is the problem.
    Also I would like to use MD5 encryption, would someone suggest how this can be accomplished.
    Thanks.
    This is the code:
    import java.io.*;
    import java.util.*;
    import javax.servlet.http.*;
    import javax.servlet.*;
    import java.sql.*;
    import javax.sql.*;
    public class LoginServlet extends HttpServlet {
      public void doPost (
         HttpServletRequest     request,
         HttpServletResponse     response
        ) throws ServletException, IOException
      String item = request.getParameter("account");  
      doGet(request,response);
      public void doGet (
         HttpServletRequest     request,
         HttpServletResponse     response
        ) throws ServletException, IOException
       HttpSession session = request.getSession(true);
       PrintWriter out = response.getWriter();
         try {
              String driverName="sun.jdbc.odbc.JdbcOdbcDriver";
              String dbUrl="jdbc:odbc:Virtual_Library_DB";
              Class.forName(driverName);
              Connection db =DriverManager.getConnection(dbUrl,"","");
              if ((session.getAttribute("user") == null) || (!session.getAttribute("ip").equals(request.getRemoteAddr()))){
                   PreparedStatement pStmt = db.prepareStatement("SELECT * FROM Login WHERE Login.account =? AND Login.password=? ");
                   pStmt.setString(1, request.getParameter("account"));
                   pStmt.setString(2, request.getParameter("password"));
                            pStmt.setString(3, request.getParameter("level"));
                   ResultSet rs = pStmt.executeQuery();
                    System.out.println("hello");
                   if(!rs.next()){
                        System.out.println("Account is not valid.");
                        request.setAttribute("msg", "Account is not valid.");
                        RequestDispatcher rd = request.getRequestDispatcher("LoginInvalid.html");
                        rd.forward(request, response);
                   else do {
                        int id = rs.getInt(1);
                        String account = rs.getString(2);
                        session.setAttribute("user", new Integer(id));
                        session.setAttribute("account", account);
                        session.setAttribute("ip", request.getRemoteAddr());
                        System.out.println("User " + session.getAttribute("user") +" has logged on.");
                        request.setAttribute("msg", "User has logged on.");
                        RequestDispatcher rd = request.getRequestDispatcher("index.html");
                        rd.forward(request, response);
                   } while(rs.next());
                   rs.close();
              else {
                   System.out.println("User has already logged on.");
                        request.setAttribute("msg", "User has already logged on.");
                        RequestDispatcher rd = request.getRequestDispatcher("index.html");
                        rd.forward(request, response);
              db.close();
         catch(Exception exp){
              System.out.println("Exception: "+ exp);
       out.close();
    web.xml
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>LoginServlet</servlet-class>
      </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
      </servlet-mapping>

    Check the session in the servlets that are allowed only for logged-in users.
    public class ServletUtils
        public static boolean checkLogin(HttpServletRequest request, HttpServletResponse response)
            HttpSession session = request.getSession(false); // false = don't create a new session if not logged in
            if (session != null)
                return true;
            Logging.log("tried to access page without login, redirecting to login");
            ...redirect to login.html...
            return false;
        // At the start of your doGet()'s:
        if (!checkLogin(request, response))
            return;Do you really need static documents to be authenticated? dot.gif's and all? Someone can make a zip file of them anyway and post it to their own web site or Kazaa.
    If you have a couple of html pages you want authenticated, easiest is to write them as servlets (+ maybe JSP's) and do the login check there.
    Ok, let's say you have ...what, an "image database" (heh) that you want available to logged-in users only. Write a servlet that serves those pages. That servlet checks the session, and then copies the appropriate file to the user (remember to set content type; consider caching the files if hit rate is very high.) The servlet would be called like /images/show?id=gerbilsex/closeup.gif to fetch the named file. Put the files outside the web server's document directory so they are not accessible except through the servlet. Perform strict checks on the file name to disallow nastiness like id=../../../etc/passwd. A similar database solution is also possible. Another variant is to map a servlet to a "virtual directory name" and get the actual file name from the URL path -- similar to the ?id= solution, except the URLs don't have parameters.
    About md5: md5 isn't an encryption algorithm, it is a hash algorithm (aka "message digest" or "fingerprint"). It can't be decrypted. What do you really want to accomplish - encryption or hashing?

  • Crystal Report 9.0 and Websphere

    hi can any body give me some steps regarding
    integration of crystal report and websphere
    i have already search this forum and i got lot many topics
    regarding this but all were using cyrstal report version 8 and 8.5
    which requires mandatory using IIS server which i dont wont to use
    i want a pure websphere and 9.0 version communication
    i had read the docs whihc states that 9.0 supports but i dont know how?
    can any bosy help regarding this

    here's the report code
    <%@ page contentType="text/html; charset=utf-8" %>
    <%@ page session="true"%>
    <%@ page import="javax.servlet.jsp.*"%>
    <%@ page import="java.util.Locale"%>
    <%@ page import="java.net.*" %>
    <%@ page import="java.text.DateFormat" %>
    <%@ page import="javax.servlet.jsp.JspWriter"%>
    <%@ page import="javax.servlet.http.HttpServletRequest" %>
    <%@ page import="javax.servlet.http.HttpSession" %>
    <%@ page import="com.crystaldecisions.sdk.occa.report.data.*" %>
    <%@ page import="com.crystaldecisions.sdk.occa.report.application.*" %>
    <%@ page import="com.crystaldecisions.report.web.viewer.*" %>
    <%@ page import="com.crystaldecisions.sdk.occa.report.exportoptions.*" %>
    <%@ page import="com.crystaldecisions.sdk.occa.report.definition.*" %>
    <!--Code Starts here ........... -->
    <%
    System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$");
    String reportName=(String)request.getAttribute("ReportName");
    String requestNumber=(String)request.getAttribute("RequestNumber");
    String requestNumber="RPT_112";
    System.out.println("********************");
    ParameterField newParameter = new ParameterField();
    ParameterField newField = null;
    System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@");
    ParameterFieldDiscreteValue newValue = null;
    System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^");
    try{
    ReportClientDocument rptClientDoc = new ReportClientDocument();
    //System.out.println("11111111111111111111111111");
    /* Change DCWKS0241AB to the name of Machine where RAS is installed for ex like DCWKS0237 */
    rptClientDoc.setReportAppServer("DCWKS0241AB");
    System.out.println("22222222222222222222222222");
    /* Change this E:\\Crystal\\Reports\\ to the path where your reports are kept */
    String reportPath="E:\\RAS\\Reports\\Percentages.rpt";
    rptClientDoc.open (reportPath, 0);
    rptClientDoc.getDatabaseController().logon("bbva","bbva");
    System.out.println("After Creating the Client Document on the Report");
    /* folowing Code remove any default value to the report and append the request number in the input parameter*/
    newField = (ParameterField)rptClientDoc.getDataDefinition().getParameterFields().getField(0);
    newField.copyTo(newParameter,true);
    newParameter.getCurrentValues().removeAllElements();
    newValue=new ParameterFieldDiscreteValue();
    newValue.setValue(requestNumber);
    newParameter.getCurrentValues().add(newValue);
    /* Just for Testing Purpose
    Values v=newParameter.getCurrentValues();
    IValue iv=v.getValue(0);
    System.out.println("---> "+iv.computeText());
    rptClientDoc.getDataDefController().getParameterFieldController().modify(newField, newParameter);
    /* Specifying the Format */
    PDFExportFormatOptions PDFExpOpts = new PDFExportFormatOptions();
    //Create the ExportOptions object, set the PDF export options, and set the format type to PDF.
    ExportOptions exOpts = new ExportOptions();
    exOpts.setFormatOptions(PDFExpOpts);
    exOpts.setExportFormatType(ReportExportFormat.from_int(ReportExportFormat._PDF));
    System.out.println("After Setting the format");
    System.out.println("Before getting source");
    //Create the ReportExportControl object and set the report source to the report that will be exported to PDF.
    ReportExportControl expViewer = new ReportExportControl();
    System.out.println("Before getting source");
    expViewer.setReportSource (rptClientDoc.getReportSource());
    System.out.println("3");
    //Set the export options to the ReportExportControl object.
    expViewer.setExportOptions(exOpts);
    System.out.println("After Setting the Export Options to the ReportExportControl object.");
    //Set the exported report to display in the browser.
    //The setExportAsAttachment method is set to false by default. If it is set to true the user will be presented with the File Download dialog box to save the exported report to disk.
    expViewer.setExportAsAttachment(false);
    //Export and view the report.
    expViewer.processHttpRequest(request, response, (getServletConfig()).getServletContext(),null);
    System.out.println("After Exporting and viewing the report back in the Browser.");
    //Destroy the control.
    expViewer.dispose();
    catch (Exception e)
    out.write("Error: Open" + e.toString() + "\n");
    %>

  • How can I have a default servlet and an index.html?

    Hi,
    I writing a small webapp to test/understand the 2.2 Servlet Spec. I am deploying this as a WAR to Orion, Tomcat and Silverstream.
    The app's name is: "myapp"
    My application has an index.html, which is listed as the sole welcome-file in the welcome-file-list element in the app's web.xml.
    The interesting thing is that, after adding a default Servlet (<url-pattern>/</url-pattern>), I can no longer access the app's index.html either implicitly or explicitly:
    1. Implicit:
    - http://localhost/myapp
    - http://localhost/myapp/
    2. Explicit:
    - http://localhost/myapp/index.html
    - http://localhost/myapp/index.html/
    All of these invoke the Default Servlet in all 3 app servers.
    Question: How can I have both a default Servlet and an index page?
    Thanks in advance.
    Miles

    you can define it in the web.xml file
    look at the dtd, element "welcome-file-list"

  • Directory structure for servlets and webservices in one application

    hi,
    Can any one help me for creating servlets and webservices in one
    application and deploying in Jboss 4.2.0.
    I want to know exactly what is the directory structure for creating this
    application and what are the additional .xml files for deploying this application.
    if any one know this answere please tell the answere.

    I figured out a solution - it's a problem of policies. In detail: Server1's codebase entry (file:) refers to the class directory of Server1's project. In the simple case of only Client1, which has no codebase entry, it works fine without a file permission on the side of Server1. In the complex case of Client1+Server2, which has to have a codebase entry (file:) refering to the class directory of the Server2's project on a separate machine, for exactly the same method call from Client1 to Server1 a file permission entry on the side of Server1 is needed for Server1's class directory. But WHY ???
    It seems to be a little confusing with the codebase entries, many of the posts are contrary to others and to my personal experiences. Some comments given by Adrian Colley throw a little light upon some aspects. Is there anybody, who can explain the whole topic, when, why, and which part of RMI application deals with codebase entries, also in case of not dynamic code downloading ? May be there is also a reference into the java docs, which I didn't found up to now.
    Thanks in advance
    Axel

  • Help With Integrating Servlet and JSP Page?

    Hello There
    --i made jsp page that contain name and description fields and add button
    --and i made servlet that contain the code to insert name and description in the database
    --and i want to make that when the user hit the add button
    -->the entered name and description is sent to the servlet
    and the servlet sent them to database?
    here's what i 've done:
    the jsp code:
    <html:html locale="true">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>
            Categories Page
           </title>
            <html:base/>
        </head>
        <body style="background-color: white">
        <form action="jpage.jsp" method="get">
            <h1>
                <center>
    categories Operations
                </center>
            </h1>
            <h3>
                 <label>Name</label>
            <input type="text" name="name" value="" size="10" />
                 <label>Description</label>
             <input type="text" name="description" value="" size="10" />
             <input type="submit" value="Add" name="button" />
           </h3>
       </form>
        </body>
    </html:html>the servlet code:
    import java.io.*;
    import java.util.Enumeration;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.net.*;
    class NewServlet1 extends HttpServlet{
         Connection conn;
         private ServletConfig config;
    public void init(ServletConfig config)
      throws ServletException{
         this.config=config;
    public void service (HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
       HttpSession session = req.getSession(true);
       res.setContentType("text/html");
    try{
         Class.forName("com.mysql.jdbc.Driver");
       conn = DriverManager.getConnection("jdbc:mysql://localhost/struts", "root", "");
         PreparedStatement ps;
       ps = conn.prepareStatement ("INSERT INTO categories (Name, Description) VALUES(?,?)");
          ps.setString (1, "aa");
          ps.setString (3, "bb");
          ps.executeUpdate();
          ps.close();
          conn.close();
      }catch(Exception e){ e.getMessage();}
      public void destroy(){}
    }

    The JSP Code:
    <html:html locale="true">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>
            Categories Page
           </title>
            <html:base/>
        </head>
        <body style="background-color: white">
        <form action="actionServlet.do?action=Additem" method="*post*">
            <h1>
                <center>
    categories Operations
                </center>
            </h1>
            <h3>
                 <label>Name</label>
            <input type="text" name="name" value="" size="10" />
                 <label>Description</label>
             <input type="text" name="description" value="" size="10" />
             <input type="button" value="Submit">
           </h3>
       </form>
        </body>
    </html:html>The Servlet Code:
    import java.io.*;
    import java.util.Enumeration;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.net.*;
    public class NewServlet1 extends HttpServlet implements SingleThreadModel {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {
            doPost(request,response);
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {
              String action = request.getParameter("action"); // action = "Additem"
              if (action.equals("Additem")) {
                   String name = request.getParameter("name");
                   String description = request.getParameter("description");
                         RequestDispatcher reqDisp = null;
                   try{
                  Connection conn;
                  PreparedStatement ps;
         Class.forName("com.mysql.jdbc.Driver");
       conn = DriverManager.getConnection("jdbc:mysql://localhost/struts", "root", "");
       ps = conn.prepareStatement ("INSERT INTO categories (Name, Description) VALUES(?,?)");
          ps.setString (1, name);
          ps.setString (3, description);
          ps.executeUpdate();
          ps.close();
          conn.close();
          reqDisp= request.getRequestDispatcher("./index.jsp");
          reqDisp.forward(request, response);
                   catch (Exception ex){
                        System.out.println("Error: "+ ex);
    }The web.xml code:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
        <servlet>
            <servlet-name>action</servlet-name>
            <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
            <init-param>
                <param-name>config</param-name>
                <param-value>/WEB-INF/struts-config.xml</param-value>
            </init-param>
            <init-param>
                <param-name>debug</param-name>
                <param-value>2</param-value>
            </init-param>
            <init-param>
                <param-name>detail</param-name>
                <param-value>2</param-value>
            </init-param>
            <load-on-startup>2</load-on-startup>
            </servlet>
        <servlet>
            <servlet-name>NewServlet1</servlet-name>
            <servlet-class>NewServlet1</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>action</servlet-name>
            <url-pattern>*.do</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>NewServlet1</servlet-name>
            <url-pattern>/NewServlet1</url-pattern>
        </servlet-mapping>
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
            </welcome-file-list>
            <servlet>
         <servlet-name>actionServlet</servlet-name>
         <servlet-class>com.test.servlet.NewServlet1</servlet-class>
    </servlet>
    <servlet-mapping>
         <servlet-name>actionServlet</servlet-name>
         <url-pattern>*.do</url-pattern>
    </servlet-mapping>
        </web-app>

  • Servlets and Application Beans

    Hi I'm reviewing some sample code that was originally done as a JSF application. I however will not be doing a JSF application but rather a simple Model 2 architecture using servlets. I'm trying to confirm what the equivalent to an application managed and session beans in JSF would be in a servlet environment. For example the following xml in a JSF app...
    - <managed-bean>
    <managed-bean-name>jpaResourceBean</managed-bean-name>
    <managed-bean-class>oracle.toplink.jpa.example.inventory.services.impl.JPAResourceBean</managed-bean-class>
    <managed-bean-scope>application</managed-bean-scope>
    </managed-bean>
    - <managed-bean>
    <managed-bean-name>inventoryService</managed-bean-name>
    <managed-bean-class>oracle.toplink.jpa.example.inventory.services.impl.ManagedInventoryBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    - <managed-property>
    <property-name>jpaResourceBean</property-name>
    <value>#{jpaResourceBean}</value>
    </managed-propert
    Would that simple be using the servlet context and session variables? Any other tips on the right way to do this?
    Thanks

    fsa3 wrote:
    I'm trying to confirm what the equivalent to an application managed and session beans in JSF would be in a servlet environment.JSF application scoped beans are stored as ServletContext attributes and JSF session scoped beans are stored as HttpSession attributes. So do the same in a servlet and you're fine.

  • JNI and Websphere 3.5

    Hi there,
    I have an application that makes use of JNI technology.
    Basically, so as to work, the app must access a C++ DLL library via JNI, that in my case is a set of classes packaged in a jar file.
    The app works just fine when is run locally, but I?m really in trouble to set up WebSphere properly so that I can web access the app with servlet and jsp.
    I haven?t been succesful getting consistent info anywhere.
    Could anybody give me detailed instructions on how to do that?
    IBM instructions lack further details, they just don?t help, they?re made for experts!
    Thanks!

    I have solved the previous problem, and fallen into another.
    Now this is quite a wierd one. Basically, as the servlet is run from the browser, the servlet calls the business classes. The business classes use other java classes that have native methods to call a DLL library.
    A have put the JNI java classes in the websphere class path, not in the web app classpath, as descrived in the IBM redbooks, and I also created the 'path' variable from the web project in WebSphere in reference to the DLL.
    When I go to the browser and call the servlet, the app works, once I get all the info on the jsp that came from the DLL. Now, if any other call is done through the web browser, the dll is no more instantiated!
    Neither from the same machine nor from anywhere else!
    Has anybody ever seen such a thing?
    I just don?t know what else to do, and have not found any more instructions.
    Please, any info on it is very much welcome.
    Thanks a lot.

  • Read  an XML file and send it to client

    Hi,
    I'm introducing to servlet development and I'm trying to do some AJAX calls. The client side is implemented, but I have some troubles on the server side. I want to open an XML file and send it to the client. How can I do that? Any special header?
    I have implemented this test in PHP, so you can imagine what I would like to do:
    if ($type == "xml"){
         $xml = "";
         $file = fopen ("file.xml", "r");
         while (!feof ($file)){
              $xml .= fgets ($file, 4096);
         fclose ($file);
         header ("Content-type: text/xml; charset=ISO-8859-1");
         echo $xml;
    }The XML file is:
    <?xml version='1.0' encoding='ISO-8859-1'?>
    <users>
         <user>
              <name>Pepe</name>
              <age>18</age>
         </user>
         <user>
              <name>María</name>
              <age>21</age>
         </user>
    </users>Thanks.

    Not very useful:(.
    This is my code:
    PrintWriter out = null;
            try{
                   String type = request.getParameter ("type");
                   if (type.equals ("xml")){
                        response.setContentType ("text/xml; charset=ISO-8859-1");
                        out = response.getWriter ();
                        String xml =
                             "<?xml version='1.0' encoding='ISO-8859-1'?>" +
                             "<users>" +
                                  "<user>" +
                                       "<name>Pepe</name>" +
                                       "<age>18</age>" +
                                  "</user>" +
                                  "<user>" +
                                       "<name>María</name>" +
                                       "<age>21</age>" +
                                  "</user>" +
                             "</users>";
                        out.println (xml);
            }finally{
                out.close ();
            }This code works. The servlet send back the xml and the client shows the content but, as you can see, i'm not reading the xml file. So my problem is on reading the xml file as a plain text. My code is this:
    response.setContentType ("text/xml; charset=ISO-8859-1");
                        out = response.getWriter ();
                        String xml = "";
                        FileReader fr = null;
                        BufferedReader br = null;
                        try{
                             fr = new FileReader (new File ("file.xml"));
                             br = new BufferedReader (fr);
                             String linea;
                             while ((linea = br.readLine ()) != null){
                                  xml += linea;
                                  //System.out.println (linea);
                             fr.close ();
                        }catch (Exception e){
                             e.printStackTrace ();
                        }But now I get an Exception File not found. The xml file is in the web directory (I'm using net beans 6.8). Where I have to put the file?
    Thanks.
    Edited by: GagleKas on Mar 15, 2010 6:39 AM

  • Questions about Java Servlets and JSP

    Hi,
    I'm a confident Java Programmer (and really enjoy using this language) but am very new to Java servlets and Java Server Pages.
    I have previously worked with Perl on my web projects (simple 'league' style voting pages). I read in my 'Core Java' book that I should no longer use perl or even cgi.
    I need to know more about Java servlets and Java Server Pages so I can make the switch to a 'real' programming language.
    I have a few questions:
    How should I start to learn JS and JSP?
    How applicable will the java knowlegdge I have already be?
    Are JSP common on the world wide web?
    What tools do I need to start? (I currently develop in JBuilder and have Java 1.4.1 Standard Edition)
    Is it likey my web host (and others) will support JSP?
    Thank-you very much for helping a novice get started,
    Regards,
    Paul

    Hi, Steve ...has to be frustrating! But do not despair.
    Let's suppose the servlet it's named MyServlet on package org.servlets
    WEB-INF should look:
    WEB-INF
    classes
    org
    servlets
    MyServlet.class
    web.xml
    web.xml file should have this two declarations:
    <web-app>
      <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>org.servlets.MyServlet</servlet-class>
      </servlet>
      <!-- other servlets -->
      <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/MyServlet</url-pattern>
      </servlet-mapping>
      <!-- other servlets mappings -->
    </web-app>Now, once the container starts (Tomcat?), you should be able to see that servlet in:
    http://localhost:8080/[my-context/]MyServletAnd what my-context is? The web application context. This string should be empty if your're deploying to the root context, otherwise should the context name. In Tomcat, deploying to root context defaults to using webapps/ROOT.
    Sorry for my English, but I felt the need to answer your request. I hope it helps despite my writing.

  • Servlets and Workspaces

    I have a named workspace which is created at startup of the server
              within a starup class.
              When the startup method is called, I instantiate and put an object
              called FooObject in the workspace.
              Then, in a servlet, called Dispatcher, in the service method, I
              retrieved my named workspace and the object
              FooObject which is in this workspace. At this time, I have a
              ClassCastException.
              To give you more details about my configuration, here is my directory
              configuration:
              weblogic
              |----------- serverclasses
              |------------- startupObject
              |------------- FooObject
              |----------- servletclasses
              |------------- myServlet
              |------------- FooObject (which is exactly
              the same of the serverclasses one)
              Do you have any ideas ? The idea is to instantiate a given object at the
              startup of the web server and to retrieve
              these objects within servlets and JSPs.
              Regards.
              Alexandre Aubry
              Consultant
              Fi System, The Web Agency
              http://www.fisystem.fr
              mailto:[email protected]
              Phone: +33 1 55 04 03 03 Fax: +33 1 55 04 03 04
              

    Do you have Service Pack 6. SP6 is supposed to fix this problem
              "Jon Armstrong" <[email protected]> wrote in message
              news:[email protected]...
              > Mark/All,
              >
              > As a recent member of the list, this is the only reference/post that
              seemed that
              > it might be related to the problem I'm seeing.
              >
              > I have a servlet that runs fine if I register it through the standard WLS
              httpd
              > servlet mechanism:
              >
              > weblogic.httpd.register.XE=appl.X.EServlet
              > weblogic.httpd.servlet.classpath=\
              > /weblogic/myserver/public_html/XE/myclasses.jar;\
              > ... etc.
              >
              > If I attempt to deploy the servlet as a WebApp:
              >
              > weblogic.httpd.webApp.XE=/C:/XE
              >
              > Where: C:/XE contains
              >
              > WEB-INF/web.xml
              > WEB-INF/lib/myclasses.jar (contains: appl.X.EServlet)
              > WEB-INF/lib/...
              > ...etc.
              >
              > I get the following ClassCast Exception when invoking the servlet:
              >
              > Fri Nov 10 15:14:08 EST 2000:<E> <ServletContext-XE> Error casting
              servlet:
              > appl.X.EServlet java.lang.ClassCastException: appl.X.EServlet
              > at
              >
              weblogic.servlet.internal.ServletStubImpl.createServlet(ServletStubImpl.java
              :382)
              >
              > at
              >
              weblogic.servlet.internal.ServletStubImpl.createInstances(ServletStubImpl.ja
              va:349)
              >
              > at
              >
              weblogic.servlet.internal.ServletStubImpl.prepareServlet(ServletStubImpl.jav
              a:338)
              >
              > at
              >
              weblogic.servlet.internal.ServletStubImpl.getServlet(ServletStubImpl.java:16
              4)
              > at
              >
              weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java
              :99)
              >
              > at
              >
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
              l.java:742)
              >
              > at
              >
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
              l.java:686)
              >
              > at
              >
              weblogic.servlet.internal.ServletContextManager.invokeServlet(ServletContext
              Manager.java:247)
              >
              > at
              weblogic.socket.MuxableSocketHTTP.invokeServlet(MuxableSocketHTTP.java:361)
              > at weblogic.socket.MuxableSocketHTTP.execute(MuxableSocketHTTP.java:261)
              > at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
              >
              > Fri Nov 10 15:14:08 EST 2000:<E> <ServletContext-XE> Servlet failed with
              > Exception
              > javax.servlet.ServletException: Servlet class: appl.X.EServlet does not
              > implement javax.servlet.Servlet
              > at
              >
              weblogic.servlet.internal.ServletStubImpl.createServlet(ServletStubImpl.java
              :385)
              >
              > at
              >
              weblogic.servlet.internal.ServletStubImpl.createInstances(ServletStubImpl.ja
              va:349)
              >
              > at
              >
              weblogic.servlet.internal.ServletStubImpl.prepareServlet(ServletStubImpl.jav
              a:338)
              >
              > at
              >
              weblogic.servlet.internal.ServletStubImpl.getServlet(ServletStubImpl.java:16
              4)
              > at
              >
              weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java
              :99)
              >
              > at
              >
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
              l.java:742)
              >
              > at
              >
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
              l.java:686)
              >
              > at
              >
              weblogic.servlet.internal.ServletContextManager.invokeServlet(ServletContext
              Manager.java:247)
              >
              > at
              weblogic.socket.MuxableSocketHTTP.invokeServlet(MuxableSocketHTTP.java:361)
              > at weblogic.socket.MuxableSocketHTTP.execute(MuxableSocketHTTP.java:261)
              > at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
              >
              > This class doesn't <implement> Servlet. It <extends> a class which
              eventually
              > <extends> HttpServlet... which should suffice, much like the typical
              HelloWorld
              > sample servlets.
              >
              > I have to remove the WEB-INF directory and register this as a standard
              httpd
              > servlet to get weblogic to run it properly.
              > This servlet deploys fine with Jakarta-Tomcat as a WebApp and the same
              web.xml
              > file. I can post that, if need be. I assume the classloader is somehow
              > confused.
              >
              > Is this the same problem discussed below? If so, there's no reference to
              the
              > version of WLS that will address this issue.
              >
              > I'm currently using WLS 5.1. <Fri Nov 10 13:48:48 EST 2000:<I>
              <WebLogicServer>
              > ************ WebLogic Server (5.1.0 04/03/2000 17:13:23 #66825)>
              >
              > Has this been fixed or is there a workaround that allows WebApp deployment
              to
              > succeed? I really would like to stay away from as much web/app server
              specific
              > configuration as possible before taking this into the field.
              >
              > Jon
              >
              > Mark Griffith wrote:
              >
              > > Alexandre:
              > >
              > > Although byte for byte the FooObject is the same, according to the VM
              they
              > > are different class. This is because a class's type distinctiveness is
              > > based not only its interfaces,methods,data members etc but ALSO on its
              > > classloader. There is a different classloader for the
              > > serversclasses_FooObject and the servletclasses_FooObject so they are
              > > considered different, so you get a CCE.
              > >
              >
              > etc...
              >
              > >
              > > This will be handled more elegantly in our next major release Spring
              2000,
              > > however note (and prepare by designing accordingly) the solution is to
              allow
              > > the Servlet to interact with interfaces not actual classes and these
              > > interfaces can be stuffed into system/server loaded classes such as
              > > workspaces and httpsessions, thus preventing CCE's.
              > >
              > > Cheers
              > > Mark G
              > >
              > > Alexandre Aubry wrote:
              > >
              > > > I have a named workspace which is created at startup of the server
              > > > within a starup class.
              > > > When the startup method is called, I instantiate and put an object
              > > > called FooObject in the workspace.
              > > >
              > > > Then, in a servlet, called Dispatcher, in the service method, I
              > > > retrieved my named workspace and the object
              > > > FooObject which is in this workspace. At this time, I have a
              > > > ClassCastException.
              > > >
              > > > To give you more details about my configuration, here is my directory
              > > > configuration:
              > > > weblogic
              > > > |----------- serverclasses
              > > > |------------- startupObject
              > > > |------------- FooObject
              > > > |----------- servletclasses
              > > > |------------- myServlet
              > > > |------------- FooObject (which is
              exactly
              > > > the same of the serverclasses one)
              > > >
              > > > Do you have any ideas ? The idea is to instantiate a given object at
              the
              > > > startup of the web server and to retrieve
              > > > these objects within servlets and JSPs.
              > > >
              > > > Regards.
              > > >
              > > > --
              > > > Alexandre Aubry
              > > > Consultant
              > > > Fi System, The Web Agency
              >
              > ---
              > Jon M. Armstrong
              > Senior Systems Consultant
              > Xelus, Inc.
              >
              > EMail: [email protected]
              > Phone: 716-419-3155
              > Fax: 716-248-9199
              >
              > Visit us online: http://www.xelus.com
              >
              >
              

  • Upgrading R11.5.10 to R12.1.2 - impact on XML Gateway and OTA

    Hello,
    We are testing upgrade of R11.5.10 to R12.1.2 and its impact on XML Gateway and OTA. We have all working well, but not the OTA.
    Outbound:
    The messagess are present in the ECX_OUTBOUND queues but are not send out.
    Inbound:
    Inbound endpoint https://server.com/servlets/oracle.apps.ecx.oxta.ECXOTAInbound returns not found or R12
    Testing https://server.com/OA_HTML/US/ECXOTAPing.htm results in redirection to
    https://server.com/webservices/TransportAgentServer and that returns not found
    https://server.com/OA_HTML/US/ECXOTAInbound.htm displays only information about redirection and it redirects
    to https://server.com/webservices/ECXOTAInbound and it is also not found
    Results of:
    SQL> @$ECX_TOP/patch/115/sql/ecxver.sql
    ECX_UTL_XSLT_DIR Profile :
    /usr/tmp
    ECX_OAG_LOGICALID Profile :
    ECX_SERVER_TIMEZONE Profile:
    ECX_SYS_ADMIN_EMAIL Profile:
    [email protected]
    ECX_XML_VALIDATE_FLAG Profile: Y
    ECX_XML_MAXIMUM_SIZE Profile : 2000000
    utl_file_dir :
    /ORACLE/DB/admin/tmp
    Oracle XML Developers Kit 11.1.0.7.0 - Production
    Parser Version Ok
    XML Gateway Status Summary
    XML Parser Version OK
    All ECX Objects Valid? OK
    All XML Parser Objects Valid? OK
    OTA Running? N/A*
    Total Messages on Outbound Queue 9
    OTA Msgs on Outbound Queue 8
    Others Msgs on Outbound Queue 1
    Messages on Inbound Queue 0
    *Please use the ECXOTAPing.html as described in the Testing Oracle Transport
    Agent section of the User's Guide
    End of Summary
    Service Component Control Event Subscriptions
    EVENT_NAME RULE_FUNCTION OUT_AGENT STATUS
    oracle.apps.ecx.inbound.message.process [email protected] Not Defined ENABLED
    oracle.apps.ecx.inbound.message.process [email protected] Not Defined ENABLED
    oracle.apps.ecx.inbound.message.process [email protected] Not Defined ENABLED
    oracle.apps.ecx.inbound.message.receive [email protected] Not Defined ENABLED
    oracle.apps.ecx.inbound.message.receive [email protected] Not Defined ENABLED
    oracle.apps.ecx.inbound.message.receive [email protected] Not Defined ENABLED
    oracle.apps.ecx.inbound.message.receive [email protected]COMNot Defined ENABLED
    oracle.apps.ecx.inbound.message.receive [email protected]COMNot Defined ENABLED
    oracle.apps.ecx.processing.message.callb [email protected] Not Defined ENABLED
    ack
    oracle.apps.ecx.processing.message.error [email protected] Not Defined ENABLED
    oracle.apps.ecx.processing.message.error [email protected] Not Defined ENABLED
    oracle.apps.ecx.processing.message.error [email protected] Not Defined ENABLED
    oracle.apps.ecx.processing.message.error [email protected]SERVER.COM Not Defined ENABLED
    oracle.apps.ecx.processing.notification.send [email protected] Not Defined ENABLED
    Disconnected from Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    Thank you in adavance for your help,

    Hi,
    Run the diagnostics script in (Note: 732295.1 - R12.0.6+ : Oracle Application Object Library XML Gateway Engine Setup Test) and see if it returns any error/warning messages.
    Regards,
    Hussein

Maybe you are looking for

  • Multiple Windows for Multiple Files using Reader 7.0.9

    Install used to be able to double click on PDFs and open each on in their own window from My Computer using Windows XP Pro SP2. This morning, each file double clicked opens in the same Reader window. In our environment the apps our locked down so the

  • Apply Ink Signature Option Grayed-Out

    Why would other computers except mine within my company who have the most recent Reader installed not be able to access the "apply ink signature" option under "extended?" I have enabled extended features.

  • Set a time/date for forms to automatically close

    We are using Forms Central for proposal submissions. There is a deadline for the proposals to be turned in, and up to now, we've had to turn the form off by hand. Is there a way to set up the form so that it automatically closes itself at a certain d

  • Output for Delivery Document

    Dear Friends, I could see output determinations maintained only for sales document,billing document,sales activities.....if delivery note has to be given then output determination sud b maintained for delivery document ryt.....why theres no determina

  • Does Kodo 4.1 support embedded with the owner-field attribute?

    Does Kodo 4.1 support embedded with the owner-field attribute? My investigations so far say no, that it is infact ignored. This is a very serious problem for the project I am working on. Please proove me wrong...