Friday, 2 February 2018

Servlets & JSP


Creating  Dynamic Web project and deploying in tomcat


New > other > web > Dynamic web project >

Project Name : MyWebapplication

Next  src > next

Context Root : My webapplication
Content directory: Webcontent  -> here .jsp, html files need to place here

check mark -> Generate web.xml deployment descriptor(web.xml)



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



window > show view >  navigator


expand project >  webcontent > web-inf  > web.xml
click source view


Now goto

select webcontent  > new > other > web  > html file  > next  > index.html > finish



write inside body



<h3>Welcome to HTML <h3>


then save


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

select project > Run As  > Run on server > next  > finish



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



XmlServlet.java

package org.srini.java;

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;

public class XmlServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{

//System.out.println("xml servlet created");

     response.setContentType("text/html");
     PrintWriter out=response.getWriter();
     String userName= request.getParameter("userName");
     out.println("hello from GET method"+userName);
   

}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{

//System.out.println("xml servlet created");

     response.setContentType("text/html");
     PrintWriter out=response.getWriter();
     String userName= request.getParameter("userName");
     String fullName= request.getParameter("fullName");
     out.println("hello from POsT method "+userName +" your full name:  "+fullName);
     String prof=request.getParameter("prof");
     out.println("You are a "+prof);
     //String location=request.getParameter("location");
     String[] location=request.getParameterValues("location");
     out.println("\nyour location is 1: "+location[0]);
     out.println("\nyour location is 2: "+location[1]);
   

}

}


------------------------------------------------------------------------------------------------------------
web.xml



<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SimpleServletProject</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  
  
  <servlet>
   <servlet-name>xmlServlet</servlet-name>
   <servlet-class>org.srini.java.XmlServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>xmlServlet</servlet-name>
  <url-pattern>/XmlSerlvetPath</url-pattern>
  </servlet-mapping>

</web-app>


------------------------------------------------------------------------------------------------------------
http://localhost:8080/ServletTest/XmlSerlvetPath?userName=Srinivas

------------------------------------------------------------------------------------------------------------
index.html


<!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=ISO-8859-1">
<title>This is title</title>
</head>

<body>
 <h3>this is body</h3>
</body>

</html>

------------------------------------------------------------------------------------------------------------
simpleForm.html



<!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=ISO-8859-1">
<title>Testing Post</title>

</head>
<body>

   <form method="post" action="XmlSerlvetPath">
       User Name: <input name="userName"/>
       Full Name: <input name="fullName"/>
       <br>
       Profession: 
       <input type="radio" name="prof" value="srini Developer">Developer</input>
       <input type="radio" name="prof" value="srini Architect">Architect</input>
       <select name="location" multiple size=3>
           <option value="here">here</option>
           <option value="there">there</option>
           <option value="far">far</option>
           <option value="near">near</option>
       
       </select>
       
       <input type="submit"/>
   </form>

</body>

</html>c
http://localhost:8080/ServletTest/SimpleForm.html

------------------------------------------------------------------------------------------------------------
Test.jsp

package com.jsp.java;

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

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

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

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
String userName=request.getParameter("userName");
        out.println("Hello ,"+userName);


}
}


------------------------------------------------------------------------------------------------------------
clock.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.Date" %>
    
    <%@ include file="/hello.jsp"  %> <br>
<!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>clock</title>
</head>
<body>
The time is : <%=new Date() %>
</body>

</html>

------------------------------------------------------------------------------------------------------------
hello.jsp


Hello, Srini..!!!

------------------------------------------------------------------------------------------------------------
test.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>Title JSP</title>
</head>
<body>
 <h3>Testing JSP</h3>

 <%!
 public int add(int a,int b){
//System.out.println("result :"+ a+b);
return a+b;
 }

 %>

 <%
   int r=add(123,456);
   
 %>
 <br>
 The value of r is : <%=r %>

 <br>




 <%
  int i=1;
  int j=2;
  int k;
  k=i+j;
  add(i,j);
  
  //out.println(k);

 %>
 The value of k is :<%=k %>

</body>

</html>

------------------------------------------------------------------------------------------------------------
object.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>Insert title here</title>
</head>
<body>

<% 
String userName= request.getParameter("name");



if (userName !=null){
session.setAttribute("sessionUserName", userName);
application.setAttribute("applicationUserName", userName);
pageContext.setAttribute("pageContextUserName", userName);
}
//request
//session.getAttribute()
//application //context

%>
                                                <br>
The user name - request object is : <%=userName %>  <br>

The user name - session object is : <%= session.getAttribute("sessionUserName") %> <br>

The user name - application object is : <%=application.getAttribute("applicationUserName") %> <br>

The user name - page context object is : <%= pageContext.getAttribute("pageContextUserName") %>

</body>

</html>

