Javaweb Learning Summary (21) Two development modes of--javaweb

Source: Internet
Author: User

After Sun introduced JSP technology, it also recommended two kinds of Web application development mode, one is Jsp+javabean mode, one is Servlet+jsp+javabean mode.

First, Jsp+javabean development mode 1.1, Jsp+javabean Development mode architecture

The architecture of the Jsp+javabean development model is shown in Turu (Figure 1-1)

Figure 1-1

In the Jsp+javabean architecture, the JSP is responsible for controlling the invocation of logic, representation logic, business Objects (JavaBean).

The Jsp+javabean model is suitable for developing Web applications where the business logic is less complex, in which the JavaBean is used to encapsulate the business data, and the JSP is responsible for processing the user request and displaying the data.

1.2, Jsp+javabean development model Writing Calculator

First analysis of JSP and JavaBean respective responsibilities, JSP is responsible for displaying the calculator (Calculator) page, for the user input calculation data, and display the calculated results, JavaBean is responsible for receiving user input calculation data and calculation, JavaBean has firstnum, secondnum, result, operator attributes, and provides a calculate method.

1, write Calculatorbean, responsible for receiving user input calculation data and calculation

The Calculatorbean code is as follows:

 1 package me.gacl.domain; 2 3 Import Java.math.BigDecimal;     4 5/** 6 * @author gacl 7 * Calculatorbean for receiving input parameters and calculation 8 */9 public class Calculatorbean {10 11//user input first number 12  Private double firstnum;13//user input second number in the private double secondnum;15//user-selected operator of the operator for the private char operator     = ' + '; 17//Result of Operation Result;19 Double Getfirstnum () {firstnum;22 }23 public void Setfirstnum (double firstnum) {this.firstnum = firstnum;26}27-public double g Etsecondnum () {secondnum return secondnum;30}31-public void Setsecondnum (double this.s)  Econdnum = secondnum;34}35-Public char getoperator () {PNS return operator;38}39-public void Setoperator (char operator) {this.operator = operator;42}43, public double GetResult () {R Eturn result;46}47-public void setresult (double result) {.result = Result;50}51 52/**53 * For calculation of the */55 public void Calculate () {. This.op Erator) {$ Case ' + ': {this.result = this.firstnum + this.secondnum;60 Brea                 k;61}62 case '-': {This.result = this.firstnum-this.secondnum;64                 break;65}66 Case ' * ': {this.result = This.firstnum * this.secondnum;68                     break;69}70 case '/': {if (this.secondnum = = 0) {72 throw new RuntimeException ("dividend cannot be 0!!!");                 }74 This.result = this.firstnum/this.secondnum;75//Rounding 76 This.result = new BigDecimal (this.result). Setscale (2,77 bigdecimal.round_half_up). Doubleval UE (); break;79}80 default:81 throw new RuntimeException ("Sorry, the operator passed in is illegal!! "); 82}83}84}
2, write calculator.jsp, responsible for displaying the calculator (Calculator) page, for the user input calculation data, and display the calculated results

The calculator.jsp page code is as follows:

 1 <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> 2 <%--using Me.gacl.domain.CalculatorBean --%> 3 <jsp:usebean id= "Calcbean" class= "Me.gacl.domain.CalculatorBean"/> 4 <%--receive user input parameters--%> 5 <jsp : SetProperty name= "Calcbean" property= "*"/> 6 <% 7//Use Calculatorbean to calculate 8 calcbean.calculate (); 9%>10 <! DOCTYPE html>11 

The results of the operation are as follows:

  

Second, the Servlet+jsp+javabean development model

In peacetime Javaweb project development, without the use of third-party MVC development Framework, usually choose Servlet+jsp+javabean development model to develop Javaweb project, servlet+jsp+ JavaBean combination development is an MVC development pattern, the controller uses the servlet, the model, the JavaBean, the Views (view) uses the JSP. Before explaining the Servlet+jsp+javabean development model, take a brief look at the MVC development model.

2.1. Request-response model in web development

Figure 2-1

In the Web world, the steps are as follows:

1, Web browsers (such as IE) initiate a request, such as access to http://www.iteye.com/

2. The Web server (such as Tomcat) receives the request, processes the request (for example, the user adds it, saves the user), and finally produces a response (typically HTML).

3. After the Web server is processed, the content is returned to the Web client (usually our browser), and the client processes the received content (for example, the Web browser will render the HTML content it receives to show to the customer).

therefore, in the Web World: The Web client initiates the request, the Web server receives, processes, and generates a response.

The general Web server is unable to proactively notify the Web client of the update content. Although there are some technologies such as server push (such as comet), and now HTML5 WebSocket can implement the Web server to actively notify the Web client.

Here we understand the request/response model for Web development, and then we look at what the standard MVC model is.

2.2. Overview of the standard MVC model

MVC Model: is an architectural pattern, it does not introduce new functionality, it just helps us to make the structure of the development more reasonable, so that the presentation and model separation, Process Control logic, business logic calls and display logic separation. As shown in (Figure 2-2):

Figure 2-2

2.3. The concept of MVC (Model-view-controller)

  Let's start by understanding the concept of MVC(model-view-controller) :

Model (model): A data model that provides data to be presented and therefore contains data and behavior that can be thought of as a domain model (domain) or JavaBean component (containing data and behavior), but is now generally separated: Value Object (data) and Service layer (behavior). that is, the model provides features such as model data query and status update of model data, including data and business.

View (view): Responsible for the presentation of the model, generally we see the user interface, what the customer wants to see.

Controller (Controller): Receive user requests, delegate to the model for processing (state change), after processing the returned model data back to the view, the view is responsible for the display. in other words , the controller did a dispatcher's job.

From Figure 2-1 We also see that in the standard MVC model can proactively push the data to update the view (The Observer design pattern, register the view on the model, update the view automatically when the model is updated), but in web development the model is unable to proactively push the view (unable to proactively update the user interface), Because in web development is the request-response model.

Then let's look at what MVC looks like in the web, and we call it web MVC to differentiate standard MVC.

2.4., Web MVC Overview

The M (model)-V (view)-C (Controller) concept in Web MVC is like the standard MVC concept, and we look at the Web MVC Standard architecture, as shown in Figure 2-3:

Figure 2-3

In Web MVC mode, the model cannot proactively push the data to the view, and if the user wants the view to be updated, it needs to send another request (that is, the request-response model).

2.5, Servlet+jsp+javabean Development Mode Introduction

The Servlet+jsp+javabean architecture can actually be thought of as what we call the Web MVC model, except that the controller uses Servlets, the model adopts JavaBean, the view uses the Jsp,2-3

Figure 2-4

Specific sample code:

1. Model

  

2. Views (view)

  

3. Controllers (Controller)

  

As you can see from the Servlet+jsp+javabean (Web MVC) architecture, the view and model are separated, and the control logic and presentation logic are separated.

Third, the shortcomings of Servlet+jsp+javabean development model

Although the Servlet+jsp+javabean (Web MVC) architecture implements the separation of views and models, and the separation of control logic and presentation logic, there are also some of the more serious drawbacks

3.1, the servlet as a controller disadvantage

The controller here uses a servlet, and using the servlet as a controller has several drawbacks:

  1, control logic may be more complex , in fact, we can according to the specification, such as request parameter submitflag=tologin, we can actually call the Tologin method directly, to simplify the control logic, and each module basically needs a controller, The resulting control logic can be complex. Now the popular web MVC framework (such as STRUTS2) supports the " request parameter Submitflag=toadd, you can directly invoke the Toadd method " Such a processing mechanism, in Struts2 similar to such a processing mechanism is called "dynamic method call"

  2, the request parameter to the model package is troublesome , if can give the framework to do this thing, we can get liberated from it.

Package code that requests parameters to the model:

1//1 Collect parameters 2 string username = Req.getparameter ("username"); 3 String password = req.getparameter ("password"); 4//2 package parameter 5 Us Erbean user = new UserBean (), 6 user.setusername (username), 7 user.setpassword (password);

When there are dozens of or even hundreds of parameters that need to be encapsulated in the model, it would be painful to write dozens of times or even hundreds of such code, it is estimated to write to vomit, so now the popular web MVC framework (such as STRUTS2) provides a very convenient way to get parameters, encapsulation parameters to the model mechanism, To reduce these tedious tasks.

  3. Select the next view, heavily dependent on the servlet API, which makes it difficult or impossible to replace the view.

Example: Use the Getrequestdispatcher method of the request object provided by the Servlet API to select the view to show to the user

1  private void Tologin (HttpServletRequest req, HttpServletResponse resp) 2             throws Servletexception, IOException {3     //The Getrequestdispatcher method of the request object provided with the Servlet API select View 4      //Here and JSP view technology tightly coupled, replacing other view technology is almost impossible 5     request.getrequestdispatcher ("/mvc/login.jsp"). Forward (request, response); 6}

  4, to the view transmission to show the model data, also need to use the servlet API, the replacement of the view technology should be replaced together, very troublesome.

Example: Use the Request object provided by the Servlet API to transmit model data to the view for presentation

Use the Request object provided by the Servlet API to transmit the model data (user) Request.setattribute ("user", user) to the view login.jsp for presentation; Request.getrequestdispatcher ("/mvc/login.jsp"). Forward (request, response)
3.2, JavaBean as a model of the shortcomings

Here the model uses JavaBean, theJavaBean component class is responsible for collecting the encapsulated data, but also the business logic processing, which may cause the JavaBean component class is very large , so the general project is now using three-tier architecture, Rather than using JavaBean directly.

3.3. Disadvantages of view

It's hard to change views, like velocity, freemarker, for example, I want to support Excel, PDF view, and so on.

About the two development modes of Javaweb introduced here, the next one will use Servlet+jsp+javabean to develop a user login registration function, in order to deepen the understanding of Servlet+jsp+javabean development model.

Javaweb Learning Summary (21) Two development modes of--javaweb

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.