Saturday, 3 February 2018

MVC in Servelts & JSP

MVC



1.    Controller
       - LoginServlet
2.   Business service
       - Authentication service

3.  Model

     - Authentication result

4.  View
      - Greeting Page
      - Login page



------------------------------------------------


1st Login page


2nd create servlet to capture the user name and password


3rd Business service - for authentication create simple java class


4th  call business service in servlet

5th now redirect to login.jsp or success.jsp based on result

6th  we need to redirect by telling the browser to redirect to  success.jsp
       we need to send to instruction to browser

7th get user details in LoginService and LoginServlet

8th Access the user details in success.jsp

------------------------------------



dto  data transfer object

we used the word model before
it is same as model

dto.User is used to transfer the data bw the layers .... LoginServlet , LoginService, success.jsp

to transfer datat b/w .   Servlet, business service , jsp




------------------------------------




login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>

<form action="login" method="post" >
UserName: <input type="text" name="userId"> <br>
Password: <input type="password" name="password"/> <br>
<input type="submit"/>

</form>


</body>

</html>


------------------------------------
LoginServlet.java

package org.srini.java;

import java.io.IOException;
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.srini.java.service.LoginService;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected 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) {
response.sendRedirect("success.jsp");
return;
}
else {
response.sendRedirect("login.jsp");
return;
}
 
 
}

}


------------------------------------
LoginService.java

package org.srini.java.service;

public class LoginService {

public boolean authenticate(String userId, String password) {
if(password==null || password.trim()=="") {
return false;
}
    return true;
}
}


------------------------------------
success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Success</title>
</head>
<body>
<h3> Login successful...!!</h3>

</body>
</html>


------------------------------------
http://localhost:8080/LoginApp/login.jsp

------------------------------------
------------------------------------
------------------------------------
------------------------------------

login.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>

<form action="login" method="post" >
UserName: <input type="text" name="userId"> <br>
Password: <input type="password" name="password"/> <br>
<input type="submit"/>

</form>


</body>

</html>

------------------------------------
LoginServlet.java

package org.srini.java;

import java.io.IOException;
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.srini.java.dto.User;
import org.srini.java.service.LoginService;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected 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);
response.sendRedirect("success.jsp");
return;
}
else {
response.sendRedirect("login.jsp");
return;
}
 
 
}


}


------------------------------------
LoginService.java

package org.srini.java.service;

import java.util.HashMap;

import org.srini.java.dto.User;

public class LoginService {

HashMap<String,String> users =new HashMap<String,String>();
public LoginService() {
users.put("user1", "abc");
users.put("user2", "pqr");
users.put("user3", "xyz");
}
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;
}

}

------------------------------------
User.java


package org.srini.java.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;
}

}

------------------------------------
Success.jsp



<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="org.srini.java.dto.User"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Success</title>
</head>
<body>
<h3> Login successful...!!</h3>

<%
User user =(User)session.getAttribute("user");

%>

Hello , <%=user.getUserName() %> !
</body>

</html>


------------------------------------

request.dispatcher()

Dispatcher is used to transfer the control to success.jsp...path that mentioned

2nd way passing control from servlet to jsp




------------------------------------
LoginServlet.java

package org.srini.java;

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.srini.java.dto.User;
import org.srini.java.service.LoginService;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected 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);
//response.sendRedirect("success.jsp");
  request.setAttribute("user",user);
 
RequestDispatcher dispatcher=request.getRequestDispatcher("success.jsp");
dispatcher.forward(request, response);
return;
}
else {
response.sendRedirect("login.jsp");
return;
}
 
 
}


}


------------------------------------
success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="org.srini.java.dto.User"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Success</title>
</head>
<body>
<h3> Login successful...!!</h3>

<%
//User user =(User)session.getAttribute("user");
   User user = (User)request.getAttribute("user");
%>

Hello , <%=user.getUserName() %> !
</body>

</html>
------------------------------------
------------------------------------
------------------------------------
------------------------------------
------------------------------------

JSTL and Bean tag



we started writing jsp because it was pain to write all html code inside servlet

put each html code inside println method

thats why we started writing jsps


we can have html page and java code in between

it works for simple html and simple jsps


if code increases its hard to maintain

inside jsp is not pure xml

all the code iside script blocks are not xml


in order to have proper xml format in order to maintain more maintainable


that's why JSTL


JSTL helps to write all the java code as XML

Advantage 

maintainance


If we take jsp ..lot of view logic involved there

probably

stylesheets
view control
alignment data


it has data about how to present page to user




JSTL --  jsp standard tag library


need to tell where to pull the id from class and what is it's scope



<jsp:



------------------------------------

<jsp:useBean id="user" class="org.srini.java.dto.User" scope="request"></jsp:useBean>

==
 User user = (User)request.getAttribute("user");


------------------------------------

success.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="org.srini.java.dto.User"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Success</title>
</head>
<body>
<h3> Login successful...!!</h3>

<!--  
<%
//User user =(User)session.getAttribute("user");
  // User user = (User)request.getAttribute("user");
%>
-->


<jsp:useBean id="user" class="org.srini.java.dto.User" scope="request"></jsp:useBean>


Hello , <%=user.getUserName() %> !
</body>

</html>


------------------------------------


Hello , <%=user.getUserName() %> !


Hello, <jsp:getProperty property="userName" name="user"/>




------------------------------------

success.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="org.srini.java.dto.User"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Success</title>
</head>
<body>
<h3> Login successful...!!</h3>

<!--  
<%
//User user =(User)session.getAttribute("user");
  // User user = (User)request.getAttribute("user");
%>
-->


<jsp:useBean id="user" class="org.srini.java.dto.User" scope="request">

<jsp:setProperty property="userName" name="user" value="NewUser"/>
</jsp:useBean>


Hello , <%=user.getUserName() %> !

Hello, <jsp:getProperty property="userName" name="user"/>
</body>

</html>



------------------------------------



Request Parameters with the setProperty tag




------------------------------------

------------------------------------


No comments:

Post a Comment