Servlet query

Hi,
I am using jdk1.4.1version and apache tomcat5.0 server.
I have written a code in servlets and also i can compile the codes.
the problem is with running the server. whenever i run the server to view the result, i will get an error as below. But i can view the tomcat's home page and yhe linked pages.
Http Status:404
type Status report
message /proj/Servletauthentication
description The requested resource (/proj/Servletauthentication) is not available.
Apache Tomcat/5.0.27
This is happening with almost every codes. Here is the configurations which i have made.
JAVA_HOME=D:\java1\Program Files\j2sdk1.4.1
CATALINA_HOME=D:\Tomcat5.0
path=%JAVA_HOME%\bin;%CATALINA_HOME%\bin;
Pls let me know where i have gone wrong. also i've written the web.xml file.
Pls its an urgent. If i get a soln to above problem i can proceed further.
Pls help

Hi,
Here is the web.xml
Let me tel u the directory structure. I created a folder in webapps called project, in this is WEB-INF, under which are classes, lib folders n web.xml.
So in classes folder there r com/mypackage/servlet, in this servlet folder r all .class files.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
     <display-name>project</display-name>
<description>
Tomcat Example servlets and JSP pages.
</description>
<servlet>
<servlet-name>com.mypackage.servlet.HelloWorld</servlet-name>
<servlet-class>com.mypackage.servlet.HelloWorld</servlet-class>
</servlet>
<servlet>
<servlet-name>com.mypackage.servlet.Servletauthentication</servlet-name>
<servlet-class>com.mypackage.servlet.Servletauthentication</servlet-class>
</servlet>
<servlet>
<servlet-name>com.mypackage.servlet.Form</servlet-name>
<servlet-class>com.mypackage.servlet.Form</servlet-class>
</servlet>
<servlet>
<servlet-name>com.mypackage.servlet.FileUpload</servlet-name>
<servlet-class>com.mypackage.servlet.FileUpload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>com.mypackage.servlet.HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>com.mypackage.servlet.Servletauthentication</servlet-name>
<url-pattern>/Servletauthentication</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>com.mypackage.servlet.Form</servlet-name>
<url-mapping>/Form</url-mapping>
</servlet-mapping>
<servlet-mapping>
<servlet-name>com.mypackage.servlet.FileUpload</servlet-name>
<url-pattern>/FileUpload</url-pattern>
</servlet-mapping>
</web-app>
Pls let me know whetehr it is right or no.
Pls help.
Regards

