Showing posts with label Servlet. Show all posts
Showing posts with label Servlet. Show all posts

Tuesday, 10 January 2012

Send text to servlet and get response code from servlet

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;
import java.util.Vector;

public class MidletServlet extends MIDlet implements CommandListener {
Display display = null;
Form form = null;
TextField tb = null;
String str = null;
String url = "http://localhost:8080/servlets-examples/servlet/getText";
Command backCommand = new Command("Back", Command.BACK, 0);
Command submitCommand = new Command("Submit", Command.OK, 2);
Command exitCommand = new Command("Exit", Command.STOP, 3);
private Test test;

public MidletServlet() {}

public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
form = new Form("Request Servlet");
tb = new TextField("Please input text: ","",30,TextField.ANY );
form.append(tb);
form.addCommand(submitCommand);
form.addCommand(exitCommand);
form.setCommandListener(this);
display.setCurrent(form);
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == backCommand) {
display.setCurrent(form);
} else if (c == submitCommand) {
str = tb.getString();
test = new Test(this);
test.start();
test.getServlet(str);
}
}


class Test implements Runnable {
MidletServlet midlet;
private Display display;
String text;

public Test(MidletServlet midlet) {
this.midlet = midlet;
display = Display.getDisplay(midlet);
}

public void start() {
Thread t = new Thread(this);
t.start();
}

public void run() {
StringBuffer sb = new StringBuffer();
try {
HttpConnection c = (HttpConnection) Connector.open(url);
c.setRequestProperty(
"User-Agent","Profile/MIDP-1.0, Configuration/CLDC-1.0");

c.setRequestProperty("Content-Language","en-US");
c.setRequestMethod(HttpConnection.POST);

DataOutputStream os =
(DataOutputStream)c.openDataOutputStream();

os.writeUTF(text.trim());
os.flush();
os.close();

// Get the response from the servlet page.
DataInputStream is =(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
}
showAlert(sb.toString());
is.close();
c.close();
} catch (Exception e) {
showAlert(e.getMessage());
}
}
/* This method takes input from user like text and pass
to servlet */
public void getServlet(String text) {
this.text = text;
}

/* Display Error On screen*/
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
};
}
import java.io.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class getText extends HttpServlet {

public void init() {
}

public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {

DataInputStream in =
new DataInputStream((InputStream)request.getInputStream());

String text = in.readUTF();
String message;
try {
message = "100 ok";
} catch (Throwable t) {
message = "200 " + t.toString();
}
response.setContentType("text/plain");
response.setContentLength(message.length());
PrintWriter out = response.getWriter();
out.println(message);
in.close();
out.close();
out.flush();
}

public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {

doPost(request,response);
}
}


Mohammad Abu Hmead
10.01.2012 11:08 AM

Send text to servlet and get response code from servlet

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;
import java.util.Vector;

public class MidletServlet extends MIDlet implements CommandListener {
Display display = null;
Form form = null;
TextField tb = null;
String str = null;
String url = "http://localhost:8080/servlets-examples/servlet/getText";
Command backCommand = new Command("Back", Command.BACK, 0);
Command submitCommand = new Command("Submit", Command.OK, 2);
Command exitCommand = new Command("Exit", Command.STOP, 3);
private Test test;

public MidletServlet() {}

public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
form = new Form("Request Servlet");
tb = new TextField("Please input text: ","",30,TextField.ANY );
form.append(tb);
form.addCommand(submitCommand);
form.addCommand(exitCommand);
form.setCommandListener(this);
display.setCurrent(form);
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == backCommand) {
display.setCurrent(form);
} else if (c == submitCommand) {
str = tb.getString();
test = new Test(this);
test.start();
test.getServlet(str);
}
}


class Test implements Runnable {
MidletServlet midlet;
private Display display;
String text;

public Test(MidletServlet midlet) {
this.midlet = midlet;
display = Display.getDisplay(midlet);
}

public void start() {
Thread t = new Thread(this);
t.start();
}

public void run() {
StringBuffer sb = new StringBuffer();
try {
HttpConnection c = (HttpConnection) Connector.open(url);
c.setRequestProperty(
"User-Agent","Profile/MIDP-1.0, Configuration/CLDC-1.0");

c.setRequestProperty("Content-Language","en-US");
c.setRequestMethod(HttpConnection.POST);

DataOutputStream os =
(DataOutputStream)c.openDataOutputStream();

os.writeUTF(text.trim());
os.flush();
os.close();

// Get the response from the servlet page.
DataInputStream is =(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
}
showAlert(sb.toString());
is.close();
c.close();
} catch (Exception e) {
showAlert(e.getMessage());
}
}
/* This method takes input from user like text and pass
to servlet */
public void getServlet(String text) {
this.text = text;
}

/* Display Error On screen*/
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
};
}
import java.io.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class getText extends HttpServlet {

public void init() {
}

public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {

DataInputStream in =
new DataInputStream((InputStream)request.getInputStream());

String text = in.readUTF();
String message;
try {
message = "100 ok";
} catch (Throwable t) {
message = "200 " + t.toString();
}
response.setContentType("text/plain");
response.setContentLength(message.length());
PrintWriter out = response.getWriter();
out.println(message);
in.close();
out.close();
out.flush();
}

public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {

doPost(request,response);
}
}


