Servlet-HTML connection

I'm having some problems connecting html to a servlet. Im currently at my university and under my own root, the servlet is under /booksonline/html/servlet. the html code looks like this
<tr>
<FORM ACTION="http://localhost:8080/BooksOnline/HTML/servlet.MyServlet" METHOD=POST>
<td valign="center"><B>Login Name: </B></td>
<td valign="center"><input type="text" name="LoginName" size="50" maxlength="50" value=""></td>
</tr>
and the corresponding part in MyServlet looks like this:
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
String name=req.getParameterValues("LoginName")[0];          
//*****Construct a response in HTML*****
String reply="<HTML>\n<HEAD><TITLE>Sample response</TITLE></HEAD>\n<BODY>\n<CENTER><BR><B>\n";
reply=reply.concat("hi "+ name);
reply=reply.concat("\n</B></CENTER>\n</BODY>\n</HTML>");
//*****Send the reply*****
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println(reply);
out.close();
i think the servlet should be fine as it was taken from an online tutorial. i think the problem may lie in it not being able to find it.
i have also tried combinations such as
="http://localhost:8080/BooksOnline/HTML/servlet/MyServlet", MyServlet.class and so on and so forth. Its really basic at the moment, but once i have it running, then i can actually have it doing better stuff. Can anyone help?!
cheers
Alex Thomas

Hi,
do i have to be running tomcat at this point? at the moment im just trying to get some connectivity before using tomcat. I just want to see that i can actually connect the html with the java. is this possible without using tomcat?
cheers
alex

