Struts (1) -- jsp + Servlet explains the basic principles of the MVC Framework

Source: Internet
Author: User

Since I first came into contact with java, I often see some experts on the Forum talking about the framework cloud. Every one of them feels that what they know about the framework is really great. Envy, envy, and hate cannot be used as food. We also follow the giant's pace to start the study framework journey. Struts is the simplest and most classic of all frameworks. Starting with struts, it is a step-by-step shortcut.

 


This article serves as a preparation article. Let's start with the destruction of the origin-the basic principles of MVC.


The functional collaboration process between the three parts of the MVC framework is clear, but here you can briefly mention:

Select the corresponding view of the data and return the view to the user.

 


 


1. the end user sends a request to the Controller.

2. After the Controller accepts the request, it checks the request and determines what business logic is used to process the request. In this case, the Controller forwards the request to a corresponding business logic for processing;

3. The model contains all the business components that process the user's request, and also executes all the data access required by the user, any data retrieved by end users is packaged and returned to the Controller.

4. The controller accepts the data returned from the model and selects
Below, we will first use an inflexible Servlet for implementation:


[Java]
Package com. xxjstgb. servlet;
Import java. io. IOException;
Import java. util. List;
Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Public class TestServlet extends HttpServlet {
@ Override
Protected void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
String requestURI = request. getRequestURI ();
Int start = requestURI. indexOf ("/", 1 );
Int end = requestURI. indexOf (".");
String path = requestURI. substring (start, end );
System. out. println ("path =" + path );
String username = request. getParameter ("username ");
UserManager userManager = new UserManager ();
String forward = "";
If ("/servlet/delUser". equals (path )){
UserManager. del (username );
Forward = "/del_success.jsp ";
} Else if ("/servlet/addUser". equals (path )){
UserManager. add (username );
Forward = "/add_success.jsp ";
} Else if ("/servlet/modifyUser". equals (path )){
UserManager. modify (username );
Forward = "/modify_success.jsp ";
} Else if ("/servlet/queryUser". equals (path )){
List userList = userManager. query (username );
Request. setAttribute ("userList", userList );
Forward = "/query_success.jsp ";
} Else {
Throw new RuntimeException ("request failed ");
}
Request. getRequestDispatcher (forward). forward (request, response );
}
}

Package com. xxjstgb. servlet;
Import java. io. IOException;
Import java. util. List;
Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Public class TestServlet extends HttpServlet {
@ Override
Protected void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
String requestURI = request. getRequestURI ();
Int start = requestURI. indexOf ("/", 1 );
Int end = requestURI. indexOf (".");
String path = requestURI. substring (start, end );
System. out. println ("path =" + path );
String username = request. getParameter ("username ");
UserManager userManager = new UserManager ();
String forward = "";
If ("/servlet/delUser". equals (path )){
UserManager. del (username );
Forward = "/del_success.jsp ";
} Else if ("/servlet/addUser". equals (path )){
UserManager. add (username );
Forward = "/add_success.jsp ";
} Else if ("/servlet/modifyUser". equals (path )){
UserManager. modify (username );
Forward = "/modify_success.jsp ";
} Else if ("/servlet/queryUser". equals (path )){
List userList = userManager. query (username );
Request. setAttribute ("userList", userList );
Forward = "/query_success.jsp ";
} Else {
Throw new RuntimeException ("request failed ");
}
Request. getRequestDispatcher (forward). forward (request, response );
}
}

Configuration file:


[Html]
<? Xml version = "1.0" encoding = "UTF-8"?>
<Web-app version = "2.4"
Xmlns = "http://java.sun.com/xml/ns/j2ee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://java.sun.com/xml/ns/j2ee
Http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>

<Servlet>
<Servlet-name> TestServlet </servlet-name>
<Servlet-class> com. xxjstgb. servlet. testServlet </servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-name> TestServlet </servlet-name>
<Url-pattern> *. do </url-pattern>
</Servlet-mapping>
</Web-app>

<? Xml version = "1.0" encoding = "UTF-8"?>
<Web-app version = "2.4"
Xmlns = "http://java.sun.com/xml/ns/j2ee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://java.sun.com/xml/ns/j2ee
Http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
 
<Servlet>
<Servlet-name> TestServlet </servlet-name>
<Servlet-class> com. xxjstgb. servlet. testServlet </servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-name> TestServlet </servlet-name>
<Url-pattern> *. do </url-pattern>
</Servlet-mapping>
</Web-app>

 


