Solved

MVC application model

Posted on 2013-01-30
4
476 Views
Last Modified: 2013-02-10
I created below simple MVC application.



view-Login.jsp



<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>Login page</title>
   
      <meta http-equiv="pragma" content="no-cache">
      <meta http-equiv="cache-control" content="no-cache">
      <meta http-equiv="expires" content="0">    
      <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
      <meta http-equiv="description" content="This is my page">
      <!--
      <link rel="stylesheet" type="text/css" href="styles.css">
      -->

  </head>
 
  <body>

 <form method="post" action="loginservletpath">
 <br>User Id:<input type="text" name="userId">
 <br>Password:<input type="password" name="password"/>
<br> <input type="submit">
 </form>
  </body>
</html>


success.jsp -view


<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1" import="org.gp.gpr.dto.User"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'success.jsp' starting page</title>
   
      <meta http-equiv="pragma" content="no-cache">
      <meta http-equiv="cache-control" content="no-cache">
      <meta http-equiv="expires" content="0">    
      <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
      <meta http-equiv="description" content="This is my page">
      <!--
      <link rel="stylesheet" type="text/css" href="styles.css">
      -->

  </head>
 
  <body>
<h3>login success</h3>
<%
User user=(User)session.getAttribute("user");

 %>
 hello <%=user.getUserName() %>
  </body>
</html>





LoginServlet.java-controller

package org.gp.gpr;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gp.gpr.dto.User;
import org.gp.gpr.service.LoginService;

public class LoginServlet extends HttpServlet {

      /**
       * Constructor of the object.
       */
      public LoginServlet() {
            super();
      }

      /**
       * Destruction of the servlet. <br>
       */
      public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
      }


      /**
       * The doPost method of the servlet. <br>
       *
       * This method is called when a form has its tag value method equals to post.
       *
       * @param request the request send by the client to the server
       * @param response the response send by the server to the client
       * @throws ServletException if an error occurred
       * @throws IOException if an error occurred
       */
      public void doPost(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
            String userId,password;

            userId=request.getParameter("userId");
            password=request.getParameter("password");
            
            LoginService loginService=new LoginService();
            boolean result=loginService.authenticate(userId,password);
            if(result){
                  User user= loginService.getUserDetails(userId);
                  request.getSession().setAttribute("user", user);
                  System.out.println("inside login servlet");
                  response.sendRedirect("success.jsp");
                  return;
                  
            }
            
            else{
                  System.out.println("inside login servlet else");
                  response.sendRedirect("Login.jsp");
                  return;
                  
            }
      }

      /**
       * Initialization of the servlet. <br>
       *
       * @throws ServletException if an error occurs
       */
      public void init() throws ServletException {
            // Put your code here
      }

}


LoginService-Business Service

package org.gp.gpr.service;

import java.util.HashMap;

import org.gp.gpr.dto.User;

public class LoginService {
      
      
      HashMap<String, String> users=new HashMap<String, String>();
      
      public LoginService(){
            
            users.put("mk", "mike");
            users.put("ek", "erik");
            users.put("pl", "paul");
      }
      public boolean authenticate(String userId, String password){
            
            
            if(password == null||password.trim() ==""){
                  return false;
            }
            return true;
      }
      
      public User getUserDetails(String userID){
            User user=new User();
            user.setUserName(users.get(userID));
            user.setUserId(userID);
            return user;
            
      }

}




web.xml - Deployment Descriptor



<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
      xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>org.gp.gpr.LoginServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/loginservletpath</url-pattern>
  </servlet-mapping>      
 
   <servlet>
    <servlet-name>xmlServlet</servlet-name>
    <servlet-class>com.gp.java.XmlServlet</servlet-class>
    <init-param>
      <param-name>default value</param-name>
      <param-value>sai</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>xmlServlet</servlet-name>
    <url-pattern>/xmlServletPath</url-pattern>
  </servlet-mapping>
 
 
  <welcome-file-list>
    <welcome-file>Login.jsp</welcome-file>
  </welcome-file-list>
