Solved

MVC application model

Posted on 2013-01-30
4
456 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
  • 2
  • 2
4 Comments
 
LVL 7

Author Comment

by:gudii9
Comment Utility
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
Comment Utility
>>>>>> 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
Comment Utility
does controller comes under backend. please advise
0
 
LVL 20

Accepted Solution

by:
Sathish David  Kumar N earned 500 total points
Comment Utility
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
strCopies  challenge 17 73
topping2 challenge 13 55
maven example error 3 34
Problem to start Neon 20 49
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

763 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now