- Архитектура MVC в Java
- Что такое архитектура MVC в Java?
- Преимущества архитектуры
- Реализация
- Слой модели
- Уровень представления
- Уровень контроллера
- Класс Main
- Вывод
- Mvc layers in java
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- MVC Architecture in Java with JSP Application Design Example
- Model Layer
- View Layer
- Controller Layer
- Advantages of MVC Architecture
- Example of JSP Application Design with MVC Architecture
- Summary
Архитектура MVC в Java
В области веб-разработки Model-View-Controller является одним из самых обсуждаемых шаблонов проектирования в современном мире веб-программирования. Архитектура MVC изначально была включена в две основные среды веб-разработки – Struts и Ruby on Rails.
- Шаблон проектирования в разработке программного обеспечения – это метод решения часто возникающей проблемы при разработке программного обеспечения.
- Проектирование модели, указывает, какой тип архитектуры вы используете для решения проблемы или разработки модели.
- Существует два типа моделей проектирования: архитектура модели 1, архитектура модели 2 (MVC).
Что такое архитектура MVC в Java?
Проекты моделей, основанные на архитектуре MVC в Java, следуют шаблону проектирования MVC и отделяют логику приложения от пользовательского интерфейса при разработке программного обеспечения. Как следует из названия, шаблон MVC имеет три слоя:
- Модель – представляет бизнес-уровень приложения.
- Просмотр – определяет представление приложения.
- Контроллер – управляет потоком приложения.
В контексте программирования Java модель состоит из простых классов , представление отображает данные, а контроллер состоит из сервлетов. Это разделение приводит к тому, что пользовательские запросы обрабатываются следующим образом:
- Браузер на клиенте отправляет запрос страницы контроллеру, присутствующему на сервере.
- Контроллер выполняет действие по вызову модели, тем самым извлекая необходимые данные в ответ на запрос.
- Затем контроллер передает полученные данные в представление.
- Представление отображается и отправляется обратно клиенту для отображения в браузере.
Разделение программного приложения на эти три отдельных компонента является хорошей идеей по ряду причин.
Преимущества архитектуры
Архитектура MVC предлагает множество преимуществ для программиста при разработке приложений, которые включают в себя:
- Несколько разработчиков могут работать с тремя слоями (Модель, Вид и Контроллер) одновременно.
- Обеспечивает улучшенную масштабируемость, которая дополняет способность приложения расти.
- Поскольку компоненты имеют низкую зависимость друг от друга, их легко поддерживать.
- Модель может быть повторно использована несколькими представлениями, что обеспечивает возможность повторного использования кода.
- Принятие MVC делает приложение более выразительным и простым для понимания.
- Расширение и тестирование приложения становится легким.
Реализация
Для реализации веб-приложения на основе шаблона проектирования MVC мы создадим:
- Course Class, который выступает в качестве модельного слоя.
- CourseView Class, который определяет уровень представления (уровень представления).
- CourseContoller Class, который действует как контроллер.
Теперь давайте рассмотрим эти слои один за другим.
Слой модели
В шаблоне проектирования MVC модель представляет собой уровень данных, который определяет бизнес-логику системы, а также представляет состояние приложения. Объекты модели получают и сохраняют состояние модели в базе данных. На этом уровне мы применяем правила к данным, которые в конечном итоге представляют концепции, которыми управляет наше приложение. Теперь давайте создадим модель, используя Course Class.
package MyPackage; public class Course < private String CourseName; private String CourseId; private String CourseCategory; public String getId() < return CourseId; >public void setId(String id) < this.CourseId = id; >public String getName() < return CourseName; >public void setName(String name) < this.CourseName = name; >public String getCategory() < return CourseCategory; >public void setCategory(String category) < this.CourseCategory = category; >>
Код прост для понимания и не требует пояснений. Он состоит из функций, чтобы получить/установить детали Course.
Уровень представления
Этот уровень шаблона проектирования MVC представляет выходные данные приложения или пользовательского интерфейса. Он отображает данные, извлеченные из слоя модели контроллером, и представляет данные пользователю при каждом запросе. Он получает всю необходимую информацию от контроллера и ему не нужно напрямую взаимодействовать с бизнес-уровнем. Давайте создадим представление, используя ClassView Class.
package MyPackage; public class CourseView < public void printCourseDetails(String CourseName, String CourseId, String CourseCategory)< System.out.println("Course Details: "); System.out.println("Name: " + CourseName); System.out.println("Course ID: " + CourseId); System.out.println("Course Category: " + CourseCategory); >>
Этот код просто для печати значений на консоль. Далее у нас есть контроллер веб-приложения.
Уровень контроллера
Контроллер похож на интерфейс между моделью и представлением. Он получает пользовательские запросы от уровня представления и обрабатывает их, включая необходимые проверки. Затем запросы отправляются в модель для обработки данных. После обработки данные снова отправляются обратно в контроллер, а затем отображаются в представлении. Давайте создадим ClassContoller Class, который действует как контроллер.
package MyPackage; public class CourseController < private Course model; private CourseView view; public CourseController(Course model, CourseView view)< this.model = model; this.view = view; >public void setCourseName(String name) < model.setName(name); >public String getCourseName() < return model.getName(); >public void setCourseId(String id) < model.setId(id); >public String getCourseId() < return model.getId(); >public void setCourseCategory(String category) < model.setCategory(category); >public String getCourseCategory() < return model.getCategory(); >public void updateView() < view.printCourseDetails(model.getName(), model.getId(), model.getCategory()); >>
Беглый взгляд на код скажет нам, что этот класс контроллера просто отвечает за вызов модели для получения/установки данных и обновления представления на основе этого.
Класс Main
Давайте назовем этот класс «MVCPatternDemo.java». Проверьте код ниже.
package MyPackage; public class MVCPatternDemo < public static void main(String[] args) < //fetch student record based on his roll no from the database Course model = retriveCourseFromDatabase(); //Create a view : to write course details on console CourseView view = new CourseView(); CourseController controller = new CourseController(model, view); controller.updateView(); //update model data controller.setCourseName("Python"); System.out.println("nAfter updating, Course Details are as follows"); controller.updateView(); >private static Course retriveCourseFromDatabase() < Course course = new Course(); course.setName("Java"); course.setId("01"); course.setCategory("Programming"); return course; >>
Приведенный выше класс извлекает данные Course из функции, используя которую пользователь вводит набор значений. Затем он помещает эти значения в модель Course. Затем он инициализирует представление, которое мы создали ранее в статье. Кроме того, он также вызывает класс CourseController и связывает его с классом Course и классом CourseView. Затем метод updateView(), являющийся частью контроллера, обновляет сведения о курсе на консоли. Проверьте вывод ниже.
Вывод
Course Details: Name: Java Course ID: 01 Course Category: Programming After updating, Course Details are as follows Course Details: Name: Python Course ID: 01 Course Category: Programming
Архитектура MVC обеспечивает совершенно новый уровень модульности вашего кода, что делает его более удобным для чтения и сопровождения. Это подводит нас к концу этой статьи. Надеюсь, вам понятно все, что с вами поделились.
Mvc layers in java
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
MVC Architecture in Java with JSP Application Design Example
MVC is a systematic way to use the application where the flow starts from the view layer, where the request is raised and processed in controller layer and sent to model layer to insert data and get back the success or failure message. The MVC Architecture diagram is represented below:
Model Layer
- This is the data layer which consists of the business logic of the system.
- It consists of all the data of the application
- It also represents the state of the application.
- It consists of classes which have the connection to the database.
- The controller connects with model and fetches the data and sends to the view layer.
- The model connects with the database as well and stores the data into a database which is connected to it.
View Layer
- This is a presentation layer.
- It consists of HTML, JSP, etc. into it.
- It normally presents the UI of the application.
- It is used to display the data which is fetched from the controller which in turn fetching data from model layer classes.
- This view layer shows the data on UI of the application.
Controller Layer
- It acts as an interface between View and Model.
- It intercepts all the requests which are coming from the view layer.
- It receives the requests from the view layer and processes the requests and does the necessary validation for the request.
- This requests is further sent to model layer for data processing, and once the request is processed, it sends back to the controller with required information and displayed accordingly by the view.
Advantages of MVC Architecture
The advantages of MVC are:
- Easy to maintain
- Easy to extend
- Easy to test
- Navigation control is centralized
Example of JSP Application Design with MVC Architecture
In this example, we are going to show how to use MVC architecture in JSP.
- We are taking the example of a form with two variables “email” and “password” which is our view layer.
- Once the user enters email, and password and clicks on submit then the action is passed in mvc_servlet where email and password are passed.
- This mvc_servlet is controller layer. Here in mvc_servlet the request is sent to the bean object which act as model layer.
- The email and password values are set into the bean and stored for further purpose.
- From the bean, the value is fetched and shown in the view layer.
Mvc_example.jsp
Explanation of the code:
Code Line 10-15: Here we are taking a form which has two fields as parameter “email” and “password” and this request need to be forwarded to a controller Mvc_servlet.java, which is passed in action.The method through which it is passed is POST method.
Mvc_servlet.java
package demotest; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Mvc_servlet */ public class Mvc_servlet extends HttpServlet < private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Mvc_servlet() < super(); // TODO Auto-generated constructor stub >protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < // TODO Auto-generated method stub String email=request.getParameter("email"); String password=request.getParameter("password"); TestBean testobj = new TestBean(); testobj.setEmail(email); testobj.setPassword(password); request.setAttribute("gurubean",testobj); RequestDispatcher rd=request.getRequestDispatcher("mvc_success.jsp"); rd.forward(request, response); >>
Explanation of the code:
Controller layer
Code Line 14:mvc_servlet is extending HttpServlet.
Code Line 26: As the method used is POST hence request comes into a doPost method of the servlet which process the requests and saves into the bean object as testobj.
Code Line 34: Using request object we are setting the attribute as gurubean which is assigned the value of testobj.
Code Line 35: Here we are using request dispatcher object to pass the success message to mvc_success.jsp
TestBean.java
package demotest; import java.io.Serializable; public class TestBean implements Serializable < public String getEmail() < return email; >public void setEmail(String email) < this.email = email; >public String getPassword() < return password; >public void setPassword(String password) < this.password = password; >private String email="null"; private String password="null"; >
Explanation of the code:
Model Layer:
Code Line 7-17: It contains the getters and setters of email and password which are members of Test Bean class
Code Line 19-20: It defines the members email and password of string type in the bean class.
Mvc_success.jsp
Explanation of the code:
Code Line 12: we are getting the attribute using request object which has been set in the doPost method of the servlet.
Code Line 13: We are printing the welcome message and email id of which have been saved in the bean object
When you execute the above code, you get the following output:
When you click on mvc_example.jsp you get the form with email and password with the submit button.
Once you enter email and password to the form and then click on submit
After clicking on submit the output is shown as below
When you enter email and password in screen and click on submit then, the details are saved in TestBean and from the TestBean they are fetched on next screen to get the success message.
Summary
In this article, we have learnt about the MVC i.e. Model View Controller architecture.
JSP plays the role of presentation of the data and controller. It is an interface between model and view while model connects both to the controller as well as the database. Main business logic is present in the model layer.