</web-app>



DTO class

package org.gp.gpr.dto;

public class User {
      private String userName;
      private String userId;
      public String getUserName() {
            return userName;
      }
      public void setUserName(String userName) {
            this.userName = userName;
      }
      public String getUserId() {
            return userId;
      }
      public void setUserId(String userId) {
            this.userId = userId;
      }

}




I could not understand where is the model object. How it come into effect. How the application interact with model.  Please advise. Any ideas, sample code, resources highly appreciated. Thanks in advance.
0
Comment
Question by:gudii9
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 7

Author Comment

by:gudii9
ID: 38837696
I re factored the code further to use requestdipatcher to maintain same request and also to make change in the server side without url showing success.jsp.

[
success.jsp code

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1" import="org.gp.gpr.dto.User"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'success.jsp' starting page</title>
   
      <meta http-equiv="pragma" content="no-cache">
      <meta http-equiv="cache-control" content="no-cache">
      <meta http-equiv="expires" content="0">    
      <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
      <meta http-equiv="description" content="This is my page">
      <!--
      <link rel="stylesheet" type="text/css" href="styles.css">
      -->

  </head>
 
  <body>
<h3>login success</h3>
<%
User user=(User)request.getAttribute("user");

 %>
 hello <%=user.getUserName() %>
  </body>
</html>



LoginServlet code

package org.gp.gpr;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gp.gpr.dto.User;
import org.gp.gpr.service.LoginService;

public class LoginServlet extends HttpServlet {

      /**
       * Constructor of the object.
       */
      public LoginServlet() {
            super();
      }

      /**
       * Destruction of the servlet. <br>
       */
      public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
      }


      /**
       * The doPost method of the servlet. <br>
       *
       * This method is called when a form has its tag value method equals to post.
       *
       * @param request the request send by the client to the server
       * @param response the response send by the server to the client
       * @throws ServletException if an error occurred
       * @throws IOException if an error occurred
       */
      public void doPost(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
            String userId,password;

            userId=request.getParameter("userId");
            password=request.getParameter("password");
            
            LoginService loginService=new LoginService();
            boolean result=loginService.authenticate(userId,password);
            if(result){
                  User user= loginService.getUserDetails(userId);
                  request.setAttribute("user", user);
                  RequestDispatcher dispatcher=request.getRequestDispatcher("success.jsp");
                  dispatcher.forward(request, response);
                  System.out.println("inside login servlet");
                  //response.sendRedirect("success.jsp");
                  return;
                  
            }
            
            else{
                  System.out.println("inside login servlet else");
                  response.sendRedirect("Login.jsp");
                  return;
                  
            }
      }

      /**
       * Initialization of the servlet. <br>
       *
       * @throws ServletException if an error occurs
       */
      public void init() throws ServletException {
            // Put your code here
      }

}





still model part is not clear to me. please advise
str.jpg
0
 
LVL 20

Expert Comment

by:Sathish David Kumar N
ID: 38838586
>>>>>> public User getUserDetails(String userID){
            User user=new User();
            user.setUserName(users.get(userID));
            user.setUserId(userID);
            return user;
           
      }



this is the part ur model is used .

Model is nothing but your bean class that is used to join ur back end(controller) and front end (jsp)
0
 
LVL 7

Author Comment

by:gudii9
ID: 38855955
does controller comes under backend. please advise
0
 
LVL 20

Accepted Solution

by:
Sathish David  Kumar N earned 500 total points
ID: 38858376
for flow purpose i mention back end (sorry its give you wrong meaning ) .

Front end  is Jsp (View)

your java code is (controller)

your Bean class are (Model)

Model is used for getting values from ur Jsp / controller  to give controller /jsp .

I think its clear now
0

Featured Post

The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

724 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question