Dan McNamara
Dan McNamara

Reputation: 39

Populate JSP textarea with method in Java Servlet

I have looked for a clear answer or lead all over stack and other forums, but all of them are associated with filling textareas with input, forms, and/or submissions. In my case I do not require any of those. I simply need the area to populate with information fetched by a query that I wrote in my Servlet's service() method. I do not want to rely on scriptlets. I want to be able to maintain security with my private instances and maintain 2 different files where I can code in one language for each. Its easier and more organized for me that way.

For the record, the algorithm for fetching the information has been tested and is working properly if run through a servlet with a printwriter executing all of the html code. I now want to separate the html/jsp from the java to maintain better coding practice.

How would I invoke my service() method and fill the textarea in my jsp with the desired values from my query?

Thank you.

Servlet:

/**
 * Servlet implementation class Homepage
 */
@WebServlet(urlPatterns = { "/Homepage" })

public class Homepage extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection connection;
private Statement stmt;
private ResultSet rs;

/**
 * @see HttpServlet#HttpServlet()
 */
public Homepage() {
    super();
}

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();

    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        System.out.println("driver found");
        connection = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1;" +
                "instance=SQLEXPRESS;databaseName=Timecard_DB;user=Dan;password=12345;");

        try {
            stmt = connection.createStatement();
            String feedSelect = "SELECT ROLE_NAME from ROLES";
            rs = stmt.executeQuery(feedSelect);
            ResultSetMetaData metadata = rs.getMetaData();
            while(rs.next()) {
                for(int i = 1; i <= metadata.getColumnCount(); i++) {
                    String colValue = rs.getString(i);
                    out.println(colValue);
                }
            }
        }

        catch (SQLException e) {
            e.printStackTrace();
        }   
    } 
    catch (Exception e) {
        e.printStackTrace();
        e.getMessage();
    }
    response.setContentType("text/html");
}

JSP:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>

<style>
body {
background-image: url(Images/whitebg.jpg);
background-repeat: no-repeat;
background-size: 100%;
}

#container {
width: 900px;
margin: 0 auto;
font-family: "Trebuchet MS", Helvetica, sans-serif;
}

#header img {
position: absolute;
top: 80px;
left: 72px;
width: 200px;
height: 50px;
}

#container a:visited {
color: blue;
}

#container a:hover {
color: red;
}

#welcome {
position: absolute;
top: 20px;
right: 100px;
}

#logout {
position: absolute;
top: 20px;
right: 20px;
width: 50px;
height:25px;
}

#links {
position: absolute;
top: 200px;
left: 72px;
}

#links ul {
list-style-type: none;
padding: 5px 10px 5px 10px;
border: 2px solid red;
border-radius: 10px;
}

#links li {
padding: 10px 0 25px 0;
}

#feed {
position: absolute;
top: 100px;
left: 400px;
width: 800px;
height: 400px;
}

#feedtext {
width:800px;
height:400px;
overflow: scroll;
}
</style>
</head>

<body>

<div id='container'>

<div id='header'>
    <img src='Images/mPowerlogo.jpg'/>
</div>

<div id='welcome'>
    Welcome, User1
</div>

<div id='logout'>
    <a href=''>Logout</a>
</div>

<div id='links'>
    <ul>
    <li><a href=''>Timecard Management</a></li>
    <li><a href=''>User Management</a></li>
    <li><a href=''>Customer Management</a></li>
    <li><a href=''>Admin</a></li>
    <li><a href=''>Reports</a></li>
    </ul>
</div>

<div id='feed'>
    <p>Recent Activity:</p>
        <textarea id='feedtext' readonly>
            ***WANT DB INFO HERE***
        </textarea>
</div>

</div>

</body>
</html>

Upvotes: 0

Views: 5177

Answers (1)

visola
visola

Reputation: 7502

First your class needs to override the doPost or doGet method from HttpServlet.

Then, when you go to your Homepage, the servlet would receive the request, process the data and add it to the request. In your loop you would do something like:

StringBuilder data = new StringBuilder();
while (rs.next()) {
    for (...) {
        data.append(rs.getString(i));
        data.append("|"); // Some separator
    }
    data.append("\n");
}

request.setAttribute("data", data);

After that you need to redirect to the JSP:

RequestDispatcher dispatcher = request.getRequestDispatcher("/pathToJsp");
dispatcher.forward(request, response);

And last you get the data in your JSP:

<textarea>
    ${data} <%-- This will grab data from the request attribute --%>
</textarea>

You need to be concerned about HTML injection in case some one save HTML in your database. This would be rendered on the browser.

In JSP you can use Expression Language to access data from the request.

Upvotes: 1

Related Questions