------------------------------------------------------------------------------------------------------------
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>TestJSP</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

</web-app>

------------------------------------------------------------------------------------------------------------
object.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>Insert title here</title>
</head>
<body>

<% 
String userName= request.getParameter("name");



if (userName !=null){
//session.setAttribute("sessionUserName", userName);
pageContext.setAttribute("sessionUserName", userName, pageContext.SESSION_SCOPE);
//application.setAttribute("applicationUserName", userName);
pageContext.setAttribute("applicationUserName", userName, pageContext.APPLICATION_SCOPE);
pageContext.setAttribute("pageContextUserName", userName);
pageContext.findAttribute("name");
}
//request
//session.getAttribute()
//application //context

%>
                                                <br>
The user name - request object is : <%=userName %>  <br>

The user name - session object is : <%= session.getAttribute("sessionUserName") %> <br>

The user name - application object is : <%=application.getAttribute("applicationUserName") %> <br>

The user name - page context object is : <%= pageContext.getAttribute("pageContextUserName") %>

</body>

</html>

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

Init Parameters


initPage.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>Insert title here</title>
</head>
<body>

The default user from servlet config file is : 
<%=getServletConfig().getInitParameter("defaultUser") %>



</body>

</html>



------------------------------------------------------------------------------------------------------------
web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>TestJSP</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  
  
  <servlet>
 
  <servlet-name>InitJsp</servlet-name>
  <jsp-file>/initPage.jsp</jsp-file>
      
       <init-param>
        <param-name>defaultUser</param-name>
        <param-value>Srinivas</param-value>
       </init-param>
  
  
  </servlet>
  
  <servlet-mapping>
  <servlet-name>InitJsp</servlet-name>
  <url-pattern>/initPage.jsp</url-pattern>
  
  </servlet-mapping>
  
  

</web-app>


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

http://localhost:8080/TestJSP/initPage.jsp
------------------------------------------------------------------------------------------------------------
initPage.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>Insert title here</title>
</head>
<body>

<%!
 public void jspInit(){
String defaultUser= getServletConfig().getInitParameter("defaultUser");
ServletContext context= getServletContext();
 
context.setAttribute("defaultUser", defaultUser);
}

%>


The default user from servlet config file is : 
<%=getServletConfig().getInitParameter("defaultUser") %>
<br>

 The default value servlet context is  <%=getServletContext().getAttribute("defaultUser") %>
<br>

The value in the servlet context is : <% getServletContext().getAttribute("defaultUser"); %>





</body>

</html>
------------------------------------------------------------------------------------------------------------
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>TestJSP</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  
  
  <servlet>
 
  <servlet-name>InitJsp</servlet-name>
  <jsp-file>/initPage.jsp</jsp-file>
      
       <init-param>
        <param-name>defaultUser</param-name>
        <param-value>Srinivas</param-value>
       </init-param>
  
  
  </servlet>
  
  <servlet-mapping>
  <servlet-name>InitJsp</servlet-name>
  <url-pattern>/initPage.jsp</url-pattern>
  
  </servlet-mapping>
  
  

</web-app>

------------------------------------------------------------------------------------------------------------
servlet config vs servlet context

servlet config : That something tomcat passes to us  on the creation of servlet object

                       it checks the init parameters in the web.xml
                       whatever configuration parameters we set there
                       tomcat bundles them into object is called servlet config and passes to are init method
and it's available to us in the servlet as member variable as servlet config

servlet context -  another name is application context probably it's better name

scoped objects like  request , session

scoped object is applicable across the application

like request is applicable only for a request

session is only applicable for user session


servlet context object or application object is available across application



------------------------------------------------------------------------------------------------------------
MVC  pattern

How to implement mvc pattern in servlets and jsp

MVC is model view and controller

It's a front end design pattern that is used for designing web applications


ex: waiter cook presenter


when user make a request to a web application through url , the first person takes the request is

controller

controller is the wiring behind all, and knows where to pass the request, what to do with req
when to send back

analyses req and  passes on to service called business service


controller doesn't know the how to pull up all  the list of  users


it calls BusinessService.getAllUsers ,  then it passes back list of users to controller

Now controller passes to View

View is specialised in rendering the list of users in proper format

and makes it ready for consumption

Then it passes on to user


Model is actually the data

Req goes to controller and then converted to data which is actually the parameter of BusinessService.getAllusers method

then business service will execute and then pass it back to controller, to user and then to
View


Here the list of users is the model


Advantage

1. Each role is specific to what they have to do, there is complete seperation of concern
2. We can easily make changes



The way we implement :


Servlet is going to be controller

and passes the request to bean : (it implements business service method)

Now the servlet pass on the response to JSP ..here JSP is the presenter or view ,..jsp will format the data and shows the data in html format







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


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


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


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


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


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


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



No comments:

Post a Comment