Similar Messages

  • Servlet query string

    Is it possible to hide the servlet query string from the browser,
    eg., http://localhost:8080/servlet1?a=10&b=20$c=30
    If we click on this URL, the whole URL will be displayed in browser, I want to hode the URL, is it possible,
    Thanks in advance
    sam

    use the post method in the form submitting to your
    servlet. query string is not displayed for post
    requests.Hi thanks for ur reply,
    I have used post method on different senario,
    I will explain my problem, I am not using any forms in my jsp
    "10/10/2001" this is the hiper link, when I click this link,
    this should invoke a servlet, see the code below,
    <td align="right"><a href="myServlet?a=1&b=<%=m.getb()%>&Date=<%= bdate %>">10/10/2001</a> ?</td>
    if U click the above link, this will show the whole URL in the browser,
    but, I want hide the whole query string, is this possible
    "http://localhost:8080/myServlet/" - no query string to be shown,
    thanks
    Hari

  • How can servlet return data as download file from browser ? !!! URGENT !!!

    My servlet query data from database and would like to return the data as text file.
    How can I return data to the browser as user click a file to download ?
    How can I set the file name ? (default name is the servlet name that I don't want it to be)
    Which content type should I return to browser to prevent browser to display data immediately but save instead ?
    Thank you very much !

    I am having the same issue. Did you ever discover a way to change the "file name" in the browser. I've tried changing numerous HTTP header fields, to no avail.
    Marc

  • Servlet don't work properly

    I have did to run this servlet but thereis an odd thing. This servlet
    query a service to database server to perform login mechanism. But the output always LoginFailed.jsp whenever i typed the user and password. Anyone wants to help.Please.Thanks in advance...
    import java.io.*;
    import java.text.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class LoginServlet extends HttpServlet {
         static final String dbURL ="jdbc:mysql://localhost:3306/login?" +
    "user=firman@localhost&password=ajolie";
         public void doPost(HttpServletRequest request, HttpServletResponse response)
              throws IOException, ServletException {
         Connection conn = null;
         String nextJSP = null;
         try {
              Class.forName("com.mysql.jdbc.Driver");
         catch (ClassNotFoundException e) {
              throw new ServletException("Unable to load JDBC driver");
         try {
              String userid = (String)request.getParameter("userid");
              String password = (String)request.getParameter("password");
              conn = DriverManager.getConnection(dbURL);
              Statement stmt = conn.createStatement();
              String query = "SELECT firstname, lastname " + "FROM users " + "WHERE userid = ' " + userid +" ' AND password =' " + password + " ' ";
              ResultSet rs = stmt.executeQuery(query);
              if (rs.next()) {
                   StringBuffer fullName = new StringBuffer();
                   fullName.append(rs.getString(1));
                   fullName.append(" ");
                   fullName.append(rs.getString(2));
                   request.setAttribute ("fullName", fullName.toString());
                   nextJSP = "/LoginOK.jsp";
              else {
                   nextJSP = "/LoginFailed.jsp";
              conn.close();
              ServletConfig config = getServletConfig();
              ServletContext context = config.getServletContext();
              RequestDispatcher rd = context.getRequestDispatcher(nextJSP);
              rd.forward(request, response);
         catch (SQLException e) {
              throw new ServletException(e.getMessage());
         finally {
              if (conn != null) {
                   try {
                        conn.close();
                   catch (SQLException e) {
                        throw new ServletException("connection close failed");
         public void doGet(HttpServletRequest request, HttpServletResponse response)
              throws IOException, ServletException {
                   doPost(request, response);
    LOGINOK.JSP
    <%response.setContentType("text/plain");%>
    Welcome <%= (request.getAttribute("fullName"))%>
    LOGINFAILED.JSP
    <%response.setContentType("text/plain");%>
    Login failed!

    Use this class and try.
    import java.io.*;
    import java.text.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class LoginServlet extends HttpServlet {
    static final String dbURL ="jdbc:mysql://localhost:3306/login?" +
    "user=firman@localhost&password=ajolie";
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
    Connection conn = null;
    String nextJSP = null;
    try {
    Class.forName("com.mysql.jdbc.Driver");
    catch (ClassNotFoundException e) {
    throw new ServletException("Unable to load JDBC driver");
    try {
    String userid = (String)request.getParameter("userid");
    String password = (String)request.getParameter("password");
    conn = DriverManager.getConnection(dbURL);
    String query = "select firstname,lastname from users where userid=? and password=?";
    PreparedStatement ps = conn.prepareStatement(query);
    ps.setString(1,userid);
    ps.setString(2,password);
    ResultSet rs = ps.executeQuery();
    if (rs.next()) {
    StringBuffer fullName = new StringBuffer();
    fullName.append(rs.getString(1));
    fullName.append(" ");
    fullName.append(rs.getString(2));
    request.setAttribute ("fullName", fullName.toString());
    nextJSP = "/LoginOK.jsp";
    else {
    nextJSP = "/LoginFailed.jsp";
    conn.close();
    ServletConfig config = getServletConfig();
    ServletContext context = config.getServletContext();
    RequestDispatcher rd = context.getRequestDispatcher(nextJSP);
    rd.forward(request, response);
    catch (SQLException e) {
    throw new ServletException(e.getMessage());
    finally {
    if (conn != null) {
    try {
    conn.close();
    catch (SQLException e) {
    throw new ServletException("connection close failed");
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
    doPost(request, response);

  • DATEDIFF in Servlet

    I have two dates in the format yyyy-mm-dd format, i want to put the difference between the days in a integer for calculation purpose, Can someone tell me how to do this in Servlet query with DB2.The date values in DB2 table are Startdate and Enddate.
    I have searched quite a bit, somehow the thing isnt working, any quick help is really appreciated.
    I want to find the absolute date difference between two values, like say the first one is 1990-12-10 and the other one is 1991-01-10
    The datediff value should be 30 in this case.
    Edited by: memspool on Nov 8, 2008 10:44 PM

    Just read the DB specific SQL documentation how to query the difference between the two dates using SQL. Then you already have it in your resultset.
    If you really want to do this in Java somehow, use the java.util.Calendar methods like after(), before(), add() and get().

  • One to one relationship in jpa

    I have two relation table like , I would Like to try select by UID by JPA ,
    select *from student as P, Address as A where P.UserId=A.UserId
    and A.UpdateId=uid;
    step one
    I have my persistence.xml testing by single table
    step two I have two entity class from DB
    in my student{} @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Basic(optional = false)
    @Column(name = "UserId", nullable = false)
    private Integer userId;.....
    in my address I have
    @JoinColumn(name = "UserId", referencedColumnName = "UserId", nullable = false)
    @OneToOne(cascade=CascadeType.ALL, mappedBy="Student")
    private Student student;
    what else I need to do in order to let it work??

    jsutherl wrote:
    To do a join in JPA you can either use "join" or the "." notation for a OneToOne.
    i.e.
    Select s from Student s where s.address.updateId = :id
    You would need a OneToOne from Student to Address for this.
    @OneToOne(mappedBy="student")
    private Address address;
    James : http://www.eclipselink.org
    I guest I get the part that you post , but if I want to display the information out of two tables, but in Servlet
    Query query=em.createNamedQuery("?");
    List stList=query.getResultList();
    Iterator stIterator=stList.iterator();
    while(stIterator.hasNext()){
    *? which class?*=?.stIterator.next();} ??
    Thank you!

  • Combo filled with data from database

    i want to display the list of schemas dynamically in a combo box and then display the tables in that schema. i tried a servlet; but the schemas are not displayed.
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.net.*;
    import java.sql.*;
    public class try extends HttpServlet
         public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
         PrintWriter out;
         res.setContentType("text/html");
         out = res.getWriter ();
         try
         out.println("<html>");
         out.println("<head>");
         out.println("<script language='javascript'>");
         out.println("function one()");
         out.println("{");
         out.println(" ResultSet rs=st.executeQuery('select distinct owner from all_tab_columns')");
         out.println("while(rs.next())");
         out.println("{");
         out.println("var newElement=document.createElement('option')");
         out.println("newElement.value=rs.getString(1)");
         out.println("document.form1.table1.options.add(newElement))");
         out.println("}");
         out.println("}");
         out.println("</script>");
         out.println("</head>");
         out.println("<body>");
         out.println("<form name=form1 action=http://mysystem:9000/servlet/query method=post>");
         out.println("Schema name");
         out.println("<input type=textbox name='user'><br>");
         out.println("Password");
         out.println("<input type=password name='pwd'><br>");
         System.out.println("Password");
         out.println("Table Name");
         DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
         Connection m_connection;
    m_connection = DriverManager.getConnection("jdbc:oracle:thin:@mysystem:1521:oracle8","scott","tiger");
         Statement st=m_connection.createStatement();
         System.out.println(st);
         out.println("<select name='table1' onFocus=one();>");
         out.println("<option value=' '>");
         out.println("</option>");
         out.println("</select>");
         out.println("<br>");
         out.println("<input type=submit>");
         out.println("</form>");
         out.println("</body>");
         out.println("</html>");
         }catch(SQLException s){
              out.println("Trial");
         catch(java.lang.Exception x){ }
    }

    If you're wanting to get data back from the database you're actually going to have to execute a query. The Statement:out.println(" ResultSet rs=st.executeQuery('select distinct owner from all_tab_columns')"); will print out the query you wish to run, showing it to the user, but it won't execute it.
    Try instead:
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    Connection m_connection;
    m_connection = DriverManager.getConnection("jdbc:oracle:thin:@mysystem:1521:oracle8","scott","tiger");
    Statement st=m_connection.createStatement();
    out.println("<select name='table1' onFocus='one();'>");
    ResultSet rs=st.executeQuery("select distinct owner from all_tab_columns");
    while(rs.next()){
    String val = rs.getString(1);
    out.println("<OPTION VALUE='" + val + "'>" + val + "</OPTION>";
    rs.close();
    st.close();
    out.println("</select>");

  • Design issue with an application

    Hi
    Requirement : I have an application which needs to access database and show the resultset on the screen.
    The design is as follows:
    (I am implementing Connection Pooling as I have not been able to configure the Tomcat's Connection Pooling)
    1)I have a Main page.
    2)I have a startup servlet(startupservlet.java) which creates a conenction pool by the following call in the init method of the servlet.
    pool = new ConnectionPool(p_url,p_username,p_userpass, p_driverclassname, p_initconnections_i, p_increment_i);
    "ConnectionPool.java" is a class which I have written which has a Hashtable which stores my connections. It also has method to get connection as well.
    3) Now I enter my search parameters on my Main page. On the click of submit button my page calls a servlet "query.java".
    4)In query.java I want to take a conenction from the pool object that was created by the "Startupservlet" using the getConnection() method.
    My first question is :
    a) Is the connection pool object that was created by the startup servlet still available for me to use.
    b) How can I access that connection pool object to get a connection.
    Is there any other approach as well. Is my design correct.
    Any comments would be welcome and highly appreciated.
    Amit

    Write a class that contains the pool. If your database stores, say, Fish:
    public class FishPool
        private static ConnectionPool pool;
        public void initialize() { pool = ...; } // Call this from initializer servlet
    // EITHER:
        public ConncetionPool pool() { return pool; }
    // OR:
        public Connection getConnection() { return pool.getConnection(); }
        public void returnConnection(Connection c) { pool.returnConnection(c); }
    }Then you can do either ("singleton pattern"):
        Connection c = FishPool.pool().getConnection();
        FishPool.pool().returnConnection(c); // In a finally blockor:
        Connection c = FishPool.getConnection();
        FishPool.returnConnection(c); // In a finally block

  • Flash reading binary from a database

    i'm storing videos and images inside a blob in mysql and i
    need to have flash 8 read the files. right now i'm querying the
    database using php and then converting the php page to xml and then
    flash is parsing the xml. i need any feedback i can get. thanks in
    advance.

    Sounds feasible if DB is on the same server as your web server. You'll need the MySQL JDBC drivers which you can get from the MySQL site.
    Note however that a more common way of doing this is to have you Applet send the parameters for the query to a servlet, have the servlet query the database and return the results to the Applet for display.

  • Working of ComboBox in JSP

    I am new to jsp programming. I have no idea how to navigate if there is two dropdownlist. Here second one depends on the first one then should i have to design two pages with sam dessign?
    I have checked the url
    http://forum.java.sun.com/editwatches!default.jspa
    thsi page contains two comboboxes. I have selected java essentials from first combo. Then it got redirected to another page.
    with the url
    http://forum.java.sun.com/editwatches!default.jspa?filterCat=5
    When I checked the view source of http://forum.java.sun.com/editwatches!default.jspa
    I have seen something like this...
    <select name="filterForum"
    onchange="location.href='editwatches!default.jspa?filterForum='+this.options[this.selectedIndex].value+'&filterCat='+this.form.filterCat.options[this.form.filterCat.selectedIndex].value;">
    In the above code what do they mean by location?
    Please reply me
    Thanks in advance

    Hi,
    Well if you are looking for Dependent Dropdown problem...
    There are many solutions in order acheive this...
    checkout some of those...
    1).Save the present of the Form in a Bean with the scope of session and onChange of the first Combo box redirect it to a Controller(Servlet) Query the Database and save the results in the FormBean which we saved in the scope session and then redirect the formBean to the same JSP again...and now repopulate the second combo with new obtained results from the database and repopulate the rest of the form according to present FormBean state from the session.
    Here is a Typical example for you
    Assuming that a Servlet had already preloaded the first drop-down values from the database in a FormBean
    FormBean.java
    =============
    public class FormBean{
    private String firstDDValue = new String("");
    private ArrayList firstDDOptions = new ArrayList();
    private String secondDDValue = new String();
    private ArrayList secondDDOptions = new ArrayList();
    // Setters & getters for all the bean properties.
    }Form.jsp:
    =========
    <jsp:useBean id="formBean" class="com.formbeans.FormBean" scope="session"/>
    <%
      ArrayList fristDD = formBean.getFirstDDOptions();
      ArrayList secondDD = formBean.getSecondDDOptions();
      String firstDDValue = formBean.getFirstDDValue();
      String secondDDValue = formBean.getSecondDDValue();
      int FDSIZE = fristDD.size();
      int SDSIZE = secondDD.size();
    %>
    <form name="formBean">
    First DropDown:
    <select name="firstDropDown" onChange="if(this.value != '-1')window.location.href='ControlerServlet?firstDropDown='+escape(this.value);" >
    <option value="-1">Pick One</option>
    <%for(int i = 0;i < FDSIZE ; i++){
        String value = ((String[])firstDDOptions.get(i))[0];
        String text = ((String[])firstDDOptions.get(i))[1];
    %>
      <%if(value.equals(firstDDValue){)%>
       <option value="<%=value%>" selected="selected"><%=text%></option>
      <%}else{%>
       <option value="<%=value%>"><%=text%></option>
      <%}%>
    <%}%>
    </select>
    <BR/>
    <BR/>
    Second DropDown:
    <select name="secondDropDown">
    <option value="-1">Pick One</option>
    <%for(int i = 0;i < FDSIZE ; i++){
        String value = ((String[])secondDDOptions.get(i))[0];
        String text = ((String[])secondDDOptions.get(i))[1];
    %>
      <%if(value.equals(secondDDValue){)%>
       <option value="<%=value%>" selected="selected"><%=text%></option>
      <%}else{%>
       <option value="<%=value%>"><%=text%></option>
      <%}%>
    <%}%>
    </select>
    <BR/>
    <BR/>
    </form> NOTE: It would be a better practise if you can make use of JSTL tags to render the page in to make your View Page look more cleaner
    ControlerServlet.java
    =====================
    public doGet(request,response){
    String firstDropDown = request.getParameter("firstDropDown");
    HttpSession session = request.getSession();
    FormBean fb = (FormBean) session.getAttribute("formBean");
    fb.setFirstDDValue(firstDropDown); 
    fb.setSecondDDOptions(DAODelegate.getSecondDropDownData(firstDropDown));
    session.setAttribute(""formBean",fb);
    response.sendRedirect("/Form.jsp");
    }2).Make use of a Hidden IFrame by using which you reload the page and then Reload a Page after getting values from the database update the parent frame combo accordingly.
    3).Take help of AJAX call a Controller get the Response in XML/JSON and parse it and then update the second combo by the XML/JSON response.
    checkout an example by you can achieve this.
    index.jsp:
    =======
    <%@page language="java" %>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>Automatic Dependent Drop-Down Updation</title>
         <script language="javascript">
          // Global Variable for XmlHttp Request Object  
          var xmlhttp
          // Timer Variables
          var c = 0
          var t
           /* A function which calls a servlet  named AjaxServlet to get XmlData using XmlHttpObject */    
            function refreshCombo(txt){
                xmlhttp = null
                // code for initializing XmlHttpRequest Object On Browsers like  Mozilla, etc.
                if (window.XMLHttpRequest){
                     xmlhttp = new XMLHttpRequest()
                // code for initializing XmlHttpRequest Object On Browsers like IE
               else if (window.ActiveXObject) {
                   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
               if (xmlhttp != null){
                  // Setting the Servlet url to get XmlData
                   url = "AjaxServlet?req="+txt;
                   // Course of Action That Should be Made if their is a change in XmlHttpRequest Object ReadyState NOTE : it is 4 when it has got request from CGI
                   xmlhttp.onreadystatechange = getResponseAction;
                   // Open the Request by passing Type of Request & CGI URL
                   xmlhttp.open("GET",url,true);
                   // Sending URL Encoded Data
                   xmlhttp.send(null);
               else{
                 // Only Broswers like IE 5.0,Mozilla & all other browser which support XML data Supports AJAX Technology
                 // In the Below case it looks as if the browser is not compatiable
                  alert("Your browser does not support XMLHTTP.")
          /* Used for verifing right ReadyState & Status of XmlHttpRequest Object returns true if it is verified */
          function verifyReadyState(obj){
             // As Said above if XmlHttp.ReadyState == 4 then the Page Has got Response from WebServer
              if(obj.readyState == 4){
               // Similarly if XmlHttp.status == 200 it means that we have got a Valid response from the WebServer
                if(obj.status == 200){               
                    return true
                 else{
                    alert("Problem retrieving XML data")
          /* Action that has to take place after getting reponse */
          function getResponseAction(){
              // Verifying State & Status
              if(verifyReadyState(xmlhttp) == true){
                  // Building a DOM parser from Response Object
                  var response = xmlhttp.responseXML.documentElement
                  // Deleting all the Present Elements in the Drop-Down Box
                  drRemove()      
                  // Checking for the Root Node Tag
                  var x = response.getElementsByTagName("option")
                  var val
                  var tex
                  var optn
                  for(var i = 0;i < x.length; i++){
                     optn = document.createElement("OPTION")
                     var er
                     // Checking for the tag which holds the value of the Drop-Down combo element
                     val = x.getElementsByTagName("val")
    try{
    // Assigning the value to a Drop-Down Set Element
    optn.value = val[0].firstChild.data
    } catch(er){
    // Checking for the tag which holds the Text of the Drop-Down combo element
    tex = x[i].getElementsByTagName("text")
    try{
    // Assigning the Text to a Drop-Down Set Element
    optn.text = tex[0].firstChild.data
    } catch(er){
    // Adding the Set Element to the Drop-Down
    document.SampleForm.state.options.add(optn)
    /* Function removes all the elements in the Drop-Down */
    function drRemove(){
    document.SampleForm.state.options.length = 0;
    </script>
    </head>
    <body>
    <pre> <h1>Refresh Drop-Down <div id='txt'> </div> </h1></pre>
    <form name="SampleForm">
    <table align="center">
    <tr>
    <td>Country:</td>
    <td>
    <select name="country" onchange="refreshCombo(this.value)">
    <option value="india">INDIA</option>
    <option value="US">United States</option>
    <option value="UK">United Kingdom</option>
    <option value="Saudi">Saudi</option>
    </select>
    </td>
    </tr>
    <tr>
    <td>State:</td>
    <td>
    <select name="state">
    <option value="-1">Pick One</option>
    </select>
    </td>
    </tr>
    </form>
    </body>
    </html>
    AjaxServlet.java:
    =============
    * AjaxServlet.java
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    * @author RaHuL
    * @version
    public class AjaxServlet extends HttpServlet {
        /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
         * @param request servlet request
         * @param response servlet response
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            // Sets the content type made to xml specific
            response.setContentType("text/xml");
            response.setHeader("pragma","no-cache");
            response.setHeader("Cache-Control","no-cache");
            response.setHeader("Cache-Control","no-store");
           //Initializing PrintWriter
            PrintWriter out = response.getWriter();
            String req = request.getParameter("req");
            // Creating an instance of XmlBean Which generates XmlData From Business Logic specified
            XmlBean xml = new XmlBean(req);
            // Method to Generate XMLDATA
            String buffer = xml.getXmlData();
            // If Close of DB connections are succefull then write the content to the printstream
            if(xml.close() == true)
                out.write(buffer);   
            out.flush();                 
            out.close();
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            // Calls a Method called processRequest Which Processes the request which was made by the Browser Page
            processRequest(request, response);
    }XmlBean.java:
    ===========
    * XmlBean.java
    import java.sql.*;
    import java.util.*;
    import java.io.*;
    * @author RaHuL
    public class XmlBean {
        private Connection con = null;
        private PreparedStatement pstmt = null;
        private ResultSet rs = null;
        private String req;
        // Setting CLASSURL path to TYPE I Driver
        private String CLASSURL = "sun.jdbc.odbc.JdbcOdbcDriver";
        /* Specifing CONNECTION PATH to a DSN named TestDsn
         * Please Make Sure you create a DSN Named TestDsn to your database which holds EMP table
        private String CONNECTIONURL = "jdbc:odbc:TestDsn";
        boolean IS_ESTABLISHED = false;
        /** Creates a new instance of XmlBean and also establishes DB Connections */
        public XmlBean(String req) {
            try{
                this.req = req;
                Class.forName(CLASSURL);
                con = DriverManager.getConnection(CONNECTIONURL,"admin","");
                IS_ESTABLISHED = true;
            } catch(SQLException sqe){
                sqe.printStackTrace();
            } catch(Exception exp){
                exp.printStackTrace();
        /* Generates XmlData For the Business Logic Specified */
        public String getXmlData(){
            String XmlBuffer = "";
            if(IS_ESTABLISHED == true){
                try{
                    pstmt = con.prepareStatement("SELECT stateid,statename FROM EMP where countryid=' "+req+" ' " );
                    rs = pstmt.executeQuery();
                    if(rs != null){
                        XmlBuffer = XmlBuffer + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>";
                        XmlBuffer = XmlBuffer + "<!--  Edited by Rahul Sharma -->";
                        // Root Node
                        XmlBuffer = XmlBuffer + "<dropdown>";
                        while(rs.next()){
                            String value = rs.getString(1);
                            String text = rs.getString(2);
                            // Sub-root Node
                            XmlBuffer = XmlBuffer + "<option>";
                            // node which holds value of drop-down combo
                            XmlBuffer = XmlBuffer + "<val>"+value+"</val>";
                            // node which holds text for drop-down combo
                            XmlBuffer = XmlBuffer + "<text>"+text+"</text>";
                            XmlBuffer = XmlBuffer + "</option>";
                        XmlBuffer = XmlBuffer + "</dropdown>";
                }catch(SQLException sqe){
                    sqe.printStackTrace();
                } catch(Exception exp){
                    exp.printStackTrace();
            return(XmlBuffer);
        /* Closes the DB Connection Conmpletely */
        public  boolean close(){
            if(IS_ESTABLISHED == true){
                try{
                    pstmt.close();
                    con.close();
                    return(true);
                } catch(SQLException sqe){
                    sqe.printStackTrace();
                } catch(Exception exp){
                    exp.printStackTrace();
            return(false);
    }Sample XML Reponse generated:
    <?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>
    <!--  Edited by Rahul Sharma -->
    <dropdown>
    <option>
    <val>DEL</val>
    <val>New Delhi</val>
    </option>
    <option>
    <val>HAR</val>
    <val>HARYANA</val>
    </option>
    </dropdown>for further reference you may use the below articles
    http://www.it-eye.nl/weblog/2005/12/13/ajax-in-struts-implementing-dependend-select-boxes/
    http://www.it-eye.nl/weblog/2006/04/04/implementing-dependent-select-boxes-in-jsf/
    Hope this might help,if that does do not forget to assign/distribute Duke Stars which you have promised :)
    REGARDS,
    RaHuL

  • How to get the query values from the url in a servlet and pass them to jsp

    ok..this is the situation...
    all applications are routed through a login page...
    so if we have a url like www.abc.com/appA/login?param1=A&param2=B , the query string must be passed onto a servlet(which is invoked before the login page is displayed)..the servlet must process the query string and then should pass all those values(as hidden values) to the login jsp..then user enters username and pswd, then there should be another servlet which takes all the hidden values of jsp and also username and pswd, authenticates the user and sends the control back to that particular application along with the hidden values...
    so i need help on how to parse the query string from the original url in the servlet, pass it out to jsp, and then pass it back to the servlet and back to the original application...damnn...any help would be greatly appreciated...thanks

    ok..this is the situation...Sounds like you have a bad design on your hands.
    You're going to send passwords in a GET request as clear text? Nice security there.
    Why not start with basic security and work your way up?
    %

  • Problem of Query Chinese words in MySQL using Java (Servlet java)

    In my servlet, if I build in this sql inside ,
    SELECT * FROM table WHERE location='Chinese word here'
    It outputs nothing!
    if i change the 'Chinese word here' to English,it have result!
    But if I query in mysql, i can
    If the 'Chinese word here' is get in a form, (ie 'Chinese word here' is got by req.getParameter but not built in), it can display result, why???

    Hi hlj_zhj
    Oh your method works, I change the Gb2322 to Big5,
    and I have a question about your "return shift", shift is not defined in your part of programme, so I change to follows:
    private String getISO(String gbstr){
    String temp=null;
    try{
    String temp_p = gbstr;
    byte[] temp_t = temp_p.getBytes("Big5");
    temp = new String(temp_t, "ISO8859-1");
    catch(Exception e){}
    return temp;
    ANOTHER question, Some of my BIG5 words contains "Hong Kong Words,eg:�`������", therefore, using temp_p.getBytes("Big5") not work in this case, do you have any suggestion in this case? thanks

  • Query handled OK on Oracle server but XSQL Servlet raises OracleXMLSQLException

    After dropping and recreating certain object types, and then using ALTER TYPE on an object dependent on those object types, XSQL Servlet raises exception for a query that is handled fine in the Oracle Server itself (ie, in SQL*Plus) as in the following test case:
    create or replace type o_object_inner as object( char1 char(1) )
    create or replace type n_nested_table as table of o_object_inner
    create or replace type o_object_outer as object (nNestedTab n_nested_table)
    For above, the following query encounters no problems on Oracle Server or in XSQL servlet:
    Select o_object_outer(NULL) as "theOuterObj" from dual
    But then if object types are modified as follows:
    drop type o_object_inner force
    create or replace type o_object_inner as object( char1 char(1) ) --same as above
    drop type n_nested_table force
    create or replace type n_nested_table as table of o_object_inner --same as above
    alter type o_object_outer compile
    The above query now encounters no problems in SQL*Plus but generates exception in XSQL servlet as follows:
    oracle.xml.sql.OracleXMLSQLException: Internal Error: Unable to resolve name
    More complex cases generated the above exception and/or the following exception:
    oracle.xml.sql.OracleXMLSQLException: Internal Error: Invalid ADT attribute
    Any insight or help would be greatly appreciated!
    Other info:
    Oracle Server 8.1.7.3 on HP-UX
    XDK 9.2.0.1 (Production) for Java on NT
    JDBC/OCI8 drivers for NT (latest for 8.1.7)

    Yes,
    I changed most of the cursor functions to cast(multiset()). Sometimes i divided a big query into two or three queries (when there was cursor nested in a cursor). It was one day work for me. Don't forget to change the tags with ROW to ITEM in your xsl-stylesheets.
    Uwe

  • C:import tag - Query string while calling servlet from JSP

    Hi,
    From my JSP I am calling a servlet to write back to the response stream of the JSP. From the JSP i am trying to pass some values into the query string as follows
         <%
         String strGetParameters = "/servlet/MyServlet?path=" + strPath;
          %>
         <pre><c:import url="<%=strGetParameters%>" /></pre>In the servlet I try to get the path from the query string by using
    request.getParameter("path")But in the servlet the query string doesnt have the "path" parameter that I added in the strGetParameters string (in the JSP).
    Am i missing something? Do i have to use something else or do something else?
    Any help is appreciated.

    I've taken some time to do a simple test and it just works.
    Here is the test code, it was tested in Java EE 5 + JSTL 1.2 + Tomcat 6.
    JSP<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
    <html>
        <head>
            <title>Test</title>
        </head>
        <body>
            <pre>
                <c:import url="myServlet?param1=foo&param2=bar">
                    <c:param name="param3" value="meep" />
                    <c:param name="param4" value="waah" />
                </c:import>
            </pre>
        </body>
    </html>MyServlet (mapped on "/myServlet")package mypackage;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class MyServlet extends HttpServlet {
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
            String param1 = request.getParameter("param1");
            String param2 = request.getParameter("param2");
            String param3 = request.getParameter("param3");
            String param4 = request.getParameter("param4");
            String output = param1 + ", " + param2 + ", " + param3 + ", " + param4;
            response.getOutputStream().write(output.getBytes());
    }All parameters gets printed.

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

Maybe you are looking for

  • How to delete a song from my Apple ID?

    I have iTunes Match, and sync a song, but I wanted to delete so I delete the song from my iTunes library, but I not select the box "Delete iCloud also", let me know how I can remove it from iCloud.

  • Live Office XI3.1 SP2

    I get the following error message when trying to authenticate with Live Office (XI3.1 SP2) : 'Class not registered - Exception from HRESULT 0x80040154 (REGDB_E_CLASSNOTREG) Any idea how to solve this ? kind reg.

  • Music player on DroidX automatically coming on

    The built in music player on the phone at random times will turn itself on which started yesterday. I will go into it and there is no stop button, just a pause. I will pause it long enough to go into settings to force close it, but a few seconds late

  • Open links behind mail

    Since migrating to Yosemite, I can no longer  use "open links behind mail" feature.  Apparently this is a bug and I see complaints about it going back to Oct 2013 at least.  Does anyone know if Apple EVER fixed this problem?

  • Schema capture problem

    Hello - I am doing a test migration on a db from SQL Server 2K5 to Oracle 10g R1 using . When attempting to capture the SQL Server db, the process begins fine but fails to capture all the tables/stored procedures in the database. In the Migration Log