Combine Servlets and JSP

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);
    }

}
chrispkotsiopoulosAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
CEHJConnect With a Mentor Commented:
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
 
Mayank SAssociate Director - Product EngineeringCommented:
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
 
CEHJCommented:
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
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
mmuruganandamCommented:
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
 
Mayank SAssociate Director - Product EngineeringCommented:
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
 
Mayank SAssociate Director - Product EngineeringCommented:
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
 
Mayank SAssociate Director - Product EngineeringCommented:
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
 
CEHJCommented:
This

value=' getValue '

would be replaced with something like

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


0
 
ShannonECommented:
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
 
CEHJCommented:
8-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.