When a user sends a request (for example, the request is http: // localhost: 8080/struts_dispatchaction/servlet/delUser. do), according to the user request URL with certain characteristics (this URL starts with/servlet/or *. end with do) to access the corresponding Servlet.

According to the configuration file, all requests configured with the end of ". do" can access TestServlet. The Servlet intercepts the special part of each request "/servlet/delUser". Based on this string, it calls the corresponding business logic and performs the corresponding redirection.

 


However, this implementation method may seem inappropriate at a Glance. The Servlet task is too heavy. The model layer logic is called here, and all page turns are also performed. In addition, it contains a large number of if... Else statements, due to service instability, it is a very bad design to add or delete else statements.

 


In the following improved design, We refined the controller into the frontend controller TestServlet and the Business controller Action.

 

 
 

 

The front-end controller has two tasks: 1. Extract the url according to certain rules; 2. Distribute the request to the corresponding Action according to the url.

Business Controller: 1. Accept form data; 2. Call business logic; 3. Return the redirection information.

Action:


[Java]
Package com. xxjstgb. servlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Public interface Action {
Public String execute (HttpServletRequest request, HttpServletResponse response)
Throws Exception;
}

Package com. xxjstgb. servlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Public interface Action {
Public String execute (HttpServletRequest request, HttpServletResponse response)
Throws Exception;
}
DelUserActiion:


[Java]
Package com. xxjstgb. servlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Public class DelUserAction implements Action {
Public String execute (HttpServletRequest request,
HttpServletResponse response) throws Exception {
// Receive form parameters
String username = request. getParameter ("username ");
// Call the business logic
UserManager userManager = new UserManager ();
Try {
UserManager. del (username );
} Catch (Exception e ){
Return "del_error.jsp"; // The redirection path can be read through the configuration file.
}
// Turn information
Return "/del_success.jsp"; // The redirection path can be read through the configuration file.
}
}

Package com. xxjstgb. servlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Public class DelUserAction implements Action {
Public String execute (HttpServletRequest request,
HttpServletResponse response) throws Exception {
// Receive form parameters
String username = request. getParameter ("username ");
// Call the business logic
UserManager userManager = new UserManager ();
Try {
UserManager. del (username );
} Catch (Exception e ){
Return "del_error.jsp"; // The redirection path can be read through the configuration file.
}
// Turn information
Return "/del_success.jsp"; // The redirection path can be read through the configuration file.
}
}

 

TestServlet after improved design:

 

[Java]
Package com. xxjstgb. servlet;
Import java. io. IOException;
Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Public class TestServlet extends HttpServlet {
@ Override
Protected void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
String requestURI = request. getRequestURI ();
Int start = requestURI. indexOf ("/", 1 );
Int end = requestURI. indexOf (".");
String path = requestURI. substring (start, end );
Action action = null;
If ("/servlet/delUser". equals (path )){
Action = new DelUserAction ();
} Else if ("/servlet/addUser". equals (path )){
Action = new AddUserAction ();
} Else if ("/servlet/modifyUser". equals (path )){
Action = new ModifyUserAction ();
} Else if ("/servlet/queryUser". equals (path )){
Action = new QueryUserAction ();
} Else {
Throw new RuntimeException ("request failed ");
}
String forward = null;
Try {
Forward = action.exe cute (request, response );
} Catch (Exception e ){
E. printStackTrace ();
}
Request. getRequestDispatcher (forward). forward (request, response );
}
}

Package com. xxjstgb. servlet;
Import java. io. IOException;
Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Public class TestServlet extends HttpServlet {
@ Override
Protected void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
String requestURI = request. getRequestURI ();
Int start = requestURI. indexOf ("/", 1 );
Int end = requestURI. indexOf (".");
String path = requestURI. substring (start, end );
Action action = null;
If ("/servlet/delUser". equals (path )){
Action = new DelUserAction ();
} Else if ("/servlet/addUser". equals (path )){
Action = new AddUserAction ();
} Else if ("/servlet/modifyUser". equals (path )){
Action = new ModifyUserAction ();
} Else if ("/servlet/queryUser". equals (path )){
Action = new QueryUserAction ();
} Else {
Throw new RuntimeException ("request failed ");
}
String forward = null;
Try {
Forward = action.exe cute (request, response );
} Catch (Exception e ){
E. printStackTrace ();
}
Request. getRequestDispatcher (forward). forward (request, response );
}
}

 

In this Servlet, the call and page redirection of the model layer have been separated into the Action. In a specific Action, the model layer logic and page redirection are called. This is the simple Implementation of the Basic MVC framework.

 

Related Article

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.