Java EE web programming (2)

Source: Internet
Author: User

Website Structure

Next, let's start the actual exercise.

The example is a simple logon website where the database uses MySQL. Servlet + JSP + JavaBean is used to complete the process. There are four JSP pages, one Servlet and one JavaBean. Although the website is simple, it is sufficient to describe this MVC development mode.

Figure 1

1. The first page you enter is login. JSP, log on to this page. If there is no such user or Password error, only error is entered. JSP. on this page, you can also go to the registration page Reg. JSP registration. Regardless of user authentication or user registration, validateservlet is transferred to userbean. In validateservlet, the business logic is basically not processed, it is only responsible for page navigation or forwarding content to JSP pages for display.

This design is also basically followed in some large projects (mature frameworks such as SSH are not considered for the moment): The model layer consists of various JavaBean and other Java classes, they implement almost all the actual functions of the website, modify data, and so on. The view layer consists of a large number of JSP or other pages, which constitute the overall appearance of the website, displays data in different styles. The controller layer consists of various servlets that forward JSP data requests to the JavaBean of the model layer, then, the model layer processing (obtaining) data is submitted to the appropriate JSP page for display, and the servlet has superior performance in controlling the page challenge, most of the page Jump logic of a website is also completed by Servlet, which plays a crucial role in controlling the three-tier model of the entire website.

Step by step

1. First, create a database test in MySQL. The database only contains one table person, which contains three fields (ID, name, password ).

2. Create a dynamic web project in eclipse and name it MVC. Then, the project structure 2 is created.

Figure 2

In this project, src directory is used to place the Java source file, and need to note that the directory is the webcontent directory, the directory is the root directory of webapp, webcontent directory has two word directory META-INF, WEB-INF, there is a web under the WEB-INF. XML document. This document is the configuration document of webapp. We need to configure servlet here later.

3. Create the preceding four JSP files in the webcontent directory.

The first is the login. jsp page, as shown in 3.

Figure 3

<%@ 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">

Here we can see two jump methods for the JSP page, using form action, and using <a href = xxx/>. Here, the form action = "Validate", this validate is a servlet, which will be explained later, and href jumps to the registered JSP page.

Then register Reg. jsp, which is very similar to the login page and does not post code, as shown in 4.

Figure 4

Then there is error. jsp, 5 on the error page.

Figure 5

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%>    <%    String error=(String)request.getParameter("error");    if(error==null)    error=(String)request.getAttribute("error");    %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

The error page is relatively simple, but it can be described in two ways of passing parameters. The error page always displays different error messages. Therefore, each request to jump to the error page must send an error message to the error page. If the request. getparameter () method is used to extract the parameters passed in the submitted form, or the parameters passed in the URL form, 5 the URL in the address bar is in this way. The parameters obtained using the request. getattribute () method are those previously put using the request. setattribute method.
After successful login, the main. jsp page is displayed, as shown in figure 6.

Figure 6

<%@ 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"><%String usr=(String)session.getAttribute("name");String pwd=(String)session.getAttribute("password");%>

The main. jsp page is relatively simple, just to show successful login users. Session is used to store user information, which is also a common method for websites. This method is safer than using cookies to store user login information. The Session object is directly used on this page. It is actually one of several common built-in objects in JSP, and also commonly used request, response, config, out, and so on.
4. Create the control layer servlet.

Package demos. MVC. servlets; import Java. io. ioexception; import Java. SQL. sqlexception; import javax. servlet. servletconfig; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import javax. servlet. HTTP. httpsession; import demos. MVC. beans. userbean; public class validateservlet extends httpservl Et {/***/Private Static final long serialversionuid = 1l; @ overridepublic void destroy () {// todo auto-generated method stub} @ overridepublic servletconfig getservletconfig () {// todo auto-generated method stubreturn NULL;} @ overridepublic string getservletinfo () {// todo auto-generated method stubreturn NULL;} @ overridepublic void Init (servletconfig arg0) throws servletexception {// todo auto-gene Rated method stub} @ overridepublic void Service (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {// todo auto-generated method stubstring user = request. getparameter ("LOGNAME"); string Pwd = request. getparameter ("logpass"); string Sign = request. getparameter ("sign"); string error = "error"; string errorcontent = ""; if (user = NULL | Pwd = NULL | user. isempty () | PWD. isemp Ty () {errorcontent = "User Name or password can't be empty! ";/* 1.how to go another page: Redirect *. can go to any URL * B. can't use httpservletrequest. setattribute to transfer parameters, * because this is an new HTTP request from client browser, the attributes you put in * have been wiped! You have to use URL with parameters to deliver parameters * C. In client browser address bar, there's the new address. * // response. sendredirect ("error. jsp? "+ Error +" = "+ errorcontent);/* 2.how to go another page: Forward *. can only go to the resources on the server * B. can use both httpservletrequest. setattribute and URL to transfer parameters. * C. in this way, it is the server use the current HTTP request to ask for something, * So, in client browser address bar, you can't see the Redirect address but the previous URL */request. setattribute (error, Errorcontent); Request. getrequestdispatcher ("error. JSP "). forward (request, response);} else if (request. getparameter ("sign") = NULL | request. getparameter ("sign "). isempty () {userbean USR = new userbean (); USR. setname (User); USR. setpassword (PWD); If (USR. isexists () {// store the user information into sessionhttpsession HS = request. getsession (); HS. setattribute ("name", user); HS. setattribute ("password", PWD); respon Se. sendredirect ("Main. jsp");} else {errorcontent = "User:" + User + "does not exist! Please sign in first "; response. sendredirect (" error. jsp? "+ Error +" = "+ errorcontent) ;}} else if (...) {// then omitted }}}

This is a very simple servlet that fully represents the servlet lifecycle.

Figure 7

The servlet only calls the init and destroy methods once throughout its lifecycle. However, once the servlet is created, the service method is called every time a request is made. These methods all come from the servlet interface. In their descendants, such as httpservlet and service, the dopost and doget methods are called to execute finer services.

This servlet shows the two methods of servlet challenge. The difference between the two methods is described in the annotations by using the response. sendredirect or requestdispatcher. Forward method. In addition, for convenience, the control logic here is put into a servlet, it seems that the verification servlet has a bloated service method, in fact, it can be divided into multiple Servlets to complete.

This servlet calls the userbean class, which is mainly used to connect to and query the database, and its code is not provided.

As you can see, it is very convenient to use servlet to control the logic, and it is clearer than to directly control the logic display in JSP.

5. Configure Servlet
Modify the Web. XML document below to configure our servlet.

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>MVC</display-name>  <servlet>    <servlet-name>ValidateServlet</servlet-name>    <servlet-class>demos.mvc.servlets.ValidateServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>ValidateServlet</servlet-name>    <url-pattern>/validate</url-pattern>  </servlet-mapping>  </web-app>

Here we can see where the validate Resource Locator Used for the previous JSP page Jump came from.

In short, using the three-tier MVC Architecture of JSP + servlet + JavaBean makes it possible to build a project with a large architecture, and understands the most basic things of javaee, in order to be more proficient in mastering those mature frameworks on javaee and understand their essence.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.