Solved

Combine Servlets and JSP

Posted on 2004-04-06
10
903 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:mayankeagle
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
 
LVL 30

Expert Comment

by:mayankeagle
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:mayankeagle
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 30

Expert Comment

by:mayankeagle
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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

708 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now