Solved

Combine Servlets and JSP

Posted on 2004-04-06
10
931 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

 
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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Android development question 2 76
JavaFX TableView not displaying correctly 3 103
Eclipse for Java EE development 2 43
program arguments vs VM arguments 4 26
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
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:
The viewer will learn how to implement Singleton Design Pattern in Java.

740 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