Solved

Combine Servlets and JSP

Posted on 2004-04-06
10
923 Views
Last Modified: 2013-11-24
Hello there.

Good news: I'm in Greece and the sun shines as usually.

Bad news: I'm in Greece, the sun shines as usually and I'm in an office trying to program in Java.

The problem: The following code is a servlet that makes a couple of SQL queries and generates an HTML page. I want to separate the HTML from the java code using JSP and servlets. I have absolutely no idea how to do it. The code is:

import java.sql.*;
import java.io.*;
import java.lang.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class tutorial extends HttpServlet {
      Connection connection;

      //Initialize DB
      public void init() throws ServletException{
        try{
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            String url = "jdbc:jtds:sqlserver://ckotsiopoulos:1433/ges_ddb";
            String login = "test_user";
                String password = "test_user";
            //open a connection to the database
                connection = DriverManager.getConnection(url, login, password);
        }
        catch(ClassNotFoundException e){
            System.out.println("Database driver not found.");
        }
        catch(SQLException e){
            System.out.println("Error opening the db connection: "
                               + e.getMessage());
        }
    }

      //Destroy unused objects
      public void destroy() {
        try{
            connection.close();
        }
        catch(SQLException e){
            System.out.println("Error closing the db connection: "
                               + e.getMessage());
        }
    }

      public void doGet(HttpServletRequest request,
                      HttpServletResponse response) {
        try {
   
            response.setContentType("text/html; charset=ISO-8859-7");

            PrintWriter out = response.getWriter();
                        
            //create a statement
            Statement st = connection.createStatement();
            ResultSet rs;
            String getValue = "";

            rs = st.executeQuery("SELECT * FROM [test_table] WHERE id=1");
            if (rs.next()) {
                  //Get the second field (2)
                  getValue =  rs.getString(2);
            }
                  else {
                  getValue = "Error";
                  }

            //I WANT TO SUMBIT THE FOLLOWING WITH 'Submit' BUTTON AND NOT EVERY TIME THE PAGE LOADS.
            st.executeUpdate("UPDATE [test_table] SET name = 'ammonite' WHERE id=1");

            out.println("<html>\n" +
            "<head>\n" +
            "<title>test page</title>\n" +
            "<link href='C:\\webapps\\GESDDB-rc2\\Gesddb\\css\\gesddb.css' type='text/css' rel='stylesheet' />\n" +
            "</head>\n" +
            "<body bgcolor='#cccccc'>\n" +
        "<form action=\"" +
        "tutorial\" " +
        "method=POST>\n" +
            "<table class='blueHeaders' border='0'>\n" +
        "<tbody>\n" +
            "<tr>\n" +
                "<td colspan='3'>\n" +
                    "&nbsp;<input class='blueHeaders' style='WIDTH: 140px; HEIGHT: 22px' type='text' name='current_sdesk' readonly='readonly' value='" + getValue + "' /></td>\n" +
                "<td colspan='2'>\n" +
                    "&nbsp;</td>\n" +
            "</tr>\n" +
                  "<tr>\n" +
                "<td colspan='3'>\n" +
                    "<input style='WIDTH: 90px; HEIGHT: 25px' type='submit' value='Submit' />\n" +
                "<td colspan='2'>\n" +
                    "&nbsp;&nbsp;</td>\n" +
            "</tr>\n" +
        "</tbody>\n" +
       "</table>\n" +
            "</form>\n" +
        "</body>\n" +
        "</html>");
            //close the objects
            st.close();

    }
            catch (Exception e) {
            e.printStackTrace();
            }
      }
            
    public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        doGet(request, response);
    }

}
0
Comment
Question by:chrispkotsiopoulos
10 Comments
 
LVL 30

Expert Comment

by:Mayank S
ID: 10764697
BTW, a JSP would also be compiled into a Servlet.

But if you really want to do that, then you can do:

- remove all the tag-statements, like out.println ( "<HTML>" ) ;, etc - and put them directly in the JSP, like: <HTML><BODY> and so on

- you can forward the request and response to the JSP using various ways. You could use:
getServletConfig ().getServletContext ().getRequestDispatcher ( "/whicheverjsp.jsp" ).forward ( request, response ) ;

- put all Java logic (in the JSP) within <% %>
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10764700
The first thing to do is to take that html and turn it into an html file. There are various ways of inserting the result of  the query and you should probably wait for some good solutions to accumulate here, before deciding. In the meantime, i'd do the html.
0
 
LVL 9

Expert Comment

by:mmuruganandam
ID: 10764705
You have use the Java Beans.  

Your objects will be set as a bean in the JSP by the servlets.

In the JSP you have to use the Bean and generate your layout.

For more details, have a look at

http://java.sun.com/products/jsp/docs.html


0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 30

Expert Comment

by:Mayank S
ID: 10764708
In fact, your entire out.println () statement can be removed. The string inside it "<html>...." can be completely put in a different JSP page, and you can forward to it using the getRequestDispatcher ().forward () like I have shown.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10764721
Do you want to use only JSPs or do you want to use both JSPs & Servlets?

Also, the string which you have in out.println () - you can put it in an HTML file but later, will you need to add Java logic to it as well? If so, then it should be a .jsp file.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10764729
Ah, I see that you're also appending the string getValue somewhere in that HTML. Well, in a JSP, you can use:

<%= getValue %>

to get that String printed there.
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 250 total points
ID: 10764776
Here's your html. Better check it though:



<html>
  <head>
    <title>test page</title>
    <link href='C:\\webapps\\GESDDB-rc2\\Gesddb\\css\\gesddb.css'
    type='text/css' rel='stylesheet'>
  </head>

  <body bgcolor='#cccccc'>
    <form action="tutorial" method="POST">
      <table class='blueHeaders' border='0'>
        <tbody>
          <tr>
            <td colspan='3'>&nbsp;<input class='blueHeaders' style=
            'WIDTH: 140px; HEIGHT: 22px' type='text' name=
            'current_sdesk' readonly='readonly' value=
            ' getValue '></td>

            <td colspan='2'>&nbsp;</td>
          </tr>

          <tr>
            <td colspan='3'><input style=
            'WIDTH: 90px; HEIGHT: 25px' type='submit' value=
            'Submit'> </td>

            <td colspan='2'>&nbsp;&nbsp;</td>
          </tr>
        </tbody>
      </table>
    </form>
  </body>
</html>


I would use a bean to return your query. Here's an example:

http://javaalmanac.com/egs/javax.servlet.jsp/usebean.jsp.html
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10764821
This

value=' getValue '

would be replaced with something like

value='<%=dbBean.getQueryResult()%> '


0
 
LVL 4

Expert Comment

by:ShannonE
ID: 10768539
Note: a JSP is just a shorthand for making servlets, but it lets one avoid putting html code inside print method calls and just type the html code directly. The way to think of a JSP is that its closer to a html file than a java program. Write the JSP as a normal html web page and just put the java code between <%  %> brackets, there's not much more to it than that.  You DON'T need to use JavaBeans with JSP, and I'd recommend you don't until you are at least familiar with JSP

The best introductory tutorial on JSP I've seen is here:
http://java.sun.com/developer/onlineTraining/JSPIntro/contents.html
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10868574
8-)
0

Featured Post

The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
web services creation SOAP vs REST 5 56
Java string replace 11 53
ejb message driven bean mdb creation steps 2 15
Eclipse for Java EE development 2 25
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

766 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question