Jump to content




Recent Status Updates

View All Updates

Developed by TechBiz Xccelerator
Photo
- - - - -

MVC Application in Java

java mvc jsp servlet

  • Please log in to reply
3 replies to this topic

#1 mdebnath

mdebnath

    CC Newcomer

  • Member
  • PipPip
  • 17 posts
  • Programming Language:C, Java, C++
  • Learning:C, Java, C++

Posted 01 October 2012 - 01:51 AM

MVC Application in Java

MVC stands for Model View and Controller. It basically defines how you structure your code, more precisely as you may know we structure any problem or bring an order to reduce its complexity and to control it. The need of following the pattern of MVC is pretty much the same. Suppose you are working on a projects in java, you have all the idea and amenities to complete the project but do not know how to start with or organize your code in java classes. In this scenario MVC pattern can pave the path. But how? Before answering this question lets demystify the notion of MVC.

An Analogy
The analogy is to get a picture of the scenario, however a one to one correspondence between them may not exists but nonetheless it will help you to get a first hand view of its working methodology.

pic1.jpg

Thus the Java objects responsible for displaying the output or getting the input into the system are in general part of the View. Controller acts as a manager between model and view and decides what goes where, when and how based on some business rules in the system. Model is manipulated through a set of business rules on which the system is built upon, for example if your software uses database, the rules based upon which data are fetched are called business rules.

Starting to code MVC
Now lets take upon an example: login web application to start Java code based upon the MVC pattern. We shall have a login page to collect the user name and password. Once the user submits the user name and password, we shall validate the credentials and if the credentials are found OK then we show the login successful page with greetings and if the credentials are not valid, we redirect back to the login page. This simple example shall give you an overview of an MVC application design.
The components according to MVC pattern will be as follows:
  • Controller (LoginServlet.java): In our case it will be a servlet. When the request for login is initiated, the user name and password is passed on to the controller who collects the data. The controller then passes the data on to the business service.
  • Business Service (LoginService.java): Our business service is a simple POJO (Plain Old Java Object) responsible for validating the user. In real world application the data model is fetched from a database. But in our case to reduce complexity and focus on the MVC pattern only, database part is omitted. Most of business critical code of an MVC application are in general are contained in business services.
  • Model (User.java): This is the data access object or the model class representing data on which the business rules apply and interact with.
  • View (login.jsp, login_success.jsp): This is basically a JSP/HTML files for streaming in/out request/response from the browser.
Steps for creating MVC app in Netbeans IDE

Step 1: Start Netbean IDE and click on File, New Project. Select Java Web from categories list and Web Application from projects list. Click Next

pic2.jpg

Step 2: Give the name of the project and leave the other options as it is, and then click Next.

pic3.jpg

Step 3: Select Server Apache Tomcat and click Finish

pic4.jpg

Step 4: Create the file structure as shown in the project explorer and write/copy paste the following code.

pic5.jpg

Controller: LoginServlet.java
package org.loginmvcapp.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.loginmvcapp.model.User;
import org.loginmvcapp.service.LoginService;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName=request.getParameter("userName");
String password=request.getParameter("password");

LoginService loginService=new LoginService();
if(loginService.isValidUser(userName, password)){
User user=loginService.getUser();
request.setAttribute("user", user);
RequestDispatcher requestDispatcher = request.getRequestDispatcher("login_success.jsp");
requestDispatcher.forward(request, response);
}else{
response.sendRedirect("index.jsp");
}
}
}

Business Service: LoginService
package org.loginmvcapp.service;
import org.loginmvcapp.model.User;

public class LoginService {

private User user;

public LoginService(){
user=new User();
user.setUserName("admin");
user.setPassword("admin");
}

public boolean isValidUser(String userName, String password){
if(userName.equals(user.getUserName()) && password.equals(user.getPassword())){
return true;
}
return false;
}

public User getUser(){
return user;
}
}



Model: User.java
package org.loginmvcapp.model;
public class User {
private String userName;
private String password;

public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View: index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<h1>Login</h1>
<form action="login" method="post">
<table>
<tr><td>User Name</td><td><input type="text" name="userName"/></td></tr>
<tr><td>Password</td><td><input type="password" name="password"/></td></tr>
<tr><td></td><td><input type="submit" value="Login"/></td></tr>
</table>
</form>
</body>
</html>

login_success.jsp
<%@page import="org.loginmvcapp.model.User"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Success</title>
</head>
<body>
<%
User user=(User)request.getAttribute("user");
%>
<h1>Hello <%=user.getUserName()%></h1>
<h2>You have successfully logged in</h2>

</body>
</html>

Step 5: To deploy the project press F6 or select Run Project from Run menu. The project shall run in a browser as shown below.

pic6.jpg

pic7.jpg

Conclusion
In a nutshell MVC is nothing but a blueprint of the code organization in a project to cope up with the complexity of large projects. This though is simplified rather oversimplified explanation but once you get your fist MVC application up and running you shall definitely get enthusiasm and confidence to delve deeper in to the realm of Java MVC.

Attached File  MVCApp.zip   197.24KB   527 downloads
  • 0

#2 VNFox

VNFox

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 648 posts
  • Programming Language:C#, PHP
  • Learning:Assembly

Posted 01 October 2012 - 08:49 AM

Good article ... it looks like something is missing in the article and got filled up with bunch of white spaces.
  • 0

www.pickmike.com
I don't just develop software. I find solutions to your business needs.


#3 mdebnath

mdebnath

    CC Newcomer

  • Member
  • PipPip
  • 17 posts
  • Programming Language:C, Java, C++
  • Learning:C, Java, C++

Posted 02 October 2012 - 04:44 AM

problem fixed
  • 0

#4 VNFox

VNFox

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 648 posts
  • Programming Language:C#, PHP
  • Learning:Assembly

Posted 02 October 2012 - 08:13 AM

I think you need to use the [img] tag for the images.
  • 0

www.pickmike.com
I don't just develop software. I find solutions to your business needs.






Powered by binpress