Parameters from midlet to servlet

Hi all,
i have been trying to pass values from MIDlet (setRequestProperty(); ) and to servlet (request.getParameter();).
but when i tried to print out the value, it just contained NULL value.
I had a look at the java forum website, there were plenty of same problems and no one got right.
I'll really appreciate it if anyone fixes this for me.
---------------------MIDLET-----------------------------------------------------------------------------
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
import java.util.*;
import org.kxml.*;
import org.kxml.parser.*;
public class MbankMIDlet  extends MIDlet implements CommandListener {
  private Display display;
  private Form loginForm = new Form("Login");
  private Form mainForm = new Form("MobileBank");
  private String loguserID;
  private String logpass;
  private String mSession;
  private StringItem stringItem = new StringItem(null,"");
  private TextField userIDTextField = new TextField("User ID", "", 8, TextField.NUMERIC);
  private TextField passwordTextField = new TextField("Password", "", 12, TextField.PASSWORD);
  static final Command loginCommand = new Command("Login", Command.OK, 1);
  static final Command exitCommand = new Command("Exit", Command.STOP, 1);
  static final Command backCommand = new Command("Back",Command.BACK, 1);
  public MbankMIDlet() {
    mainForm.append(stringItem);
    mainForm.addCommand(exitCommand);
    mainForm.addCommand(backCommand);
    mainForm.setCommandListener(this);
  public void startApp() throws MIDletStateChangeException {
    display = Display.getDisplay(this);
    loginForm.append(userIDTextField);
    loginForm.append(passwordTextField);
    loginForm.addCommand(loginCommand);
    loginForm.addCommand(exitCommand);
    loginForm.addCommand(backCommand);
    loginForm.setCommandListener(this);
    display.setCurrent(loginForm);
  public void destroyApp(boolean unconditional) {
    notifyDestroyed();
  public void mainMenu() {
    display.setCurrent(loginForm);
  public void pauseApp() {
    display = null;
    loginForm = null;
    mainForm = null;
    stringItem = null;
    userIDTextField = null;
    passwordTextField = null;
  public void commandAction(Command c, Displayable d) {
    String label = c.getLabel();
    if (label.equals("Exit")) {
      destroyApp(true);
       mSession = null;
    } else if (label.equals("Login")) {
      login();
    } else if (label.equals("Back")){
      mainMenu();
  private void login() {
    loguserID = userIDTextField.getString();
    logpass = passwordTextField.getString();
    Form waitForm = new Form("Waiting...");
    display.setCurrent(waitForm);
    Thread t = new Thread() {
      public void run() {
        connect();
    t.start();
  private void connect() {
    HttpConnection hc = null;
    InputStream in = null;
    OutputStream os = null;
    String url = getAppProperty("MbankMIDlet.URL");
    try {
      hc = (HttpConnection)Connector.open(url);
      hc.setRequestMethod(HttpConnection.GET);
      hc.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0" );
      hc.setRequestProperty("Content-Language", "en-US" );
      hc.setRequestProperty("Accept", "text/plain");
      hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded" );
      hc.setRequestProperty("Connection","close");
      hc.setRequestProperty("loguserID", loguserID);
      hc.setRequestProperty("logpass", logpass);
      os = hc.openOutputStream();
      os.close();
//      os.flush();  //tried close() and flush() but none of them worked.
      if (mSession != null) {
          hc.setRequestProperty("Cookie", mSession);
      // Read the session ID from a cookie in the response headers.
      String cookie = hc.getHeaderField("Set-cookie");
      if (cookie != null) {
          int semicolon = cookie.indexOf(';');
          mSession = cookie.substring(0, semicolon);
      in = hc.openInputStream();
      int rc = hc.getResponseCode();
      if( rc == HttpConnection.HTTP_OK ) { //HTTP_OK equals 200
        System.out.println("HttpConnection OK");
        StringBuffer xmlBuffer = new StringBuffer();
        String xmlString = null;
        int ch;
        while ( ( ch = in.read() ) != -1 )
          xmlBuffer.append( ( char )ch );
        xmlString = xmlBuffer.toString();
        stringItem.setText(xmlString);
      else if (rc == HttpConnection.HTTP_UNAUTHORIZED){//HTTP_UNAUTHORIZED equals 401
        System.out.println("HttpConnection Unauthorized");
        int contentLength = (int)hc.getLength();
        byte[] raw = new byte[contentLength];
        int length = in.read(raw);
        String s = new String(raw,0,length);
        stringItem.setText(s);
      in.close();
      hc.close();
    catch (IOException ioe) {
      stringItem.setText(ioe.toString());
    finally {
      display.setCurrent(mainForm);
}---------------SERVLET----------------------------------------------------------------------------
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class LoginServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          HttpSession session = request.getSession();
          response.setContentType("text/plain");
          PrintWriter out = response.getWriter();
          String userID, password, userRole = null;
          try {
                              userID = (String)request.getParameter("loguserID");
              password = (String)request.getParameter("logpass");
              System.out.println(userID); // "Null printed"              System.out.println(password);  // "Null printed"
          catch (Exception e) {
               //If anything goes wrong, print the Exception message
              e.printStackTrace(out);
}Thanks.

getParameter() can't parse the input stream well if there is any issues in the sent content. this is true, with varying mobile phone http impl.
You would find the content at servlet, by using request.getInputStream() and reading the entire content.
Here is the sample code:
public static String readMobileData(final HttpServletRequest aRequest) throws Exception
     String lData = null;
     Enumeration params = aRequest.getParameterNames();
     while (params.hasMoreElements())
     //from real Nokia 6600 Mobile the request is sent as param, though
     //it is post
     String lName = params.nextElement().toString();
     lData = aRequest.getParameter(lName);
     System.out.println("\nParameter:" + lName + "=" + lData);
     if (lData == null)
     //in emulator the data is coming as inputstream
     ServletInputStream in = aRequest.getInputStream();
     DataInputStream dIn = new DataInputStream(in);
     lData = dIn.readUTF();
     lData = lData.substring(lData.indexOf("=") + 1);
     System.out.println("Stream Request:\n" + lData);
     return lData;
Regards,
Raja Nagendra Kumar,
C.T.O,
When Teja is Tasked, the Job Gets Done
www.tejasoft.com

Similar Messages

  • Need help with my HttpConnection From Midlet To Servlet...

    NEED HELP ASAP PLEASE....
    This class is supposed to download a file from the servlet...
    the filename is given by the midlet... and the servlet will return the file in bytes...
    everything is ok in emulator...
    but in nokia n70... error occurs...
    Http Version Mismatch shows up... when the pout.flush(); is called.. but when removed... java.io.IOException: -36 occurs...
    also i have posted the same problem in nokia forums..
    please check also...
    http://discussion.forum.nokia.com/forum/showthread.php?t=105567
    now here are my codes...
    midlet side... without pout.flush();
    public class DownloadFile {
        private GmailMidlet midlet;
        private HttpConnection hc;
        private byte[] fileData;
        private boolean downloaded;
        private int lineNumber;
    //    private String url = "http://121.97.220.162:8084/ProxyServer/DownloadFileServlet";
        private String url = "http://121.97.221.183:8084/ProxyServer/DownloadFileServlet";
    //    private String url = "http://121.97.221.183:8084/ProxyServer/Attachments/mark.ramos222/GmailId111d822a8bd6f6bb/01032007066.jpg";
        /** Creates a new instance of DownloadFile */
        public DownloadFile(GmailMidlet midlet, String fileName) throws OutOfMemoryError, IOException {
            System.gc();
            setHc(null);
            OutputStream out = null;
            DataInputStream is= null;
            try{
                setHc((HttpConnection)Connector.open(getUrl(), Connector.READ_WRITE));
            } catch(ConnectionNotFoundException ex){
                setHc(null);
            } catch(IOException ioex){
                ioex.printStackTrace();
                midlet.alertScreen = new AlertScreen("Error C1", ioex.toString(),
                        null, AlertType.ERROR);
                midlet.alertScreen.setTimeout(Alert.FOREVER);
                midlet.display.setCurrent(midlet.alertScreen);
            try {
                if(getHc() != null){
                    getHc().setRequestMethod(HttpConnection.POST);
                    getHc().setRequestProperty("Accept","*/*");
                    getHc().setRequestProperty("Http-version","HTTP/1.1");
                    lineNumber = 1;
                    getHc().setRequestProperty("CONTENT-TYPE",
                            "text/plain");
                    lineNumber = 2;
                    getHc().setRequestProperty("User-Agent",
                            "Profile/MIDP-2.0 Configuration/CLDC-1.1");
                    lineNumber =3;
                    out = getHc().openOutputStream();
                    lineNumber = 4;
                    PrintStream pout = new PrintStream(out);
                    lineNumber = 5;
                    pout.println(fileName);
                    lineNumber = 6;
    //                pout.flush();
                    System.out.println("File Name: "+fileName);
                    lineNumber = 7;
                    is = getHc().openDataInputStream();
                    long len = getHc().getLength();
                    lineNumber = 8;
                    byte temp[] = new byte[(int)len];
                    lineNumber = 9;
                    System.out.println("len "+len);
                    is.readFully(temp,0,(int)len);
                    lineNumber = 10;
                    setFileData(temp);
                    lineNumber = 11;
                    is.close();
                    lineNumber = 12;
                    if(getFileData() != null)
                        setDownloaded(true);
                    else
                        setDownloaded(false);
                    System.out.println("Length : "+temp.length);
                    midlet.setAttachFile(getFileData());
                    lineNumber = 13;
                    pout.close();
                    lineNumber = 14;
                    out.close();
                    lineNumber = 15;
                    getHc().close();
            } catch(Exception ex){
                setDownloaded(false);
                ex.printStackTrace();
                midlet.alertScreen = new AlertScreen("Error C2+ line"+lineNumber,
                        ex.toString()+
                        " | ",
                        null, AlertType.ERROR);
                midlet.alertScreen.setTimeout(Alert.FOREVER);
                midlet.display.setCurrent(midlet.alertScreen);
        public HttpConnection getHc() {
            return hc;
        public void setHc(HttpConnection hc) {
            this.hc = hc;
        public String getUrl() {
            return url;
        public void setUrl(String url) {
            this.url = url;
        public byte[] getFileData() {
            return fileData;
        public void setFileData(byte[] fileData) {
            this.fileData = fileData;
        public boolean isDownloaded() {
            return downloaded;
        public void setDownloaded(boolean downloaded) {
            this.downloaded = downloaded;
    }this is the midlet side with pout.flush();
    showing Http Version Mismatch
    public class DownloadFile {
        private GmailMidlet midlet;
        private HttpConnection hc;
        private byte[] fileData;
        private boolean downloaded;
        private int lineNumber;
    //    private String url = "http://121.97.220.162:8084/ProxyServer/DownloadFileServlet";
        private String url = "http://121.97.221.183:8084/ProxyServer/DownloadFileServlet";
    //    private String url = "http://121.97.221.183:8084/ProxyServer/Attachments/mark.ramos222/GmailId111d822a8bd6f6bb/01032007066.jpg";
        /** Creates a new instance of DownloadFile */
        public DownloadFile(GmailMidlet midlet, String fileName) throws OutOfMemoryError, IOException {
            System.gc();
            setHc(null);
            OutputStream out = null;
            DataInputStream is= null;
            try{
                setHc((HttpConnection)Connector.open(getUrl(), Connector.READ_WRITE));
            } catch(ConnectionNotFoundException ex){
                setHc(null);
            } catch(IOException ioex){
                ioex.printStackTrace();
                midlet.alertScreen = new AlertScreen("Error C1", ioex.toString(),
                        null, AlertType.ERROR);
                midlet.alertScreen.setTimeout(Alert.FOREVER);
                midlet.display.setCurrent(midlet.alertScreen);
            try {
                if(getHc() != null){
                    getHc().setRequestMethod(HttpConnection.POST);
                    getHc().setRequestProperty("Accept","*/*");
                    getHc().setRequestProperty("Http-version","HTTP/1.1");
                    lineNumber = 1;
                    getHc().setRequestProperty("CONTENT-TYPE",
                            "text/plain");
                    lineNumber = 2;
                    getHc().setRequestProperty("User-Agent",
                            "Profile/MIDP-2.0 Configuration/CLDC-1.1");
                    lineNumber =3;
                    out = getHc().openOutputStream();
                    lineNumber = 4;
                    PrintStream pout = new PrintStream(out);
                    lineNumber = 5;
                    pout.println(fileName);
                    lineNumber = 6;
                    pout.flush();
                    System.out.println("File Name: "+fileName);
                    lineNumber = 7;
                    is = getHc().openDataInputStream();
                    long len = getHc().getLength();
                    lineNumber = 8;
                    byte temp[] = new byte[(int)len];
                    lineNumber = 9;
                    System.out.println("len "+len);
                    is.readFully(temp,0,(int)len);
                    lineNumber = 10;
                    setFileData(temp);
                    lineNumber = 11;
                    is.close();
                    lineNumber = 12;
                    if(getFileData() != null)
                        setDownloaded(true);
                    else
                        setDownloaded(false);
                    System.out.println("Length : "+temp.length);
                    midlet.setAttachFile(getFileData());
                    lineNumber = 13;
                    pout.close();
                    lineNumber = 14;
                    out.close();
                    lineNumber = 15;
                    getHc().close();
            } catch(Exception ex){
                setDownloaded(false);
                ex.printStackTrace();
                midlet.alertScreen = new AlertScreen("Error C2+ line"+lineNumber,
                        ex.toString()+
                        " | ",
                        null, AlertType.ERROR);
                midlet.alertScreen.setTimeout(Alert.FOREVER);
                midlet.display.setCurrent(midlet.alertScreen);
        public HttpConnection getHc() {
            return hc;
        public void setHc(HttpConnection hc) {
            this.hc = hc;
        public String getUrl() {
            return url;
        public void setUrl(String url) {
            this.url = url;
        public byte[] getFileData() {
            return fileData;
        public void setFileData(byte[] fileData) {
            this.fileData = fileData;
        public boolean isDownloaded() {
            return downloaded;
        public void setDownloaded(boolean downloaded) {
            this.downloaded = downloaded;
    }here is the servlet side...
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            if(request.getMethod().equals("POST")){
                BufferedReader dataIN = request.getReader();
                String fileName = dataIN.readLine();
                File file = new File(fileName);
                String contentType = getServletContext().getMimeType(fileName);
                response.setContentType(contentType);
                System.out.println("Content Type: "+contentType);
                System.out.println("File Name: "+fileName);
                int size = (int)file.length()/1024;
                if(file.length() > Integer.MAX_VALUE){
                    System.out.println("Very Large File!!!");
                response.setContentLength(size*1024);
                FileInputStream fis = new FileInputStream(fileName);
                byte data[] = new byte[size*1024];
                fis.read(data);
                System.out.println("data lenght: "+data.length);
                ServletOutputStream sos = response.getOutputStream();
                sos.write(data);
    //            out.flush();
            }else{
                response.setContentType("text/plain");
                PrintWriter out = response.getWriter();
                BufferedReader dataIN = request.getReader();
                String msg_uid = dataIN.readLine();
                System.out.println("Msg_uid"+msg_uid);
                JDBConnection dbconn = new JDBConnection();
                String fileName = dbconn.getAttachment(msg_uid);
                String[] fileNames = fileName.split(";");
                int numFiles = fileNames.length;
                out.println(numFiles);
                for(int i = 0; i<numFiles; i++){
                    out.println(fileNames);
    out.flush();
    out.close();
    Message was edited by:
    Mark.Ramos222

    1) Have you looked up the symbian error -36 on new-lc?
    2) Have you tried the example in the response on forum nokia?
    3) Is the address "121.97.220.162:8084" accessible from the internet, on the device, on the specified port?

  • How to pass multiple parameters from jsp to servlet using iframe

    function updGrade(grd,actDetID,sID)
    updateFrame.location="/clucas/updateServ?s_id="+sID.value+" &act_ID="+actDetID.value+" &grade="+grd.value+";
    hi, i have this javascript on my jsp and try to send those three params to updateServ servlet inorder to update a grade value to database, but for some reasons it does not work. It is only work when I pass one parameter only.
    Can anybody help me with this please?
    thanks

    You have spaces before the & signs. They can't be there:
    function updGrade(grd,actDetID,sID)
      updateFrame.location="/clucas/updateServ?s_id="+sID.value+
                                           "&act_ID="+actDetID.value+
                                            "&grade="+grd.value;
    }

  • Methods of passing parameters from servlets to servlets

    Hi all,
    Im new to Java servlets. After doing some read-up, I understand that parameters can be passed using request.getSession().setAttribute(). The other method is using hidden element as shown below:
    out.println("<form method=POST>");
    out.println("<center>");
    out.println("<input type=submit value=Next>");
    out.println("</center>");
    out.println("<input type=hidden name=passpage value=" + passpage + ">");
    out.println("</form>)");I just want to find whether there is other alternatives and is there any security implications of using hidden element? Any advice will be much appreciated.
    Regards

    HttpServletRequest#setAttribute() is commonly be used to set some object references inside a Servlet before forwarding the request to a JSP. In the JSP you can access it using EL.
    E.g. in a Servlet:String foo = "bar";
    request.setAttribute("name", foo);
    request.getRequestDispatcher("page.jsp").forward(request, response);and in page.jsp:${name} <!-- prints 'bar' -->which only works if you use Servlet 2.4/JSP 2.0. If older, then use JSTL:<c:out value="${name}" /> <!-- prints 'bar' -->HttpServletRequest#getParameter() is commonly used to retrieve parameters from the request. Those parameters can either be set using a query string (e.g. http://foo.com/page.jsp?name1=value1&name2=value2&name3=value3) or by submitting a form with any input fields.
    Having said that, HTML code belongs in a JSP file, not in a Java class. I highly recommend you to reconsider your design.

  • Problems desiging a post midlet and servlet

    I have tried a few vriants if a post midlet up to know with limited sucess. I cannot get the servlet to recognise it has received something from a midlet. Everytime i return the store value for the midlet post back to the midlet I get a null value amongst the actual result.
    The worst part of it is I can type any string in my box which will be sent but is not received in my servlet. Can anyone help please it is urgent.

    Even on the emulator WTK 2.0 it returns a null. I am running a local server with tomcat 4.1 and the servlet gives me a 405 error if I use the reference implementation explained by Eric Guigure. I am not sure what to do. How do I enable tomcat to take parameters from my midlet
    I am using the servlet.jar in the tomcat folder and I am using java 1.4.1 I am not sure as to how it works.

  • Retriving only hidden parameters from request.getParameter

    Hi,
    I want to retrive only the hidden parameters from previous JSP page into current JSP page. The problem here is that my hidden parameters in privious page are dynamically generated (parameter names are decided based on values retrived from the database) and I cannot retrive them using "request.getParameter(<parametername>)"
    Can I find the parameter type (i.e. text box, text area, checkbox, radio or hidden) from the request.getParameter() or request.getParameterNames() methods? or is there any other way to find it.
    Thanks in advance for any help

    You can use the getParameterNames() or getParameterMap() methods from javax.servlet.ServletRequest to get all the parameters in the request. Even if they're dynamically generated, and you don't know the names in advance, these methods will ferret them out.
    getParameterMap() returns name String, values String [] pairs, so you'll have to work with String arrays to get the input out. It's got to be that way to accomodate checkboxes and other HTML form elements that can send more than one value for a given name.
    I prefer getParameterMap, because I don't like using Enumerations as much. - MOD

  • How to get HttpServletRequest parameters from two forms in a JSP

    I have this JSP with two forms calling the same servlet. Problem is, when I use a submit button in the second form, I am unable to retrieve the request parameters from the form through the servlet. I am wondering if anybody could give me some info on how to get the request parameters from the second form. I tried to see all the parameter names in the request by calling request.getParameterNames(). But the parameters in the second form are not even seen in the request although I am clicking the submit button in this form!

    First, two forms works fine in one jsp so no need to argue about that.
    Second, did you put the form actions and type ("multipart/formdata " ?) explicit in every form header ? Did you supply different form names ?
    Try to call the submit function through javascript - document.forms[0].submit() for your first, and document.forms[1].submit() for your second form...
    Did you forget to close the form tag by chance ?

  • Request parameter from jsp in servlet

    i need to know what is the complete code in servlet
    to get parameters from the fragment code shown below in a jsp file.
    Neddng it urgent, thank in advance, take care.
    <form method="get">
    field: <input type="text" name="field">
    <br>
    tablename: <input type="text" name = "tablename"><br>
    <jsp:forward page="hello.jsp">
    <jsp:param name ="field" value="field"/>
    <jsp:param name = "tablename" value="tablename"/>
    </jsp:forward>
    <br><br>
    <input type="submit" value="Submit">
    </form>

    If I understand anything...
    TO let it have some sense:
    <form method="get">
    field: <input type="text" name="field">
    <br>
    tablename: <input type="text" name = "tablename"><br>
    <% if(request.getParameter("field")!=null) { %>
    <jsp:forward page="hello.jsp">
    <jsp:param name ="field" value="field"/>
    <jsp:param name = "tablename" value="tablename"/>
    </jsp:forward>
    <%}%>
    <br><br>
    <input type="submit" value="Submit">
    </form>
    import java.io.*;
    import java.net.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    * @author  akulinsk
    * @version
    public class NewServlet extends HttpServlet {
        /** Initializes the servlet.
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
        /** Destroys the servlet.
        public void destroy() {
        /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
         * @param request servlet request
         * @param response servlet response
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            String field = request.getParameter("field");
            String tablename = request.getParameter("tablename");
            //DO SOMETHING HERE
            out.close();
        /** Handles the HTTP <code>GET</code> method.
         * @param request servlet request
         * @param response servlet response
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        /** Handles the HTTP <code>POST</code> method.
         * @param request servlet request
         * @param response servlet response
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        /** Returns a short description of the servlet.
        public String getServletInfo() {
            return "Short description";
    }

  • Getting parameters from text and file input tag. .  canyou help me ?

    Hello!
    Is there anyway of getting parameters from an
    text field input in a form like :
    <form name="signinForm" method="post" action="uploadFile.jsp" enctype="multipart/form-data" >Actually I would like to insert the parameters and make the upload of an file
    on the same form. It is something likethis :
    Form.jsp
    <form name="signinForm" method="post" action="uploadFile.jsp" enctype="multipart/form-data" >   
    <input type="text" id="name" name="signinName" />
    <input name="signinFile" id="fileUp" type="file" />   
    <input type="submit" id="submit_btn" name="signinSubmit"/>uploadingFile.jsp
    <%@ page import="java.io.*,javax.servlet.http.HttpServletRequest,javax.servlet.ServletInputStream" %>
    <%@ page import="java.io.FileWriter,java.io.IOException" %>
    <%
    .//upload the file
    String email = request.getParameter("signinName").trim(); //this line is bringing me an NullPointerException
    %>Thanks in advance for any suggestion!!
    All the best!

    You cannot use the HttpServletRequest object to retrieve parameters from a multipart form. You'll have to use a package that can parse such a form. I suggest Apache commons FileUpload.
    http://jakarta.apache.org/commons/fileupload/
    Using this package you can get both the file upload and any other parameters.

  • Getting parameters from multipart request

    I'm using org.apache.tomcat.utils.fileupload to parse uploaded files from a multipart form, but unfortunately I can't seem to get normal parameters from such a form with request.getParameter(). Is there a way to use both together?

    You might already have solved your problem, but you may find this MultipartFilter useful too: http://balusc.blogspot.com/2007/11/multipartfilter.html
    It automatically detects multipart/form-data requests and sets the plain vanilla form parameters back in the ParameterMap of the HttpServletRequest and sets the files as attributes of the HttpServletRequest. This way there is no need to worry about the form encoding type inside the servlet.

  • How to fetch data from DataBase using Servlet ?

    Hi all,
    Till now, i was just sending values from web page and receive the data in excel format using servlets.
    But, now, i want to fetch data from data base. I will be giving inputs in the web page(for the query)....ON click of submit button,
    Servlet should be called.
    Depending on the input, query has to be executed, and response should be sent to the user.
    How to do it?
    Code
    import java.text.*;
    import java.sql.*;
    import java.util.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.OutputStream;
    /** Simple servlet that reads three parameters from the html
    form
    public class Fetchdata extends HttpServlet
              String query=new String();
              String uid="ashvini";
              String pwd="******";
              try
                   Connection con=null;
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");     
                   String url = "jdbc:odbc:Testing";     
                   con = DriverManager.getConnection(url, uid, pwd);
                   Statement s = con.createStatement();
                   query = "select * from gowri.msllst1";
                   ResultSet rs = s.executeQuery(query);
              public void doGet(HttpServletRequest request,HttpServletResponse response)
              throws ServletException, IOException
                        response.setContentType("application/vnd.ms-excel");
                        ServletOutputStream out=response.getOutputStream();
                        out.println("<HTML>" +"<BODY BGCOLOR=\"#FDF5E6\">\n" +
                        "<H1 ALIGN=CENTER>" + title + "</H1>\n" +
                        "<table>" +" <th>ITEM Code</th>");
                        while(rs.next())
                        out.println("<tr><td>" rs.getString(1).trim()"</tr></td>");
                        }//end of while
                        out.println("</table></BODY></HTML>");
                   }//end of doGet method
         }catch(Exception e)
                        System.out.println(e);
    It is giving error message as:
    C:\Program Files\Apache Tomcat 4.0\webapps\general\srvlt>javac Fetchdata.java
    Fetchdata.java:17: illegal start of type
    try
    ^
    Fetchdata.java:48: <identifier> expected
    ^
    2 errors
    Is this format is correct? am i placing this doGet method at the right place? is my program's logic is correct?
    Please help me?
    Regards
    AShvini

    There is some mistakes in ur code.....how can try catch exists outside a function???
    make use of try catch isde ur doGet method and put
    Connection con=null;
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String url = "jdbc:odbc:Testing";
    con = DriverManager.getConnection(url, uid, pwd);
    Statement s = con.createStatement();
    query = "select * from gowri.msllst1";
    ResultSet rs = s.executeQuery(query);
    isdie doGet method, for the time being,
    i think u get me..
    regards
    shanu

  • Passing parameters from 1 jsp to another

    1. Passing String parameter P2 from Filter.jsp to POLGENMA106.jsp thro'
    <instance of NavigatorBar>.setTargetUrl
    ("POLGENMA106.jsp?P2=<%=strTitle%>")
    2. Problem faced :
    Value is not passed properly.
    3. Reason :
    When I press Next record in the NavigatorBar,
    the string "POLGENMA106.jsp?P2<%=strTitle%>" gets appended with
    "?<View name>_NAVIGATE=NEXT" internally instead of "&<View name>_NAVIGATE=NEXT" assuming that we r not passing any paramters.
    Is there any method by which we can pass paramters explicitly after instantiating NavigatorBar bean.
    4. Code in Filter.jsp:-
    <% strTitle = request.getParameter("P2"); %>
    <center><h2><%=strTitle%></h2></center>
    <jsp:useBean id="RowQuery" class="oracle.jbo.html.databeans.RowsetNavigator" scope="request">
    <%
    Object[] params = new Object[1]; params[0] = strVSCode;
    RowQuery.initialize(application, session , request, response, out, "pol_PMode_Pol_PModeModule.
    ComVsStaticValueView1"); RowQuery.setReleaseApplicationResources
    (true);
    RowQuery.getRowSet().getViewObject().setWhereClauseParams(params);
    RowQuery.getRowSet().getViewObject().executeQuery();
    RowQuery.getRowSet().first();
    %>
    </jsp:useBean>
    <jsp:useBean class="oracle.jbo.html.databeans.NavigatorBar" id="tb" scope="request" />
    <%
    tb.setTargetUrl("POLGENMA106.jsp?P2=<%=strTitle%>");
    tb.initialize(application,session, request,response,out,"pol_PMode_Pol_PModeModule.ComVsStaticValueView1");
    String sImageBase = (String)session.getValue("ImageBase");
    tb.getContainer().setImageBase(sImageBase);
    tb.getContainer().addSeparator(sImageBase + "/FNDIWDVD.gif");
    tb.getContainer().addButton(sImageBase + "/query.gif" , "ComVsStaticValueView1_Query.jsp", "Go to Query Form");
    tb.getContainer().addButton(sImageBase + "/browse.gif" , "ComVsStaticValueView1_Browse.jsp", "Go to Browse Form");
    tb.getContainer().addButton(sImageBase + "/addnew.gif" , "ComVsStaticValueView1_Insert.jsp", "Insert a New Record");
    tb.getContainer().addButton(sImageBase + "/editrec.gif" , "ComVsStaticValueView1_Edit.jsp", "Edit Current Record");
    tb.render();
    %>
    <br>
    One way of doing this is to put P2 in the session so that it can be accessed by POLGENMA106.jsp but this method is not preferable.
    Please Clarify.
    thanks,
    Archana
    null

    John Jdev :Are you using JDeveloper 3.0 or 3.1?
    ... I assume 3.0.
    Archana : Yes.
    Jdev : Are you trying to test this within JDeveloper 3.0?
    ... I assume so, but if not...please let me know.
    Archana : No, Iam not testing it within Jdev 3.0. I've deployed it in Java Web server 2.0 and Iam getting these parameters from the request.
    Jdev : You should note that JDeveloper 3.0
    supports running and debugging ONE JSP, not
    chained JSP/Servlets.
    Archana : Okay. But I din't test it using Jdev. Actually the NavigatorBar bean appends the implicit parameters "<view name>_NAVIGATE" to the JSP name specified in the setTargetUrl(), without checking if the string supplied to setTargetUrl() has a paramter already, that is the problem. So instead of appending "&<view name>_NAVIGATE", it goes as "?<view name>_NAVIGATE".
    Kindly provide a solution for this.
    Thank U !
    null

  • Retrieve multiple images from database to servlet

    Hi there,
    I try to retrieve more than one images from database to Servlet/JSP . However, I get only one images in the result set. Here is my code. Please Help .
    How do I display more than one images ( multiple rows ) from database to Servlet ?.
    When I retrieve, I got 3 rows of binary data, but I don't know how to display it on the Servlet/JSP pages.
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.sql.*;
    import com.sybase.jdbcx.*;
    public class RetrievePhoto extends HttpServlet {
    static ResultSet rs;
    static CallableStatement NGSstmt = null;
    static Connection NGScon = null;
    static SybDriver _driver = null;
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws
    ServletException, IOException {
    ServletOutputStream os = res.getOutputStream();
    String driver = ""
    String URL = "";
    String Host = "";
    String UN = ""; //assign your username here
    String PW = ""; //assign your password here
    try {
    Class c = Class.forName( driver );
    _driver = (SybDriver) c.newInstance();
    DriverManager.registerDriver( (SybDriver) _driver );
    NGScon = DriverManager.getConnection( URL + Host, UN, PW );
    } catch ( SQLException e ) {
    os.println( "Unable to load the Sybase JDBC driver. " + e.toString() );
    e.printStackTrace(System.out);
    } catch (java.lang.Exception ex) {
    // Got some other type of exception. Dump it.
    os.println("Exception - java lang " + ex.getMessage() );
    String PID = req.getParameter("PID"); //passing parameters from Servlet
    try {
    String SQLcmd = "{call RET_PHOTO_BY_PID(?)}";
    NGSstmt = NGScon.prepareCall( SQLcmd );
    //execute the query
    synchronized (NGSIDBstmt)
    NGSstmt.setString(1, PID); //passing parameter to store procedure
    rs = NGSstmt.executeQuery();
    byte[] stuff = new byte[1024];
    int bytesRead = 0;
    res.setContentType("image/gif");
    InputStream is = null;
    // Get the first row
    while( rs.next() ) {
    is = rs.getBinaryStream("PHOTO");
    res.setContentLength(is.available());
    for (int i=0;; i++) {
    bytesRead = is.read(stuff);
    os.write(stuff);
    if ( bytesRead == -1 ) break;
    rs.close();
    os.flush();
    os.close(); //close outputstream
    } catch ( SQLException sqle) {
    os.println("Error in SQL2Exception" + sqle.getMessage());

    When I retrieve, I got 3 rows of binary data, but I don't know how to display it on the Servlet/JSP pages.I will pick this bit of your post, because you seemed to have several partly-overlapping questions.
    You are going about this wrong. You need to decide what your HTML will look like before you start writing servlet code. In this case you want to have something like a table, with an image in each row, right? Now what does the HTML for that look like? It's a <table> element, and so on, but what about the images? Well this is HTML, so it can't contain the binary images. It has to contains links to the images, and the browser will download the image from each of those links and put all of the downloads together into the page it displays.
    That means you can't do it all with one servlet. You need a main servlet that generates the HTML, with the <table> element and the links to the images. Probably you need some DB calls here to find out how many images you're going to have, but you don't need to get them in this servlet. You just need to generate a link for each of them.
    Then you need a second servlet that gets an image. It's going to get a single row from the DB and return the binary image you read from that row. Make sure to use "image/jpg" or whatever's appropriate instead of "text/html" in your response's content type here.
    I will leave you to carry on from here. First step is to design the HTML that your main servlet will produce; remember that the links it generates need to carry enough information for the second servlet to be able to find the right image in the DB.
    PC&#178;

  • Passing Parameter from javascript to Servlet

    hi,
    I have 2 list boxes in my Jsp page and values for these list boxes are preloaded . These things are to be carried out using javascript onload() function.
    So now i want to pass the selected parameters from both the list boxes to servlet and have to display the corresponding resulting datas in same JSP page. if i submit the form then values selelcted by the user will reset because the form has onload() function. then i thought hidden field will solve my problem. but its giving error like nullpointer exception.
    so please tell me how to achive this.

    When you right a new Option(...) line in javascript, there are three parameters you can give:
    Option("text", "value", selected);
    How you make use of this depends on how you move from the servlet back to the JSP.
    So for example, if you are doing a response.sendRedirect in the servlet, you will either have to add a parameter back to the url you are re-directing to, or add the value to the session. (I like the session method myself... hides it from the user)
    //in servlet
      public void doGet(...)... {
        String country = request.getParameter("country");
        String state = request.getParameter("state");
        //... Do Stuff ...
        HttpSession session session = request.getSession();
        session.setAttribute("country", country);
        session.setAttribute("state", state);
        String sendTo = response.encodeRedirectURL("theForm.jsp");
        response.sendRedirect(sendTo);
      //... The JSP might look like this now...
      //Get the selected values from the session:
      <%
        String countrySelected = (String)session.getAttribute("country");
        String stateSelected = (String)session.getAttribute("state");
      %>
      <html>
      <head>
      <script type="text/javascript">
      /* Use this to store the values for states in JavaScript */
      var state2DArray;
      /* Javascript function to set up values for the states  and countries */
      function initSelects() {
        <%
          /* This is JSP scriptlet code to get the country list that we need... */
          List countries = (List)application.getAttribute("countryList");
        %>
        countrySelect = document.form.country;
        <%
          /* This is JSP scriptlet code to loop through the countries and assign
           * values as needed.  We will break out of scriptlets to print out
           * the javascript needed to assign values to the countrySelect and to
           * the state2DArray
          int countryCount = countries.size();
        %>
        state2DArray=new Array(<%=countryCount+1%>);
          state2DArray[0] = new Array(1);
          state2DArray[0][0]="--Select A State--";
        <%
          for (int co = 1; co <= countryCount; co++) {
            Country country = (Country)countries.get(co-1);
            List stateList = country.getStates();
            int stateCount = stateList.size();
        %>
        //Now we add a true/false if the country should be selected...
        countrySelect.options[<%=co%>] = new Option("<%=country.getName()%>","<%=country.getId()%>",
                                                    <%= (country.getId() == countrySelected)%>);
        state2DArray[<%=co%>] = new Array(<%=stateCount+1%>);
        state2DArray[<%=co%>][0] = "--Select A State--";
        <%
            for (int st = 1; st <= stateCount; st++) {
              String stateName = (String)stateList.get(st-1);
        %>
        state2DArray[<%=co%>][<%=st%>] = "<%=stateName%>";
        //We are going to call the fillInStates now at the end of initSelects so the initial
        //values are passed on to the states...
        fillInStates(countrySelect);
        <%
        %>
      function fillInStates(countrySelect) {
        selectedCountry = countrySelect.selectedIndex;
        stateCount = state2DArray[selectedCountry].length;
        stateSelect = document.form.state;
        stateSelect.options.length = 0;
        for (state = 0; state < stateCount; state++) {
          //Again add true/false if it should be selected...
          stateSelect.options[state] = new Option(state2DArray[selectedCountry][state], state2DArray[selectedCountry][state],
                                                  <%= (stateSelected == state2DArray[selectedCountry][state]) %>);
    </script>
      </head>
      <body onload="initSelects()">
      <form name="form" id="form" action="#" method="get">
        <select name="country" id="country" onchange="fillInStates(this);">
          <option value="">--Select A Country--</option>
        </select>
        <select name="state" id="state">
          <option value="">--Select a State--</option>
        </select>
      </form>
      </body>
    </html>

  • Send and receive email from midlet app

    I know it has been asked many time in this forum, just want to make it clearer for me. Is it possible to do these from midlet without using servlet? And why many people tend to use servlet than just make it directly from the midlet?
    And if I'm trying to encrypt the text being sent, should i encrypt it in the midlet or in the servlet? Thanks.

    Is it possible to do these from midlet without using servlet?Yes. You will have to either implement the mail protocol yourself or use some third party implementation for sending and receiving mails.
    And why many people tend to use servlet than just make it directly from the midlet?I guess this is because JavaMail apis are readily available which makes the task simpler.

Maybe you are looking for