I have this little java project in which I have to use jsp files.
I have an html with a login button that triggers the following function:
var loginCall = "user/login";
var logoutCall = "user/logout";
var signupCall = "user/signup";
function login() {
var login = baseUrl + loginCall + "?";
var loginFormElements = document.forms.loginForm.elements;
login = addParam(login, USER_NAME, loginFormElements.userName.value, false);
login = addParam(login, PASSWORD, loginFormElements.password.value, true);
simpleHttpRequest(login, function(responseText){
var status = evalJSON(responseText);
if (status.errorCode == 200) {
var res = status.results;
var sessionId = res[0].sessionId;
setCookie(SESSION_ID,sessionId);
window.location="http://localhost:8080/"+baseUrl+"/main.html";
} else {
showError(status.errorCode, "Username or password was incorrect.")
}
}, function(status, statusText){console.log('z');
showError(status, statusText);
});
}
As far as I can see a httpRequest is made and sent with data to baseUrl + loginCall, meaning localhost/something/user/login?name=somename&pass=somepass
This is where I'm stuck, do I have to make a java file somewhere somehow, that takes the request information, works it up with the database and returns an answer?
If so, where, how? Do I have to name it login/user.java?
Can anyone point me to the right direction, if not give me some code example or explanation of what I have to do next?
You need to have another look at the JSP MVC
The jsp page should hold the html and javascript and java code. If you want to call a separate .java class, you need to write that class as a servlet then call it.
So in your .jsp you have you html and javascript just like you have it there, then any java you include in these brackets <% %>
Have a look at the tutorials here http://www.jsptut.com/
And i see your doing a login page. I used this brilliant tutorial for creating a log in system which helped me understand how jsp and servlets worked.
http://met.guc.edu.eg/OnlineTutorials/JSP%20-%20Servlets/Full%20Login%20Example.aspx
Also check out this image which should help you understand the concept. Remember servlets are pure java classes, used for mostly java but can also output html, jsp's are used for mostly html (& javascript) but can include jsp. So the servlets do the work, then the jsp gets the computed values so that they can be utilized by JavaScript. that's how i think of it anyway, may be wrong
http://met.guc.edu.eg/OnlineTutorials/static/article_media/jsp%20-%20servlets/LoginExample%20[4].jpg
All the best
If you are not using any MVC framework then best approach would be to extending HttpServlet classes for handling requests and doing all heavy lifting tasks such as business logic processing,accessing/updating databases etc. and then dispatching the request to .jsp files for presentation.In .jsp.You can also add custom objects to request scope that you wish to access on '.jsp' pages + using expression language you can access most request related implicit objects
I taken a typical example of flow in brief.You may can an idea and explore in deep yourself.
Here is java servlet class that will handle a posted form.
public class doLogin extends HttpServlet{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String username= request.getParameter("username"); // get username/pasword from form
String password = request.getParameter("password");
// This is your imaginary method for checking user authentication from database
if(checkUserAuthentication(username,password)){
/*
user is authenticated.Now fetch data for user to be shown on homepage
User is another class that holds user info. Initialize it with data received from database
*/
user userData = new User;
user.setName(...);
user.setAge(...);
user.setInfo(...);
// etc
}
RequestDispatcher view = req.getRequestDispatcher("login.jsp");
req.setAttribute("userdata", userData); // set user object in current request scope
view.forward(req, resp);//forward to login.jsp
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
}
but you need a form with some action to invoke above ServletClass
<form action="/checkLogin" method="POST">
<input type="text" name="username" value="">
<input type="password" name="password" value="">
<input type="submit" name="login" value="Login">
</form>
To tell your Servlet container to invoke doLogin class on form login button click
you have to configure it in deployment descriptor file web.xml which is part of standard dynamic web application in java
In web.xml' following xml snippet make apllication server aware ofdoLogin` class
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.yourdomain.doLogin</servlet-class>
</servlet>
But its not mapped to any url yet,It is configured as below in <servlet-mapping> section in web.xml
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/checkLogin</url-pattern>
</servlet-mapping>
Now any post request to url /checkLogin will invole doPost method on doLogin class
After successful login request will be trasfered to 'login.jsp' page.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
You can use java code in sciptlet <% %> syntax to access userData object
<%
User data = (User)request.getAttribute('userData');
%>
Better and tidy approach is to use expression language
${ pageContext.request.userData.name }
Above expression calls getName() method on object of User class using java beans naming conventions
Here, you can learn more about expression language
May be some time later I can improve this and provide you more insight.Hope that helps :)
Related
I've developed an HTML page that sends information to a Servlet. In the Servlet, I am using the methods doGet() and doPost():
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String id = req.getParameter("realname");
String password = req.getParameter("mypassword");
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String id = req.getParameter("realname");
String password = req.getParameter("mypassword");
}
In the html page code that calls the Servlet is:
<form action="identification" method="post" enctype="multipart/form-data">
User Name: <input type="text" name="realname">
Password: <input type="password" name="mypassword">
<input type="submit" value="Identification">
</form>
When I use method = "get" in the Servlet, I get the value of id and password, however when using method = "post", id and password are set to null. Why don't I get the values in this case?
Another thing I'd like to know is how to use the data generated or validated by the Servlet. For example, if the Servlet shown above authenticates the user, I'd like to print the user id in my HTML page. I should be able to send the string 'id' as a response and use this info in my HTML page. Is it possible?
Introduction
You should use doGet() when you want to intercept on HTTP GET requests. You should use doPost() when you want to intercept on HTTP POST requests. That's all. Do not port the one to the other or vice versa (such as in Netbeans' unfortunate auto-generated processRequest() method). This makes no utter sense.
GET
Usually, HTTP GET requests are idempotent. I.e. you get exactly the same result everytime you execute the request (leaving authorization/authentication and the time-sensitive nature of the page —search results, last news, etc— outside consideration). We can talk about a bookmarkable request. Clicking a link, clicking a bookmark, entering raw URL in browser address bar, etcetera will all fire a HTTP GET request. If a Servlet is listening on the URL in question, then its doGet() method will be called. It's usually used to preprocess a request. I.e. doing some business stuff before presenting the HTML output from a JSP, such as gathering data for display in a table.
#WebServlet("/products")
public class ProductsServlet extends HttpServlet {
#EJB
private ProductService productService;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = productService.list();
request.setAttribute("products", products); // Will be available as ${products} in JSP
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
}
}
Note that the JSP file is explicitly placed in /WEB-INF folder in order to prevent endusers being able to access it directly without invoking the preprocessing servlet (and thus end up getting confused by seeing an empty table).
<table>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.name}</td>
<td>detail</td>
</tr>
</c:forEach>
</table>
Also view/edit detail links as shown in last column above are usually idempotent.
#WebServlet("/product")
public class ProductServlet extends HttpServlet {
#EJB
private ProductService productService;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Product product = productService.find(request.getParameter("id"));
request.setAttribute("product", product); // Will be available as ${product} in JSP
request.getRequestDispatcher("/WEB-INF/product.jsp").forward(request, response);
}
}
<dl>
<dt>ID</dt>
<dd>${product.id}</dd>
<dt>Name</dt>
<dd>${product.name}</dd>
<dt>Description</dt>
<dd>${product.description}</dd>
<dt>Price</dt>
<dd>${product.price}</dd>
<dt>Image</dt>
<dd><img src="productImage?id=${product.id}" /></dd>
</dl>
POST
HTTP POST requests are not idempotent. If the enduser has submitted a POST form on an URL beforehand, which hasn't performed a redirect, then the URL is not necessarily bookmarkable. The submitted form data is not reflected in the URL. Copypasting the URL into a new browser window/tab may not necessarily yield exactly the same result as after the form submit. Such an URL is then not bookmarkable. If a Servlet is listening on the URL in question, then its doPost() will be called. It's usually used to postprocess a request. I.e. gathering data from a submitted HTML form and doing some business stuff with it (conversion, validation, saving in DB, etcetera). Finally usually the result is presented as HTML from the forwarded JSP page.
<form action="login" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="login">
<span class="error">${error}</span>
</form>
...which can be used in combination with this piece of Servlet:
#WebServlet("/login")
public class LoginServlet extends HttpServlet {
#EJB
private UserService userService;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userService.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
response.sendRedirect("home");
}
else {
request.setAttribute("error", "Unknown user, please try again");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
}
You see, if the User is found in DB (i.e. username and password are valid), then the User will be put in session scope (i.e. "logged in") and the servlet will redirect to some main page (this example goes to http://example.com/contextname/home), else it will set an error message and forward the request back to the same JSP page so that the message get displayed by ${error}.
You can if necessary also "hide" the login.jsp in /WEB-INF/login.jsp so that the users can only access it by the servlet. This keeps the URL clean http://example.com/contextname/login. All you need to do is to add a doGet() to the servlet like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
(and update the same line in doPost() accordingly)
That said, I am not sure if it is just playing around and shooting in the dark, but the code which you posted doesn't look good (such as using compareTo() instead of equals() and digging in the parameternames instead of just using getParameter() and the id and password seems to be declared as servlet instance variables — which is NOT threadsafe). So I would strongly recommend to learn a bit more about basic Java SE API using the Oracle tutorials (check the chapter "Trails Covering the Basics") and how to use JSP/Servlets the right way using those tutorials.
See also:
Our servlets wiki page
Java EE web development, where do I start and what skills do I need?
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
Update: as per the update of your question (which is pretty major, you should not remove parts of your original question, this would make the answers worthless .. rather add the information in a new block) , it turns out that you're unnecessarily setting form's encoding type to multipart/form-data. This will send the request parameters in a different composition than the (default) application/x-www-form-urlencoded which sends the request parameters as a query string (e.g. name1=value1&name2=value2&name3=value3). You only need multipart/form-data whenever you have a <input type="file"> element in the form to upload files which may be non-character data (binary data). This is not the case in your case, so just remove it and it will work as expected. If you ever need to upload files, then you'll have to set the encoding type so and parse the request body yourself. Usually you use the Apache Commons FileUpload there for, but if you're already on fresh new Servlet 3.0 API, then you can just use builtin facilities starting with HttpServletRequest#getPart(). See also this answer for a concrete example: How to upload files to server using JSP/Servlet?
Both GET and POST are used by the browser to request a single resource from the server. Each resource requires a separate GET or POST request.
The GET method is most commonly (and is the default method) used by browsers to retrieve information from servers. When using the GET method the 3rd section of the request packet, which is the request body, remains empty.
The GET method is used in one of two ways:
When no method is specified, that is when you or the browser is requesting a simple resource such as an HTML page, an image, etc.
When a form is submitted, and you choose method=GET on the HTML tag. If the GET method is used with an HTML form, then the data collected through the form is sent to the server by appending a "?" to the end of the URL, and then adding all name=value pairs (name of the html form field and value entered in that field) separated by an "&"
Example:
GET /sultans/shop//form1.jsp?name=Sam%20Sultan&iceCream=vanilla HTTP/1.0 optional headeroptional header<< empty line >>>
The name=value form data will be stored in an environment variable called QUERY_STRING.
This variable will be sent to a processing program (such as JSP, Java servlet, PHP etc.)
The POST method is used when you create an HTML form, and request method=POST as part of the tag. The POST method allows the client to send form data to the server in the request body section of the request (as discussed earlier). The data is encoded and is formatted similar to the GET method, except that the data is sent to the program through the standard input.
Example:
POST /sultans/shop//form1.jsp HTTP/1.0 optional headeroptional header<< empty line >>> name=Sam%20Sultan&iceCream=vanilla
When using the post method, the QUERY_STRING environment variable will be empty.
Advantages/Disadvantages of GET vs. POST
Advantages of the GET method:
Slightly faster
Parameters can be entered via a form or by appending them after the URL
Page can be bookmarked with its parameters
Disadvantages of the GET method:
Can only send 4K worth of data. (You should not use it when using a textarea field)
Parameters are visible at the end of the URL
Advantages of the POST method:
Parameters are not visible at the end of the URL. (Use for sensitive data)
Can send more that 4K worth of data to server
Disadvantages of the POST method:
Can cannot be bookmarked with its data
The servlet container's implementation of HttpServlet.service() method will automatically forward to doGet() or doPost() as necessary, so you shouldn't need to override the service method.
Could it be that you are passing the data through get, not post?
<form method="get" ..>
..
</form>
If you do <form action="identification" > for your html form, data will be passed using 'Get' by default and hence you can catch this using doGet function in your java servlet code. This way data will be passed under the HTML header and hence will be visible in the URL when submitted.
On the other hand if you want to pass data in HTML body, then USE Post: <form action="identification" method="post"> and catch this data in doPost function. This was, data will be passed under the html body and not the html header, and you will not see the data in the URL after submitting the form.
Examples from my html:
<body>
<form action="StartProcessUrl" method="post">
.....
.....
Examples from my java servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
String surname = request.getParameter("txtSurname");
String firstname = request.getParameter("txtForename");
String rqNo = request.getParameter("txtRQ6");
String nhsNo = request.getParameter("txtNHSNo");
String attachment1 = request.getParameter("base64textarea1");
String attachment2 = request.getParameter("base64textarea2");
.........
.........
Please help me to understand what should I do if I want to update my jsp page after using filter.
For example, my jsp page /index.jsp contains <div id="login-id"> that I would like to update.
I have a filter that looks like:
<filter-mapping>
<filter-name>AccessFilter</filter-name>
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
public class AccessFilter implements Filter {
private LoginChecker loginChecker;
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//some code goes here where I get name and hash from the cookies
loginChecker = new LoginChecker();
if (loginChecker.isLoggedIn(name, hash)) {
// here I want to send something into my div
} else {
}
chain.doFilter(request, response);
}
I guess that I need to do something like this:
HttpServletResponse resp = (HttpServletResponse) response;
resp.getWriter().write("12345");
chain.doFilter(request, resp);
And add to index like:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$.get('index.jsp', function(data) {
console.log("data = " + data);
});
</script>
But I think I am wrong because I get whole page instead of just "12345".
Thank you.
in your case I believe what you are trying to achieve is actually just retrieving values you generated in your Filter in the JSP documents. If this is correct you can go a route like this.
The class HttpServletRequest features the getter/setter setAttributes and getAttributes which you can use very similarly to what you are used to from POST and GET parameters.
In you filter you are then able to set arbitrary data to the attributes map like this.
request.setAttribute("data", "my data");
If this data is later needed in your JSP you can do something like this:
First make sure that EL Expressions are evaluated in your JSP page by setting the following in the page header:
<%# page isELIgnored="false" %>
Then you can access the request attributes like this:
<p>Hello world this is my JSP and we received ${data} from our filter</p>
To clarify the request attributes. Opposed to session attributes the request attributes only live for the time of a single request. This means an usually empty map is created at the beginning of each HTTP request and then gradually gets filled with additional information during the processing run of the request.
I am using Spring 3. In my jsp I have a form
<form action='componentAction.html' method='POST'>
<input type='hidden' id='action_' name='componentAction' value=""/>
</form>
The value of the form's action changes to either start, stop or pause.
I also have 3 buttons: start, stop and pause. Upon pressing one of these buttons the value of the form changes.
<input type="button" value="Start" onclick="changeFormValueAndSubmit('start')">
<input type="button" value="Stop" onclick="changeFormValueAndSubmit('stop')">
<input type="button" value="Pause" onclick="changeFormValueAndSubmit('pause')">
I would like to be able to send the value of the form to my controller via ajax call after the press happens.
Can someone please show me the right way of doing it? Alsos hould I use POST or GET?
I have tried following tutorials such as
http://www.raistudies.com/spring/spring-mvc/ajax-spring-mvc-3-annonations-jquery/
http://hmkcode.com/spring-mvc-json-json-to-java/
http://java.dzone.com/articles/using-spring-mvc%E2%80%99s
But I have failed miserably.
Thanks to anyone for their hlep in advance!
Using JQuery you can use the following in your changeFormValueAndSubmit() function
function changeFormValueAndSubmit(buttonName) {
var formData = $('form').serialize();
jQuery.post('/path', formData, function(d) {
// handle response
});
...
}
Note: that in this example, jquery will send all the data fields in your form.
Make your you include the jquery framework in your JSP and also have a controller method in spring to handle the POST.
POST is preferable over GET.
On server side using Spring 3 annotations, something like
#Controller
public class ExampleController {
#ResponseBody
#RequestMapping(value = "/path", method=RequestMethod.POST)
public String post(#RequestParam String componentAction) {
// do work
...
return "OK"; // depends on what you need to send back...
}
}
You must enable MVC annotations. See http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html#mvc-annotation-driven
POST or GET will determine if the form data is sent encoded in the URL (GET) or in embedded in the http requests message body (POST). Since it is an ajax call, the URL will not be shown directly to the user, but either way, the user can see the contents of the request under the browser's developer tools.
The simplest way to get spring to direct traffic to your jsp is like such:
<servlet-mapping>
<servlet-name>MyJSPServlet</servlet-name>
<url-pattern>/urlFromOutside</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>MyJSPServlet</servlet-name>
<jsp-file>/pathToJspFile/MyJspFile.jsp</jsp-file>
</servlet>
To get the form data, in your jsp file, you have access to the request object and can get the parameters like so:
<%= request.getParameter("componentAction") %>
How would I pass hidden parameters? I want to call a page (test.jsp) but also pass 2 hidden parameters like a post.
response.sendRedirect("/content/test.jsp");
TheNewIdiot's answer successfully explains the problem and the reason why you can't send attributes in request through a redirect. Possible solutions:
Using forwarding. This will enable that request attributes could be passed to the view and you can use them in form of ServletRequest#getAttribute or by using Expression Language and JSTL. Short example (reusing TheNewIdiot's answer] code).
Controller (your servlet)
request.setAttribute("message", "Hello world");
RequestDispatcher dispatcher = servletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
View (your JSP)
Using scriptlets:
<%
out.println(request.getAttribute("message"));
%>
This is just for information purposes. Scriptlets usage must be avoided: How to avoid Java code in JSP files?. Below there is the example using EL and JSTL.
<c:out value="${message}" />
If you can't use forwarding (because you don't like it or you don't feel it that way or because you must use a redirect) then an option would be saving a message as a session attribute, then redirect to your view, recover the session attribute in your view and remove it from session. Remember to always have your user session with only relevant data. Code example
Controller
//if request is not from HttpServletRequest, you should do a typecast before
HttpSession session = request.getSession(false);
//save message in session
session.setAttribute("helloWorld", "Hello world");
response.sendRedirect("/content/test.jsp");
View
Again, showing this using scriptlets and then EL + JSTL:
<%
out.println(session.getAttribute("message"));
session.removeAttribute("message");
%>
<c:out value="${sessionScope.message}" />
<c:remove var="message" scope="session" />
Generally, you cannot send a POST request using sendRedirect() method. You can use RequestDispatcher to forward() requests with parameters within the same web application, same context.
RequestDispatcher dispatcher = servletContext().getRequestDispatcher("test.jsp");
dispatcher.forward(request, response);
The HTTP spec states that all redirects must be in the form of a GET (or HEAD).
You can consider encrypting your query string parameters if security is an issue.
Another way is you can POST to the target by having a hidden form with method POST and submitting it with javascript when the page is loaded.
Using session, I successfully passed a parameter (name) from servlet #1 to servlet #2, using response.sendRedirect in servlet #1. Servlet #1 code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String name = request.getParameter("name");
String password = request.getParameter("password");
...
request.getSession().setAttribute("name", name);
response.sendRedirect("/todo.do");
In Servlet #2, you don't need to get name back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name"); ---but you don't need this.
If Servlet #2 calls a JSP, you can show name this way on the JSP webpage:
<h1>Welcome ${name}</h1>
To send a variable value through URL in response.sendRedirect(). I have used it for one variable, you can also use it for two variable by proper concatenation.
String value="xyz";
response.sendRedirect("/content/test.jsp?var="+value);
Use this:
out.println("<script>window.location.href = \"hoadon?OrderId=" + getIdOrder + "\"\n</script>>");
I have a doubt regarding the use of servlets.
In the application I'm building I use Html pages to ask the user for info.
Imagine a Html page that lets the user request to see on the screen the content of a data base. What I'm doing is:
1.- From the Html page I'm calling a servlet that will open a connection with the database.
2.- The servlet builds the web page that the user will see.
My question is: is there any other way of doing this? Do I have to build the web page in the servlet or is there any way of sending the information contained in the database to an .html file which will build the web page (in my case I need to show on the screen a table containing all the information) ?
Thanks
Servlets are meant to control, preprocess and/or postprocess requests, not to present the data. There the JSP is for as being a view technology providing a template to write HTML/CSS/JS in. You can control the page flow with help of taglibs like JSTL and access any scoped attributes using EL.
First create a SearchServlet and map it on an url-pattern of /search and implement doGet() and doPost() as follows:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Preprocess request here and finally send request to JSP for display.
request.getRequestDispatcher("/WEB-INF/search.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Postprocess request here. Get results from your DAO and store in request scope.
String search = request.getParameter("search");
List<Result> results = searchDAO.find(search);
request.setAttribute("results", results);
request.getRequestDispatcher("/WEB-INF/search.jsp").forward(request, response);
}
Here's how the JSP /WEB-INF/search.jsp would look like, it makes use of JSTL (just drop JAR in /WEB-INF/lib) to control the page flow.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<form action="search" method="post">
<input type="text" name="search">
<input type="submit" value="search">
</form>
<c:if test="${not empty results}">
<p>There are ${fn:length(results)} results.</p>
<table>
<c:forEach items="${results}" var="result">
<tr>
<td>${result.id}</td>
<td>${result.name}</td>
<td>${result.value}</td>
</tr>
</c:forEach>
</table>
</c:if>
Note that JSP is placed in /WEB-INF to prevent users from direct access by URL. They are forced to use the servlet for that by http://example.com/contextname/search.
To learn more about JSP/Servlets, I can recommend Marty Hall's Coreservlets.com tutorials. To learn more about the logic behind searchDAO, I can recommend this basic DAO tutorial.
To go a step further, you could always consider to make use of a MVC framework which is built on top of the Servlet API, such as Sun JSF, Apache Struts, Spring MVC, etcetera so that you basically end up with only Javabeans and JSP/XHTML files. The average MVC frameworks will take care about gathering request parameters, valitate/convert them, update Javabeans with those values, invoke some Javabean action method to process them, etcetera. This makes the servlet "superfluous" (which is however still used as being the core processor of the framework).
In addition to Servlets, Java has JSP pages, which are a mix of HTML and custom tags (including the Java Standard Tag Library or JSTL) which are eventually compiled into Servlets.
There are other technologies for making web applications, including things like Java Server Faces (JSF), Apache Struts, Spring, etc... Spring in particular is very widely used in modern web application development.
Ultimately, though, it's like Brian Agnew said... you have to communicate back and forth from the browser to the server. These are just various technologies to facilitate that.
Ultimately the browser has to send a request to the server for the database info. You can do this in many ways:
build the whole page in the servlet (perhaps the simplest)
build a page in the servlet containing (say) XML data, and the browser renders it into HTML (via XSL/Javascript etc.). That may be suitable if you want the browser to control the formatting and presentation.
build a page containing AJAX requests to go back to the server and get the data. That may be more suitable for data that updates regularly, or more interactive applications.
There are numerous ways to skin this cat. I suspect you're doing the simplest one, which is fine. I would tend towards this without explicit requirements that mean I need to do something else. Further requirements that complicate matters may include paging the data if there's too much to fit on the screen. All the solutions above can be made to incorporate this in some fashion.
My java is rusty but...
in your Data Access layer, iterate over the result set and build a custom object and insert it into an ArrayList;
class DataAccess {
public ArrayList foo() {
// Connect to DB
// Execute Query
// Populate resultSet
ArrayList result = new ArrayList();
while (resultSet.hasNext()) {
CustomObject o = new CustomObject();
o.setProperty1(resultSet.getInt(1));
o.setProperty2(resultSet.getString(2));
// and so on
result.add(o);
}
return result;
}
}
Call this method from your Servlet. After you have populated the ArrayList, put it on the Request object and forward on to your .jsp page
ArrayList results = DataAccessClass.foo();
Request.setAttribute("Results", results);
In your jsp, build your markup using scriptlets
<% foreach (CustomObject o in Request.getAttribute("Results"))
{%>
<td><%= o.getProperty1()</td>
<td><%= o.getProperty2()</td>
<% } %>
Good luck