Mohammad Abu Hmead
10.01.2012 11:08 AM

Thursday, 21 July 2011

Creat Servlet and Connect it to MS SQL server


1) Install Netbeans 6.9 or later
2) Download GlassFish from this site
install GlassFish, it will run easy
3) Run NetBeans IDE and view Services window 


Right Click on servers the click on "add server.."

Type instead of x the version of the GlassFish you want to add
the press Next and type the link of the GlassFish installation folder 
press Next and Select the domain and press Finish
** Now your GlassFish Created 

4) Now you have to start the server by right click on GlassFish 3.1 and click start 
if the server didn't  start the solution is bellow

5) Creating GlassFish Domain
open your  glass fish directory and open bin folder 
double click on "asadmin" it will run and type "domain" then an error list will shown like the figure bellow 

never mind, just I want to show you how you can get correct commands 
now type "create-domain domain2" and wait for response 

back to netbeans and repeat step 3 but choose domain2 and run the server

---------------------------------------------
Now we want to configure MSSQL server
1) install SQL server 2005 or later
2) Create your DB with windows authentications 
3) Create new user with Sql authentications with password and select the DB to be shown to this user 
4) Go to DB and right Click and choose properties and press on Permissions and select the user and check all CheckBoxes under Grant Header like the figure bellow 

5) Now you want to know the port number on which the SQL server listen to
by doing like the two figures bellow

from the previous figure you can get the port.


-------------------------------------------
Now Creating Servlet 

1) Run Netbeans and press on "File" tab and press on "New Project" 
2) Select Java Web from Categories and Web Application from Projects
3) Type your project name and directory and the libraries directory 
4) Choose GlassFish and JEE 
5) Do like the figure bellow (let all of them empty)

Click finish, now you have a web project

*** Creating Servlet
on project name right click and select  new Servlet
Do like the bellow two figures 



Press finish and edit the 

Add the sql db driver into libraries 
downloadable from this site http://www.mediafire.com/?3ycmaelhoot

Look at the example bellow

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.servlet.annotation.WebServlet;

/**
 *
 * @author Mohammad
 */
//this to call the servlet from an ip address
//http://ipaddress:port/defaultSite/ServletCallableName

@WebServlet(name = "ServletCallableName", urlPatterns = {"/ServletCallableName"})

public class NewServlet extends HttpServlet {

    private Connection conn;
    private PrintWriter printWriter;
    private StringBuffer stringBuffer;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String ua = request.getHeader("User-Agent");      

        stringBuffer = new StringBuffer();
       
            CallableStatement callableStatment = null;

            try {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;"//1433 sql port look at    
//figures bellow
                        + "databaseName=WhoWantsToBeMillionaireQs;user=mohammad;password=moh");

                callableStatment = conn.prepareCall("{call get_rando_rows(?)}");//call get_rando_rows: procedure name created on Sql serve DB, takes one parameter, the procedure runs 3 select statments and returns 3 results as three tables 
                callableStatment.setString("Count", "5");//the procedure parameter 

                boolean isExecuted = callableStatment.execute();//to execute the query 

                int rsCount = 0;
                try {

                    do {
                        if (isExecuted) {
                            ResultSet rs = callableStatment.getResultSet();
                            rsCount++;

                            ResultSetMetaData rsmd = rs.getMetaData();
                            int numOfColumns = rsmd.getColumnCount();
                            while (rs.next()) {
                                for (int i = 1; i <= numOfColumns; i++) {
                                    stringBuffer.append(rs.getString(i));
                                    stringBuffer.append("|#|");
                                }
                            }
                            rs.close();
                            System.out.println();
                            isExecuted = callableStatment.getMoreResults();
                        }
                    } while (isExecuted);
                    callableStatment.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } catch (SQLException ex) {
                stringBuffer.append("  SQL Exception.  ");
                stringBuffer.append(ex.getMessage());
            } catch (ClassNotFoundException cex) {
                stringBuffer.append("  Class Not Found Exception  ");
                stringBuffer.append(cex.getMessage());
            } catch (Exception ex) {
                stringBuffer.append("Unknown Exception  ");
                stringBuffer.append(ex.getMessage());

            }
       
        response.setContentType("text/plain");
        printWriter = response.getWriter();
        printWriter.print(stringBuffer.toString());
        printWriter.close();

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    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
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}


Mohammad Abu Hmead 
Palestine 
21.07.2011
01:43 AM