Similar Messages

  • Servlets/JDBC - Connect to database ONCE and not in every servlet - How?

    Hello, I'm using servlets and JDBC.
    In every servlet , i connect to the database and then i close the connection, but this is not ptactical.
    I would like to connect to the database once (at the beginning) when container starts and then close the connection.
    How am i supposed to do that?
    Thanks, in advance!

    Bad idea. Don't do that. The connection will timeout sooner or later (depends on DB used, it's usually around 30 mins) and your application will crash.
    You should always acquire and close the connection (and statement and resultset!) in the shortest possible scope. To improve connecting performance just use connection pooling.
    Create a DAO class which does all the task and just instantiate and assign it as Servlet class variable during Servlet's init() method. For more insights and code samples start here: [http://balusc.blogspot.com/2008/07/dao-tutorial-data-layer.html].
    To go back to your fundamental question, doing some stuff during startup and shutdown of webapp, you could use the ServletContextListener for this. But again, do NOT do this to get hold of an external resource such as a connection! It's receipt for trouble.

  • How to create ShoppingCart By Using mysql+Servlet+Html

    Hi everyone:
    I am working on a project using Jbuilder, which is a shopping site.
    The functions are:
    1, Access database and display all kinds of products in a table
    2, Add the item you want into a Temporary Cart
    3, Remove unwanted items from cart
    4, Confirm the order
    I can only use mysql + Servlet + Html.
    I am at the step of display everything from the database, but i don't have any idea how to do the rest of the functions.
    i have read lots of information, it seems that i need to use session tracking, and connection pool stuff.
    Can any one give me some suggestions about how to design this project and how to implement it, and what kinds of thing i need to aware of.
    cheers
    Lin

    Hi,
    i have idea about ur app in different env i.e. in different servers but i don't know how it will impl in jbuilder.i will send u link of whole shop app and also u can refer the wrox books and site.

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

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

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

  • Javax.servlet.ServletException: Connection reset by peer....Help needed..

    Initially, when I clicked on my JSPs, everything was fine. I was able to retrieve data successfully from all the JSPs. However, after much clicking through the JSPs. I was not able to access the JSPs and the Internal Servlet Error was shown.
    Below is my Tomcat.log:
    Context log: path="/Aedge" Error in jsp service() : Connection reset by peer: socket write error
    javax.servlet.ServletException: Connection reset by peer: socket write error
         at org.apache.jasper.runtime.JspServlet.service(JspServlet.java:375)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.tomcat.core.ServletWrapper.handleRequest(ServletWrapper.java:503)
         at org.apache.tomcat.core.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:163)
         at org.apache.tomcat.servlets.DefaultServlet.doGet(DefaultServlet.java:187)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.tomcat.core.ServletWrapper.handleRequest(ServletWrapper.java:503)
         at org.apache.tomcat.core.ContextManager.service(ContextManager.java:559)
         at org.apache.tomcat.service.http.HttpConnectionHandler.processConnection(HttpConnectionHandler.java:160)
         at org.apache.tomcat.service.TcpConnectionThread.run(SimpleTcpEndpoint.java:338)
         at java.lang.Thread.run(Unknown Source)
    Context log: path="/Aedge" <b>Internal Servlet Error:</b><br>.....
    What is the problem here? How can I solve this as I had to restart my Tomcat once a while due to this problem.

    ok.. I have db classes where all my sql statements methods are being displayed.. In each db class, there will be a getInstance() method to create the connection. Below is one of my db class.. How to I modified the things you had mentioned in my codes..
    package aedgeSoft.access;
    import aedgeSoft.business.*;
    import java.sql.*;
    import java.util.*;
    import java.util.Date;
    import java.io.*;
    public class DBMemberType
         private Connection con;
         private static DBMemberType instance = null;
         public static DBMemberType getInstance()
              try
                   if(instance==null)
                        instance = new DBMemberType();
              catch(SQLException e)
                   System.out.println("Problems with loading database in DBMemberType");
              catch(ClassNotFoundException e)
                   System.out.println("Problems with loading db driver in DBMemberType");
              finally
                   return instance;
         private DBMemberType() throws SQLException, ClassNotFoundException
              try{
              Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
              con = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;user=username;password=password;DatabaseName=db");
              catch(InstantiationException e)
                   e.printStackTrace();
              catch(IllegalAccessException e)
                   e.printStackTrace();
         //add memberType
         public boolean addMemberType(MemberType mt)
    ..........

  • How can I generate a html page in a servlet-applet connection?

    Hello, I have an applet which contains an ok button, when I click this button, I need that servlet generate an html page and view it in browser. How can I do this?
    Thanks

    But with this method only is possible I think open a page web, and if it is possible call url of the servlet, you generate other request and response object (other call to method doGet or doPost because ShowDocument needs parameter url), so the previously request when I click button ok it's no the same and how I obtain the prinwriter from first request, showDocument don't obtain html page from printwriter.

  • Servlet (html code doesn't work correctly on IE6)

    Hi, i've a problem with code html on servlet...my page works correctly with firefox but on IE6 i've a lot of bugs about table alignment and CSS looks like not exist . This is code that doesn't work:
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            PrintWriter out = response.getWriter();
            String context = request.getContextPath();
            response.setContentType("text/html");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>RisultatoRicerca Servlet</title>");
            out.println("<link rel='stylesheet' type='text/css' href='"+context+"/css/cd.css'>");
            out.println("<script>");
            out.println("</script>");
            out.println("</head>");
            out.println("<body>");
            DbUtility utility = new DbUtility();
            GestioneCd gestioneCd =new GestioneCd();
            GestioneNoleggio gestioneNoleggio=new GestioneNoleggio();
            Cd cd = newCd();
    cd.setArgomento(request.getParameter("argomento")==null?"":request.getParameter("argomento"));
            cd.setEtichetta(request.getParameter("etichetta")==null?"":request.getParameter("etichetta"));
            cd.setUbicazione(request.getParameter("ubicazione")==null?"":request.getParameter("ubicazione"));
            int valoreRadio=request.getParameter("attivo")==null?0:Integer.parseInt(request.getParameter("attivo"));
            if (valoreRadio==1){
                cd.setAttivo(true);
            }else if (valoreRadio==2){
                cd.setAttivo(false);
            Connection con = null;
             LinkedList cdFromRisultatoRicerca=new LinkedList();
            try{
                con=utility.getConnection();
                cdFromRisultatoRicerca=gestioneCd.getRisultatoRicercaCd(con, cd,valoreRadio);
                ListIterator iterator = cdFromRisultatoRicerca.listIterator();
                int id=0;
                String argomento="";
                String etichetta="";
                String ubicazione="";
                out.println("<form name='visualizza' method='post'");
                out.println("<table align='center'>");  // NOT WORKS , table alignment not respected on IE6
                out.println("<tr><td colspan='9' align='center'></td></tr>");
                out.println("<tr><td colspan='9' align=center class='titolo'>Risultato ricerca</td></tr>");
                out.println("<tr>");
                out.println("   <td align='left' class='titolo'>Id</td>");
                out.println("   <td align='left' class='titolo'>Argomento</td>");
                out.println("   <td align='left' class='titolo'>Etichetta</td>");
                out.println("   <td align='left' class='titolo'>Ubicazione</td>");
                out.println("   <td align='center' class='titolo'>N.copie</td>");
                out.println("   <td align='center' class='titolo'>Disponibili</td>");
                out.println("   <td align='left' class='titolo'>Attivo</td>");
                out.println("   <td class='titolo'> </td>");
                out.println("   <td class='titolo'> </td>");
                out.println("</tr>");
                out.println("<tr>");
                out.println("   <td colspan='7' align='center'>");
                out.println("       <HR width='100%'>");
                out.println("   </td>");
                out.println("   <td> </td>");
                out.println("   <td> </td>");
                out.println("</tr>");
                int copie=0;
                while (iterator.hasNext()){
                    cd=(Cd)iterator.next();
                    out.println("<tr>"); // NOT WORKS, on IE6 lines appears not in a table
                    out.println("   <td>"+cd.getId()+"</td>");
                    out.println("   <td>"+cd.getArgomento()+"</td>");
                    out.println("   <td>"+cd.getEtichetta()+"</td>");
                    out.println("   <td>"+cd.getUbicazione()+"</td>");
                    out.println("   <td align='center'>"+cd.getCopie()+"</td>");
                    int copieNoleggiate=gestioneNoleggio.getCopieNoleggiate(con,cd);
                    int copieDisponibili=(cd.getCopie())-(copieNoleggiate);
                    out.println("   <td align='center'>"+copieDisponibili+"</td>");
                    out.println("   <td align='center'>");
                    if (cd.isAttivo()==true){
                        out.println("<img src="+context+"/immagini/pulsanteverde2.gif>");
                    }else{
                        out.println("<img src="+context+"/immagini/pulsanterosso2.gif>");
                    out.println("   </td>");
                    out.println("   <td>");
                    out.println("       <a href='javascript:;' onclick=\"javascript:window.open('"+context+"/servlet/ModificaCd?id="+cd.getId()+"','Modifica','width=500,height=300,top=200,left=300');\" target='main'>Modifica</a>");
                    out.println("   </td>");
                    if (cd.isAttivo()){
                        out.println("   <td>");
                        out.println("       <a href='javascript:;' onclick=\"javascript:window.open('"+context+"/servlet/ConfermaDisattiva?id="+cd.getId()+"','Disattiva','width=300,height=70,top=250,left=350');\" target='main'>Disattiva</a>");
                        out.println("   </td>");
                    }else{
                        out.println("   <td>");
                        out.println("       <a href='javascript:;' onclick=\"javascript:window.open('"+context+"/servlet/ConfermaAttiva?id="+cd.getId()+"','Attiva','width=300,height=70,top=250,left=350');\" target='main'>Attiva</a>");
                        out.println("   </td>");
                    out.println("</tr>");
                    out.println("<tr>");
                    out.println("   <td colspan='7' align='center'>");
                    out.println("       <HR width='100%'>");
                    out.println("   </td>");
                    out.println("   <td> </td>");
                    out.println("   <td> </td>");
                    out.println("</tr>");
                out.println("<tr>");
                out.println("   <td colspan='9' align='center'>");
                out.println("       <a href='"+context+"/jsp/index.jsp' target='main'>Torna Home</a>");
                out.println("   </td>");
                out.println("</tr>");
                out.println("</table>");
                out.println("</form>");
            }catch (SQLException e){
                out.println(e.getMessage());
                out.println(e.getSQLState());
            }finally{
                try {utility.closeConnection(con);} catch (Exception e) {con=null;}
            out.println("</body>");
            out.println("</html>");
            out.close();
        }And this is CSS :
    BODY {
            background : #CCCCCC ;
            color : #000000 ;
            font-family  : sans-serif ;
            font-size : 13px ;
    A {
            color : #D2691E ;
            font-weight : bold ;
            font-family : sans-serif ;
            font-size : 12px ;
            text-decoration : none ;
    TABLE {
            background : #CCCCCC ;
            color : #000000 ;
            font-family : sans-serif ;
            font-size : 13px ;
            border : 1px ;
    .titolo {
            background-color : #CCCCFF ;
            font-family : sans-serif ;
            color : #000000 ;
            font-size : 13px ;
            font-style : normal ;
            font-weight : bold ;
    }Thx for your attenction :D

    out.println("<form name='visualizza'
    'visualizza' method='post'");
    out.println("<table align='center'>");
    'center'>"); // NOT WORKS , table alignment not
    respected on IE6You're missing a > at the end of the form start tag.

  • JSP Servlet JDBC connection

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

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

  • Servlet Database Connections

    Hello all, i have a servlet that gets a new database connection everytime doPost(..) is called, and closes the connection and the end of the method. What would be best bearing in mind that i want it to be able to handle as many concurrent requests as possible without it falling over...
    1) this way
    2) Have is so when the servlet is instatiated a connection is made, and everytime its used it's tested to see if it is still open
    3) Have some exteral managment (like hibernate) for pooling of connections
    4) something else?
    Thanks for any help!
    Dori

    Use connection pooling.
    You don't necessarily use Hibernate for this. It does in fact also nothing with connection pooling, it is just another ORM framework. You can just use the connection pooling facility provided by a decent appserver. Just consult its JNDI resources/datasources documentation for details. If you are for example using Tomcat, here is such a doc: [http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html]. Good luck.
    That said, option 2 is a very, very bad idea. When a connection is kept open that long time in the servlet, the DB will timeout and close it sooner or later and your application will gracefully crash.

  • Midlet & Servlet(Tomcat) Connection

    I have built up a midlet that need to connect to the servlet which is hosted using Tomcat ...
    When i click the submit button in the mobile emulator ... i received the following message in the console of Java Wireless ToolKit .... What is the problem actually ? .... Can anyone give me some guides ?
    Any Helps will be appreciated
    "<html><head><title>Apache Tomcat/5.0.12 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 404 - Servlet RequestServlet is not available</h1><HR size="1" noshade><p><b>type</b> Status report</p><p><b>message</b> <u>Servlet RequestServlet is not available</u></p><p><b>description</b> <u>The requested resource (Servlet RequestServlet is not available) is not available.</u></p><HR size="1" noshade><h3>Apache Tomcat/5.0.12</h3></body></html>"
    The following is my midlet :
    public class SecondMidletServlet extends MIDlet implements CommandListener, Runnable {
    Display display = null;
    List menu = null;
    TextBox input = null;
    String user = null;
    String url = "http://pup.no-ip.net:8001/Servlet/RequestServlet";
    static final Command backCommand = new Command("Back", Command.BACK, 0);
    static final Command submitCommand = new Command("Submit", Command.OK, 2);
    static final Command exitCommand = new Command("Exit", Command.STOP, 3);
         StringBuffer b = new StringBuffer();
    String currentMenu = null;
         Thread thread;
    public SecondMidletServlet() {
    public void startApp() throws MIDletStateChangeException {
    display = Display.getDisplay(this);
    menu = new List("Invoke Servlet", Choice.IMPLICIT);
    menu.append("Add a user", null);
    menu.addCommand(exitCommand);
    menu.setCommandListener(this);
    mainMenu();
    public void pauseApp() {
    public void destroyApp(boolean unconditional) {
    notifyDestroyed();
    void mainMenu() {
    display.setCurrent(menu);
    public void addName() {
    input = new TextBox("Enter first name:", "", 5, TextField.ANY);
    input.addCommand(submitCommand);
    input.addCommand(backCommand);
    input.setCommandListener(this);
    input.setString("");
    display.setCurrent(input);
    void invokeServlet(String url) throws IOException {
    HttpConnection c = null;
    InputStream is = null;
    OutputStream os = null;
    //StringBuffer b = new StringBuffer();
    TextBox t = null;
    try {
    c = (HttpConnection)Connector.open(url);
                   if(c == null)
                        System.out.println("PKPK");
                   else
                        System.out.println("PSPS");
    c.setRequestMethod(HttpConnection.POST);
    c.setRequestProperty("IF-Modified-Since", "20 Jan 2001 16:19:14 GMT");
    c.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");
    c.setRequestProperty("Content-Language", "en-CA");
    os = c.openOutputStream();
    String str = "name="+user;
    byte postmsg[] = str.getBytes();
    System.out.println("Length: "+str.getBytes());
    for(int i=0;i<postmsg.length;i++) {
    os.write(postmsg);
    // or you can easily do:
    // os.write(("name="+user).getBytes());
    os.flush();
    is = c.openDataInputStream();
    int ch;
    while ((ch = is.read()) != -1) {
    b.append((char) ch);
    System.out.print((char)ch);
    } finally {
    if(is!= null) {
    is.close();
    if(os != null) {
    os.close();
    if(c != null) {
    c.close();
    //display.setCurrent(t);
         public void run()
              try
                   invokeServlet(url);
                   TextBox t = new TextBox("Second Servlet", b.toString(), 1024, 0);
                   t.addCommand(backCommand);
                   t.setCommandListener(this);
                   display.setCurrent(t);
              catch(Exception ex){}     
         public void refreshScreen(StringBuffer b)
              TextBox t = new TextBox("Second Servlet", b.toString(), 1024, 0);
              t.addCommand(backCommand);
              t.setCommandListener(this);
              display.setCurrent(t);
    public void commandAction(Command c, Displayable d)
    String label = c.getLabel();
    if (label.equals("Exit")) {
    destroyApp(true);
         else if (label.equals("Back")) {
    mainMenu();
         else if (label.equals("Submit"))
    user = input.getString();
    // try {
    //invokeServlet(url);
              thread = new Thread(this);
              thread.start();
              // catch(IOException e) {}
         else {
    addName();
    //Servlet side
    public class RequestServlet extends HttpServlet {
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    BufferedReader br = request.getReader();
    String buf = br.readLine();
              System.out.println("LSLS");
    out.print("Rec: "+buf);

    Hi,
    Since you use POST Method for the request, you have to implement the doPost(...) Method in the servlet, right? Do a simple implementation of the doGet(...) Method and call the Servlet using a browser. So you can easily check, whether the Servlet is available or not. You got the Error 404 which means, that the Servlet cant be found on the Tomcat. Make sure, that it is deployed correctly and your URL in the MIDlet is also correct.
    hth
    Kay

  • Servlet -  database connection usage

    Hi
    I am writing a servlet based upon the multi thread model (default in many cases).In the servlet, I go to database 2 or 3 times per request and get data. I have broken down my main method into 4 methods. so method 1 calls method 2 with some params, method 2 calls method 3 etc.
    I am using connection pooling. I am passing the connection object from method 1 to downstream methods. and release the connection only at the end.
    My question is since this servlet can be accessed by multiple threads, is this a good practice of passing connection downstream since a servlet might try to access with a closed connection object. Should I just get connection objects from the pool and release them inside each method.
    thanks

    Hi
    I am writing a servlet based upon the multi thread
    model (default in many cases).In the servlet, I go to
    database 2 or 3 times per request and get data. I have
    broken down my main method into 4 methods. so method 1
    calls method 2 with some params, method 2 calls method
    3 etc.
    I am using connection pooling. I am passing the
    connection object from method 1 to downstream methods.
    and release the connection only at the end.
    My question is since this servlet can be accessed by
    multiple threads, is this a good practice of passing
    connection downstream since a servlet might try to
    access with a closed connection object. Should I just
    get connection objects from the pool and release them
    inside each method.
    thanksIf the Connection is a local variable for the service, doPost, doGet, etc... there isn't any problem with your aproach.
    If it is, then your Connection is shared between all the threads that run concurrently (run througth the servlet).
    Concerning your aproach (and the Connection beeing a local variable), there is no problem in passing it to the next method by parameter because it is the same thread running the code.
    MSB

  • Save servlet html output as jpeg.

    Hello everybody,
    I have a servlet that creates an html page.
    The html consits of information from a database and displays a data sheet with images and text.
    I have been asked if the outputed data sheet can be saved as an image (jpeg).
    Is this possible?
    Thanks.

    I am can of confused how this works
    I know that there is more to do in order to create an
    image.First you have to make a desition, what do you need?
    * if you only want to save a data sheet i think the better solution is a Excel format file, for this yo coul take a look at http://jakarta.apache.org/poi/hssf/index.html
    * if you want to generate a pdf with images, tables, etc. yo should take a look at http://xml.apache.org/fop/
    * if you want to create a custom image i cant help you
    the proces to generate excel isnt dificult but to make a pdf is a little hard. but if you read the documentation and the examples you shouldnt have problems
    Jorge

  • Servlet-html

    How to send values from servlet to html..
    I retrieve values from database using servlet pgm and want to display in textfield...
    do reply
    thx,
    dish

    You welcome to use my code... the syntax is not 100% for i changed table names, field names, etc for copyright purposes... but this is how i did mine
    You will need to change it according to yur program/output
    Create your SQL statement ...
    =======================================================================================================
    String q8="SELECT *     + "from search_projects "
         + "where queried_user_name = '" + g_user_name + "'";
    os.println("<BR><BR><BR>");
    DisplayQuery(q8, res, "view");
    ========================================================================================================
    static String DisplayQuery(String p_sql,HttpServletResponse res, String p_heading_types)
    throws ServletException,IOException
    PrintWriter os=res.getWriter();
    Statement stmt = null;
    String l_error = "";
    try
    stmt = con.createStatement();
    stmt.execute(p_sql);
    ResultSet rs = stmt.getResultSet();
    if (rs != null)
    DispResultSet(rs, res, p_heading_types);
    rs.close();
    return(p_sql);
    catch (Exception e)
    os.println("<BR><BR>EXCEPTION. Unable to execute. If problem persists, please contact");
    os.println(e);
    return("<BR>ERROR3");
    ===================================================================================================
    static void DispResultSet(ResultSet rs, HttpServletResponse res, String p_heading_types)
    throws ServletException,IOException, SQLException
    PrintWriter os=res.getWriter();
    ResultSetMetaData rsmd = rs.getMetaData ();
    int p=0;
    int numCols = rsmd.getColumnCount ();
    if (p_heading_types.equals("view"))
    while (rs.next())
    os.println("<TABLE BORDER=1 COLS=" + numCols + ">");
         os.println("<TR>");
         os.println("<TD>");
    os.println("<TH><FONT color=blue>Id</FONT></TH>");
    os.println("</TD>");
         os.println("<TD>");
    os.print("<FONT color=black>"+rs.getString(1)+"</FONT></TD>");
         os.println("</TD>");
         os.println("</TR>");
         os.println("<TR>");
         os.println("<TD>");
    os.println("<TH><FONT color=blue>Amount</FONT></TH>");
         os.println("</TD>");
         os.println("<TD>");
    os.print("<FONT color=black>"+rs.getString(2)+"</FONT></TD>");
         os.println("</TD>");
         os.println("</TR>");
         os.println("<TR>");
         os.println("<TD>");
    os.println("<TH><FONT color=blue>rings</FONT></TH>");
         os.println("</TD>");
         os.println("<TD>");
    os.print("<FONT color=black>"+rs.getString(3)+"</FONT></TD>");
         os.println("</TD>");
         os.println("</TR>");
         os.println("<TR>");
         os.println("<TD>");
    os.println("<TH><FONT color=blue>Date</FONT></TH>");
         os.println("</TD>");
         os.println("<TD>");
    os.print("<FONT color=black>"+rs.getString(4)+"</FONT></TD>");
         os.println("</TD>");
         os.println("</TR>");
         os.println("<TR>");
         os.println("<TD>");
    os.println("<TH><FONT color=blue>Email</FONT></TH>");
         os.println("</TD>");
         os.println("<TD>");
    os.print("<FONT color=black>"+rs.getString(5)+"</FONT></TD>");
         os.println("</TD>");
         os.println("</TR>");
    os.println("</TABLE>");
    os.println("<BR><BR><BR>");
    p=p+1;
    Thanks
    Naren

  • Java Servlet/Html link problem

    Hi,
    I have been using the Java servlet to create the html code itself using the PrintWriter.I would like to know if it possible to input ALL the code into -
    PrintWriter out=null;
    out.println("<Html><Body>the entrie html code</Body></Html>");
    or must I input in this form?-
    out.println("<html>");
    out.println("<Body>");
    out.println("<The entire html code>");
    out.println("</Body>");
    out.println("</Html>");
    Does it really make a difference?
    I would also like to know it is possible to retrive data from a database and (via servlet) input the list of data into the combo-box of an html Webpage.
    Thank you very much for your assistance.Kindly acknowledge receipt.
    Yours sincerely,
    Aeshan
    PS- I'll send more information soon

    Your answers are yes ...and yes.
    But don't use:
    PrintWriter out=null;
    Use:
    PrintWriter out = response.getWriter();
    Usually the println() method is used to make both the servlet source code ...as well as the html it generates ...a little nicer to read. This may or may not be important to you, but may matter to your employer and those who maintain your code in the future.

  • Declarative security of servlet- html view changes depending upon  the role ??

              Hi All,
              There is acl for ejb methods and we can restrict roles to use certain
              methods of the bean. Now my question is that
              Is something possible in a declarative fashion so that user can have
              certain options enabled and certain disabled in the jsp/servlet output
              depending upon his role ?
              For example, let suppose we have a servlet MyServlet that creates an
              html output with some input boxes and buttons (add, modify, delete). Now
              is it possible, that ceratin user will only see modify button, some
              won't see any button, can only view the screen depending upon their role
              and verything in declarative fashion ?
              Any suggestion is welcome.
              TIA,
              Sudarson
              

    Servlet security is defined in the context of the web application containing
              the servlet, and web app security provides for the declarative protection of
              resources like servlets, jsps and html pages; so the answer is no.
              See http://e-docs.bea.com/wls/docs61///webapp/security.html
              Thanks
              Jim
              sudarson wrote:
              > Hi All,
              >
              > There is acl for ejb methods and we can restrict roles to use certain
              > methods of the bean. Now my question is that
              >
              > Is something possible in a declarative fashion so that user can have
              > certain options enabled and certain disabled in the jsp/servlet output
              > depending upon his role ?
              >
              > For example, let suppose we have a servlet MyServlet that creates an
              > html output with some input boxes and buttons (add, modify, delete). Now
              > is it possible, that ceratin user will only see modify button, some
              > won't see any button, can only view the screen depending upon their role
              > and verything in declarative fashion ?
              >
              > Any suggestion is welcome.
              >
              > TIA,
              > Sudarson
              [Reply.vcf]
              

Maybe you are looking for