Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Combine Servlets and JSP

Posted on 2004-04-06
10
Medium Priority
?
948 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
The Orion Papers

Are you interested in becoming an AWS Certified Solutions Architect?

Discover a new interactive way of training for the exam.

 
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 1000 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 top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

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

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
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…
This video teaches viewers about errors in exception handling.
Suggested Courses

715 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