Writing a servlet

Jsp files are converted to servlets at the first run as you know...Other requests are threaded from that servlet until a code change made in a jsp file...
So why do we write servlets...?
We may write a jsp(which is easier) then run it and automatically servlet created?is this true?
i think not...So what is wrong with my point?

u missunderstand my question...You misunderstood his answer. :o)
i say jsp's are converted to servlets..so we dont
need to write servlets..do we?JSPs are HTML-centric ways of writing servlets. In common practice, scriptlets are typically frowned upon. They make the JSP unwieldy, ugly, and difficult to maintain. Furthermore, in keeping with a good Model 2 design philosophy, JSPs should be reserved for view logic alone. Other business logic belongs in another tier.
For more information, please read the following:
Understanding JavaServer Pages Model 2 architecture
Web-Tier Application Framework Design
Almost All Java Web Apps Need Model 2
~

Similar Messages

  • Writing to servlet output stream

    Hi All,
    I am writing to a servlet(imageservlet) output stream in a jsp page two times as follows:
    <img src="\imageservlet?key=x1">
    <img src="\imageservlet?key=x2">
    It is causing memory errors. Do I have to take special precautions?
    Thanks inadvance.

    Hi,
    THis is my servlet code.
    import java.io.*;
    import java.io.StringWriter;
    import javax.servlet.http.*;
    import javax.servlet.*;
    import java.awt.Color;
    import com.trizetto.healthweb.service.GenerateImage;
    * Simple servlet to use with Image I/O generator
    public class GenerateImageServlet extends HttpServlet
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
         String className="PieChartGenerator";
         if(request.getParameter("keyName").equals("Pie"))
              className=PieChartGenerator";
         else if( request.getParameter("keyName").equals("Gantt") )
              className="GanttChartGenerator";
    try
    GenerateImage ge=
    (GenerateImage) Class.forName(className).newInstance();
    String type = ge.createImage(response.getOutputStream());
    response.setContentType(type);
    catch (Exception e)
    throw new ServletException(e);
    But this one does not generate image. The image is generated from the Graphics object of the Frame.
    Something like the following code:
    http://www.javaworld.com/javaworld/jw-05-2000/servlets/Servlets.zip
    http://www.javaworld.com/javaworld/jw-05-2000/jw-0505-servlets-p2.html
    http://www.javaworld.com/javaworld/jw-05-2000/jw-0505-servlets-p1.html
    I am using Java 1.1.
    I am running my app. in websphere. The error happens randomly while I am stopping the websphere application server.
    Thanks in advance.

  • IOException - WEB8001 - when writing to servlet response outputstream

    I am attempting to port a Java servlet application from iws 6.0 to 6.1, sp2, but am encountering IOExceptions during load testing.
    The servlet composes its response in a character array, and then calls the following method to write the characters to the servlet response object:
    static void writeResponse( HttpServletResponse response, char[] chars, String charset ) throws IOException {
        OutputStreamWriter writer =
            new OutputStreamWriter( response.getOutputStream(), charset );
        char[] buffer = new char[8192];
        CharArrayReader reader = new CharArrayReader( chars );
        int read = 0;
        while(( read = reader.read( buffer, 0, 8192 )) > -1 )
           writer.write( buffer, 0, read );
        writer.close();
    }Under moderate load (2-4 simultaneous connections), an IOException will sometimes be thrown. The stack dump is:
    java.io.IOException: WEB8001: Write failed
         at com.iplanet.ias.web.connector.nsapi.NSAPIConnector.write(NSAPIConnector.java:750)
         at com.iplanet.ias.web.connector.nsapi.NSAPIResponseStream.write(NSAPIResponseStream.java:74)
         at org.apache.catalina.connector.ResponseBase.flushBuffer(ResponseBase.java:765)
         at org.apache.catalina.connector.HttpResponseBase.flushBuffer(HttpResponseBase.java:779)
         at com.iplanet.ias.web.connector.nsapi.NSAPIResponse.flushBuffer(NSAPIResponse.java:127)
         at org.apache.catalina.connector.ResponseBase.write(ResponseBase.java:738)
         at org.apache.catalina.connector.ResponseStream.write(ResponseStream.java:325)
         at sun.nio.cs.StreamEncoder$CharsetSE.writeBytes(StreamEncoder.java:336)
         at sun.nio.cs.StreamEncoder$CharsetSE.implWrite(StreamEncoder.java:395)
         at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:136)
         at java.io.OutputStreamWriter.write(OutputStreamWriter.java:191)
         at eng.pubs.servlet.DocServlet.writeResponse(DocServlet.java:1034)The exception is not thrown consistently for any given URL, but appears to be random. When run under iws 6.0, the exceptions do not occur at all. Most of the time, the method will have written 32K
    of data when the exception is thrown.
    Any clues about how I might debug this?

    What are you using as your test client?The test client is WebStone 1.0. WebStone always downloads the whole response, and reports the size of the response in bytes. From this I can see that when the IO exception occurs, webstone is unable to read the whole response, as it reports a smaller size.
    So, I do not think the problem is that the client has prematurely aborted its download. WebStone doesn't work that way. I think something has gone awry on the server side, and this worries me.

  • Writing to servlet log files?

    Using the log(...) method of the servlet API. No problem finding the log file in the case of the embedded server in JDev. I cannot find the log file in the standalone OC4J. Seems to me there is an XML attribute to 'turn-on' to enable logging but I do not remember it.
    Please send me info to enable logging -
    THANKS - Ken Cooper

    The string written to standalone log file does not exist anywhere in the JDev installation folder!Do you mean your oc4j standalone installation is inside you Jdev installation? I am so confused.
    As far as I checked, the servlet log(...) should go to the log file for the j2ee application, which is by default, application.log in application-deployments/yourApp directory. It did in my simple test.

  • Writing a servlet code

    Hi all i am newbie to the servlet programming. I need your help. Actually my problem is, I need to send a message to a remote server. Say i need to send message to the Msn.com by getting a username and password from the user and it will be sent to the MSN.com. how do i go about doing that. can anyone reply me asap.
    Thank you
    Shree

    Hi Shree
    If you want to send a message to MSN.com
    1.
    You have to first find what attribute names that the MSN.com is expecting. There Syntax and case is also important. When it comes to password it could be Password or password or sPassword or any format that they specify.
    2.
    Then you have to find out what method that the MSN.com use to process the fields that you send. That is there are two ways that it could process POST and GET. If they are using POST you have to set your method as POST or if it's GET set it as GET
    eg. <FORM action="msn.com" method=post>
    Also note that you have to specify the action in your form where that is the actual place where your fields are going to be processed.
    3.
    So the last thing you have to do is making the html form with the above collected information
    eg.
    <FORM action="msn.com" method=post>
    User Name<INPUT TYPE=TEXT NAME=USER_NAME>
    <BR>
    Password <INPUT TYPE=PASSWORD NAME=PASSWORD>
    <BR>
    <INPUT TYPE=SUBMIT>
    </FORM>

  • Writing HTML to Netscape w/ Servlet isn't working

    I am writing a servlet program that resides on port 8080, after there is an input from a form on a HTML page the servlet take the input and then sends HTML.
    The problem is, that it just shows the HTML code and not the formatted page. I use a PrintWriter to write the HTML code to the web browser. The code works fine in Internet Explorer, but in Netscape 4.xx and 6.xx it doesn't work at all.
    Does anyone have any idea what could be causing this or how I could fix it?

    You use the next Content Type?
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<body bgcolor=\"white\">");
    ...

  • TEXTAREA with servlets

    Hi,
    I am writing a servlet where I need to retain the text the user entered in an HTML TEXTAREA after a page refresh.
    Upon page refresh, I send the value of the TEXTAREA to the servlet via the URL. I then populate the TEXTAREA's default value with req.getParameter(<my textarea value>).
    My problem is this: carriage returns are lost. How can I retain them when I pass the value using only Javascript?
    Below is a bit of my code. ldifHeaders contains the value of the TEXTAREA captured via Javascript <field>.value.
    out.println("function refreshPage(mailPlatform)");
    out.println("{");
    out.println(" window.location.replace('"+sServletPath+"/MailSystemDetails?LDIFHeaders='+ldifHeaders);");
    out.println("}");

    Hi,
    Try using the escape sequence to translate the URL
    As far as I remember, the carriage return will be
    translated into "%0D"
    /SlashWould you know how to break up the value returned from the javascript <textarea>.value?
    If I can break this value up into tokens, I can manually build the URL like you mentioned. Thanks.

  • How to set content type in servlet?

    Hi, there,
    I'm writing a servlet to use ObjectOutputStream to return an object to applet. How can I set this content type in servlet?
    Thanks.

    Actually, I'm writing a "HashMap" from servlet to applet. I have used your suggested content type "application/octet-stream" and another "appication/x-java-serialized-object" to try it. But in applet side, when I use (HashMap)in.readObject(), it always gives me a exception as:"java.util.HashMap; IllegalAccessException". Why?
    Thankd.

  • 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

  • JDBC & Servlets

    I am writing some servlets that write to a sQL Servler database, reading from a html form.
    I have noticed that when I enter a name to a html text field, it will not take any characters after a blank space, and similiarily after a new line in a html textarea.
    this is how i get the info from the form:
    String name = request.getParameter("name");
    I am then inserting the data via sql query :
    Insert into EmployeeDetails values ('"+uid+"', '"+name+"') ");
    etc...
    Any help would be appreciated people
    Cheers

    sorry everyone, it is actually saving to the database but if i wanted to display the data in another text field, it will only display the first word.
    eg, I enter in joe bloggs and i see only joe in my new text field

  • JDBC and Servlets

    I am writing a servlet which retrieves data from a database into a result set. I want to compare a username (taken into the servlet via a form for example) with a username from the result set.
    Can anyone tell me how this might be coded? Thanx.

    get the userid and password from the html form:
    String userid = req.getParameter("userid").trim();
    String password = req.getParameter("password").trim();
    find userid and password from database:
    String sql="SELECT PASSWORD FROM USER WHERE USERID =?";
    try{
    Class.forName(".............");
    con = DriverManager.getConnection(url,user,password);
    pstmt = con.prepareStatement(sql);
    pstmt.setString(1,userid);
    ResultSet result = pstmt.executeQuery();
    if(result != null){
    result.next();
    String pwd_DB = result.getString(1);
    Compare password:
    if (pwd_DB.equals(password)
    Hope it will give you some help.
    Yen

  • Directing home page to servlet

    We use Netscape 3.6 and iPlanet 4.1 as web servers, and Tomcat 3.3.1 as servlet engine.
    I am writing a servlet for a mobile site that identifies user agent to generate the appropriate mark up language for the device (WML/HDML/HTML and etc).
    I am unable to configure the web server to route the home page to the servlet. (e.g. going to http://mobile.xxx.com would direct to http://mobile.xxx.com/home.xml which home.xml is processed by the servlet engine)
    Any thoughts?
    Thank you in advance.
    Anita Loo

    Anita,
    Have you tried adding home.xml as one of the index filenames under Content Management | Document Preferences?
    See if adding home.xml as the first entry helps in what you're trying to accomplish. What the webserver will do on a request to / is go through the list of files defined in Index filenames and look for the first match. If no match is found, it will either display a directory listing of all files in the document root or respond with an error page depending on what option Directory Indexing is set to.

  • Servlet for downloading a file

    i am writing a servlet for downloading a file on a GET action in the form..the web-xml is deployed correctly as far as i can interpret..bt i am encountering an error during the run time..
    HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    here is the log file..
    Jul 11, 2008 12:07:14 AM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet DwnFile threw exception
    java.lang.NullPointerException
         at com.example.web.dwnfile.doGet(dwnfile.java:17)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    it has some more content bt it is just the exceptions thrwn...
    and here is my *.java file*
    package com.example.web;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    public class dwnfile extends HttpServlet
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
    response.setContentType("/image/jpeg");
    ServletContext ctx=getServletContext();
    InputStream is=ctx.getResourceAsStream("/2004.jpeg");
    int read=0;
    byte[] bytes=new byte[1024];
    OutputStream os=response.getOutputStream();
    while ((read=is.read(bytes))!=-1)
    {os.write(bytes,0,read);
    os.flush();
    os.close();
    the bold line is whre the exception is pointing..i think..
    thanks in advance..
    Edited by: Sun_Rockz on Jul 10, 2008 7:13 PM

    response.setContentType("/image/jpeg");
    ServletContext ctx=getServletContext();
    InputStream is=ctx.getResourceAsStream("/2004.jpeg");there was an error in this part of code..the image extension of .jpeg is not allowed it seems..on changing it to jpg worked..and
    in the first line the contenttype mst not be preceded by a forward slash..
    now one more doubt relating to the same servlet..
    response.setContentType("application/x-zip");
    ServletContext ctx=getServletContext();
    InputStream is=ctx.getResourceAsStream("/servlet_spec.zip");
    if i keep this in my servlet the required action is taking place..i.e.i am gettin a download option bt the problem is tht the file is getting downloaded as a download.do file.....
    download.do is the url pattern tht i am using in my html web page..
    i tried replacing different types of allplications and files bt all are downloaded wit the same name. i.e. download.do
    so what do u think is reason behind this..
    thanks for all the replies.
    Edited by: Sun_Rockz on Jul 11, 2008 10:47 AM
    Edited by: Sun_Rockz on Jul 11, 2008 10:51 AM

  • EOF error in servlet

    hello guys, i am writing applet-servlet communication application, i am getting this error, which i am unable to resolve after digging into google also, hope someone here could help me get rid of the error. thanks in advance
    code at applet
         URL url = new URL(getCodeBase(), "NewServlet");
    URLConnection con = url.openConnection();
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(false);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(stream);
    oos.writeObject(obj);
    oos.flush();
    oos.close();
    byte[] buf = stream.toByteArray();
    // con.setRequestProperty ("Content-Type", "application/x-java-serialized-object");
    con.setRequestProperty("CONTENT-LENGTH",Integer.toString(buf.length));
    DataOutputStream dataout = new DataOutputStream(con.getOutputStream());
    dataout.write(buf);
    dataout.flush();
    dataout.close();
    code at servlet
         public void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
         doPost(request, response);
         public void doPost(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
              InputStream in = request.getInputStream();
              try
         ObjectInputStream ois = new ObjectInputStream(in);
         catch(EOFException e1)
         System.out.println(" EXCEPTION ");
         e1.printStackTrace();
    java.io.EOFException
    at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2279)
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2748)
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:780)
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:280)
         at NewServlet.doPost(NewServlet.java:112)
    at NewServlet.doGet(NewServlet.java:69)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
    at java.lang.Thread.run(Thread.java:619)
    also another thing :
    when i do System.out.println(" Content Length = " + request.getContentLength()); it shows -1
    and at applet side when i write
    JOptionPane.showMessageDialog(this,"Priting buf length \n" + buf.length,"Testing!!" , JOptionPane.WARNING_MESSAGE); it shows 501
    while
    JOptionPane.showMessageDialog(this,"Priting con length \n" + con.getContentLength(),"testing!!" , JOptionPane.WARNING_MESSAGE); shows 234

    I think you have to read the headers on the servlet side before you can read the object. I did this once a while ago, but if I recall you have to read a series of strings, each one a header record, until you hit a blank line. That is the indication that the rest of the content is the posted object.

  • Font error in html produced by servlet

    I am writing a servlet that reads data from html form and displays the
    input data in html form for confirmation.
    The program uses japanese characters but when servlet shows the output
    it doesnt show the japanese characters..instead ??? are displayed.
    How can i solve this problem. Here's my code
    public class MosiKomi extends HttpServlet {
           protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            // declaring the variables to assign the input from the form
            String firstName;
            String lastName;
            String furiganaF;
            String furiganaL;
            //Reading the input parameters from the form
            try {
                firstName = request.getParameter("firstname");
                lastName = request.getParameter("lastname");
                furiganaF = request.getParameter("furiganafirst");
                furiganaL = request.getParameter("furiganalast");
            }catch(){
                // exception error code
           return;
            //Printing the above information for confirmation
            // TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>japanese characters</title>"); // japanese character is where i have the japanese characters written
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Jchar " + firstName + "Jchar"+ lastName +"</h1>" +"<br>"); // Jchar are the japanese characters
            out.println("<h1>Jchar" + furiganaF + furiganaL +"</h1>");
            out.println("</body>");
            out.println("</html>");
            //out.close();
        }Any comment on the codes will be highly appreciated too.(like..bad designing...or it would be better this way etc.)
    Thanx in advance

    ok i solved the problem of displaying japanese characters in HTML ouput of servlet.
    However I am stuck with this part.
    The user inputs the japanese characters in the form and submits it.
    But when the servlet displays the input name
    String firstname // this variable is used to store the input names in japanese charactersit doesnt display the characters but instead shows ???
    How can i display the characters input by the users?

Maybe you are looking for

  • Certificado Digital

    Henrique, Criei esse novo post, pois creio que o erro seria em outra tema. Fiz a importação completa do certificado para o PI, pois ja tenho dois ambientes funcionando (MG, MT), SP, PA, BA e RJ todas estão no mesmo cenario e foram configuradas juntas

  • API for component info

    Hi, we're looking for a way to get the version string or the service pack level of the NetWeaver and/or the enterprise portal. There is this "component info web page" when you retrieve http://<nw-host>/sap/monitoring/ComponentInfo. We're searching fo

  • Eclipse beginner, work with already defined packages and folders structure

    Hi! my apologies if this is not the correct subforum, the question is about beginning Eclipse I've already compiled and run the "hello world" example but I need to run an already developed (not by me) software. I'm doing something wrong: first I crea

  • Laptop cannot see airport express

    I have three laptops on my home network.  Two can see my airport express, one cannot.  I have the airport express set to join my home network automatically.  I am only using airport express to be able to listen to my itunes music through my home ster

  • Database query in HTML textbox.

    hi all, here I'm doing a program in servlet & I want to display database query in the HTML Textbox. Suppose I have queried the name of student in the database through servlet programming & I want to display the that ouput "NAME" in my HTML TEXTBOX. A