Java EE 8 Development with Eclipse
上QQ阅读APP看书,第一时间看更新

Creating JSP

We will perform the following steps to create the JSP:

  1. Right-click on the WebContent folder and select New | JSP File. Name it index.jsp. The file will open in the editor with the split view. The top part shows the design view, and the bottom part shows the code. If the file is not opened in the split editor, right-click on index.jsp in the Project Explorer and select Open With | Web Page Editor.

Figure 2.10: The JSP editor

  1. If you do not like the split view and want to see either the full design view or the full code view, then use appropriate toolbar buttons at the top right, as shown in the following screenshot:

Figure 2.11: The JSP editor display buttons

  1. Change the title from Insert title here to Login.
  2. Let's now see how Eclipse provides code assistance for HTML tags. Note that input fields must be in a form tag. We will add a form tag later. Inside the body tag, type the User Name: label. Then, type <. If you wait for a moment, Eclipse pops up the code assist window showing options for all the valid HTML tags. You can also invoke code assist manually.
  3. Place a caret just after < and press Ctrl + Spacebar.

Figure 2.12: HTML code assist in JSP

Code assist works on partial text too; for example, if you invoke code assist after text <i, you will see a list of HTML tags starting with i (i, iframe, img, input, and so on). You can also use code assist for tag attributes and attribute values.
For now, we want to insert the input field for username.

  1. Select input from the code assist proposals, or type it.
  2. After the input element is inserted, move the caret inside the closing > and invoke code assist again (Ctrl/Cmd + Spacebar). You will see the list of proposals for the attributes of the input tag.

Figure 2.13: Code assist for the tag attribute value

  1. Type the following code to create a login form:
<body> 
  <h2>Login:</h2> 
  <form method="post"> 
    User Name: <input type="text" name="userName"><br> 
    Password: <input type="password" name="password"><br> 
    <button type="submit" name="submit">Submit</button> 
    <button type="reset">Reset</button> 
  </form> 
</body> 
 

Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books that you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you.

If you are using the split editor (design and source pages), you can see the login form rendered in the design view. If you want to see how the page would look in the web browser, click the Preview tab at the bottom of the editor. You will see that the web page is displayed in the browser view inside the editor. Therefore, you don't need to move out of Eclipse to test your web pages.

Figure 2.14: Design and Source views

If you click on any user interface control in the design view, you will see its properties in the Properties view (see Figure 2.14). You can edit properties, such as Name and Value of the selected element. Click on the Style tab of the Properties window to edit CSS styles of the element.

We have not specified the action attribute in the previous form. This attribute specifies a URL to which the form data is to be posted when the user clicks the Submit button. If this attribute is not specified, then the request or the form data would be submitted to the same page; in this case, the form data would be submitted to index.jsp. We will now write the code to handle form data.

As mentioned in Chapter 1, Introducing JEE and Eclipse, you can write Java code and the client-side code (HTML, CSS, and JavaScript) in the same JSP. It is not considered good practice to mix Java code with HTML code, but we will do that anyway in this example to keep the code simpler. Later in the book, we will see how to make our code modular.

Java code is written in JSP between <% and %>; such Java code blocks in JSP are called scriptlets. You can also set page-level attributes in JSP. They are called page directives and are included between <%@ and %>. The JSP that we created already has a page directive to set the content type of the page. The content type tells the browser the type of response (in this case, html/text) returned by the server. The browser displays an appropriate response based on the content type:

<%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding="UTF-8"%> 

In JSP you have access to a number of objects to help you process and generate the response, as described in the following table:

 

In this example, we are going to make use of request and out objects. We will first check whether the form is submitted using the POST method. If true, we will get values of username and password fields. If the credentials are valid (in this example, we are going to hardcode username and the password as admin), we will print a welcome message:

<% 
  String errMsg = null; 
  //first check whether the form was submitted 
  if ("POST".equalsIgnoreCase(request.getMethod()) && 
request.getParameter("submit") != null) { //form was submitted String userName = request.getParameter("userName"); String password = request.getParameter("password"); if ("admin".equalsIgnoreCase(userName) &&
"admin".equalsIgnoreCase(password)) { //valid user System.out.println("Welcome admin !"); } else { //invalid user. Set error message errMsg = "Invalid user id or password. Please try again"; } } %>

We have used two built-in objects in the preceding code—request and out. We first check whether the form was submitted—"POST".equalsIgnoreCase(request.getMethod(). Then, we check whether the submit button was used to post the form—request.getParameter("submit") != null.

We then get the username and the password by calling the request.getParameter method. To keep the code simple, we compare them with the hardcoded values. In the real application, you would most probably validate credentials against a database or some naming and folder service. If the credentials are valid, we print a message by using the out (JSPWriter) object. If the credentials are not valid, we set an error message. We will print the error message, if any, just before the login form:

<h2>Login:</h2> 
  <!-- Check error message. If it is set, then display it --> 
  <%if (errMsg != null) { %> 
    <span style="color: red;"><%=;"><%=;"><%=errMsg %></span> 
  <%} %> 
  <form method="post"> 
  ... 
  </form> 

Here, we start another Java code block by using <%%>. If an error message is not null, we display it by using the span tag. Notice how the value of the error message is printed—<%=errMsg %>. This is a short syntax for <%out.print(errMsg);%>. Also notice that the curly brace that started in the first Java code block is completed in the next and separate Java code block. Between these two code blocks you can add any HTML code and it will be included in the response only if the conditional expression in the if statement is evaluated to true.

Here is the complete code of the JSP we created in this section:

<%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding="UTF-8"%> 
<!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=UTF-8"> <title>Login</title> </head> <% String errMsg = null; //first check whether the form was submitted if ("POST".equalsIgnoreCase(request.getMethod()) &&
request.getParameter("submit") != null) { //form was submitted String userName = request.getParameter("userName"); String password = request.getParameter("password"); if ("admin".equalsIgnoreCase(userName) &&
"admin".equalsIgnoreCase(password)) { //valid user out.println("Welcome admin !"); return; } else { //invalid user. Set error message errMsg = "Invalid user id or password. Please try again"; } } %> <body> <h2>Login:</h2> <!-- Check error message. If it is set, then display it --> <%if (errMsg != null) { %> <span style="color: red;"><%out.print(errMsg); %></span> <%} %> <form method="post"> User Name: <input type="text" name="userName"><br> Password: <input type="password" name="password"><br> <button type="submit" name="submit">Submit</button> <button type="reset">Reset</button> </form> </body> </html>