First create a Javabean class that represents a single row of the table. I have no idea what data you are saying, but let User take it as an example of the real world:
public class User { private Long id; private String name; private Integer age;
This, of course, is an example. You need to specify the class and properties, respectively, that represent the actual data.
Now create a DAO class that performs the desired task of interacting with the database using JDBC . You only need to make sure that you have the correct SQL Server JDBC driver in the classpath. I can recommend jTDS for this, as it is much better and faster than Microsoft's own JDBC drivers. Well, suppose you want to list all User that are of the same age :
public List<User> listByAge(Integer age) throws SQLException { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; List<User> users = new ArrayList<User>(); try { connection = database.getConnection(); statement = connection.prepareStatement("SELECT id, name, age FROM user WHERE age = ?"); statement.setInt(1, age); resultSet = statement.executeQuery(); while (resultSet.next()) { User user = new User(); user.setId(resultSet.getLong("id")); user.setName(resultSet.getString("name")); user.setAge(resultSet.getInt("age")); users.add(user); } } finally { if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {} if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {} if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {} } return users; }
Now create the UsersServlet servlet class that preprocesses the data in the doGet() method.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<User> users = userDAO.list(); request.setAttribute("users", users); request.getRequestDispatcher("/WEB-INF/users.jsp").forward(request, response); }
Map this servlet in web.xml as follows:
<servlet> <servlet-name>users</servlet-name> <servlet-class>mypackage.UsersServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>users</servlet-name> <url-pattern>/users</url-pattern> </servlet-mapping>
Note the <url-pattern> , you can run this servlet http://example.com/context/users .
Now create a users.jsp JSP file that you put in the WEB-INF folder so that no one can access it directly without using a servlet. You can use JSTL c:forEach to iterate over List :
<table> <thead> <tr><th>ID</th><th>Name</th><th>Age</th></tr> </thead> <tbody> <c:forEach items="${users}" var="user"> <tr><td>${user.id}</td><td>${user.name}</td><td>${user.age}</td></tr> </c:forEach> </tbody> </table>
Run it http://example.com/context/users . It should be.