WHAT'S NEW?
Date Conversions are one of the most important part of an app development. It is also a tricky task for the developer as well, as database needs a different format and client need to be shown the date in some different format.


So following method will help you convert your YYYY-MM-DD format to DD, MM(in words) year format


Lets make a class by name DateConvertor.java


class DateConvertor
{
public static String getFormatedDate(String date)
{
String dat[]=date.split("-");
String year=dat[0];
int m=Integer.parseInt(dat[1]);
String day=dat[2];


String month="";
switch (m) {
case 1:
month="January";
break;
case 2:
month="February";
break;

case 3:
month="March";
break;

case 4:
month="April";
break;

case 5:
month="May";
break;

case 6:
month="June";
break;

case 7:
month="July";
break;

case 8:
month="August";
break;

case 9:
month="September";
break;

case 10:
month="October";
break;

case 11:
month="November";
break;

case 12:
month="December";
break;

default:
break;
}

String fDate=day+", "+month+" "+year;
return fDate;
}
}



Now pass any date in YYYY-MM-DD format and get the formatted date just like that. If you want to learn more about Java click on this link

Now from any place just call the method and get the output

String dt="2018-02-26";
String fDate=DateConvertor.getFormatedDate(dt);


Have you ever tried to print an object using System.out.println() ? 

 Most probably you must have tried printing a String or an Integer value which prints its value.


For example, let say for the following code


String s="Tom";System.out.println(s);



It will print "Tom".


or


int i=10;System.out.println(i);


will print 10.



But what will it print in following scenario.

Let say there is a class Circle with a int variable of radius.


class Circle

{

int radius;

Circle(int radius)

{

this.radius=radius;

}

}



Now let say you make an object of class Circle and print it.


Circle c= new Circle(10);

System.out.println(c);



What should I expect to get printed now? Radius of the Circle or any other thing.
When you run this code, it will print the following.


Circle@15db9742



Why this? What is that number after @ sign and why that name of class.

When any object is printed under System.out.println(), it prints its response of toString().


toString() method



java.lang.Object- Alpha class or super class for all the class that exist in Java have a method with following signature.

public String toString()

By default java.lang.Object is designed to return the following

NameofClass@Hexcode(hashCode) 


Hence the output,

Circle@15db9742

Then why is it printing it differently for String and Integer?

Simple!! They have overridden the toString() method.

Let say I want the output of Circle object when printed as "Radius=radiusValue", I will have to override the toString() method.

class Circle

{
int radius;

Circle(int radius)

{

this.radius=radius;

}
public String toString()

{

String x="Radius="+radius;

return x;

}
}


Now when you print the object of class Circle, output will be different.



Circle c=new Circle(24);

System.out.pritnln(c);



Output: Radius=24


Java IO have lot of high level and low level of readers and writers.

Files can be read using both the input stream as well as output stream.




Let us try to read the content from a file using FileReader.

FileReader
- A low level Reader for reading the data from the file.


Constructor:


FileReader(File f)

- Open a reader on the specified object.

FileReader(String s)

- Open a reader on the specified path.



Methods


public int read()

- Reads the ascii value of the character till the EOF(End of File)  is reached.

Code to read the data from the file



import java.io.*;



public class ReadUsingFR

{

public static void main(String[] args)

{

try

{

File f=new File("xyz.txt"); // Replace xyz.txt with your file path.

FileReader fr=new FileReader(f);

int data=0;



while((data=fr,read())!=-1)

{

char c=(char)data;

System.out.print(c);

}

fr.close();

}

catch(Exception e)

{

e.printStackTrace();

}



}

}


IMPLICIT OBJECTS- JSP simplifier authoring & provides certain objects implicitly to be accessed within a JSP page without any explicit declaration.
- These objects are called as implicit objects .
- These objects are not declared explicitly but they are provided by Container during translation phase.
There are in all 9 implicit objects

TIP FOR STUDENT:It is always recommended to remember the name of this implicit object & their classes in context to interviews.....
There are 9 implicit objects:-
1) request.
2) response
3) out
4) session
5) application


6) config
7) page
8)pageContext
9)exception

1) request:-
- request object represents all the information about HttpRequest.
- Instance of :javax.servlet.http.HttpServletRequest
Scope:request scope.- Using this object we can access headers cookies ,etc.

2) response:-
- response object represents response to the client.
- Instance of : javax.servlet.http.HttpServletResponse.
Scope:page scope- response object is used for adding cookies, redirecting the calls,etc

3) out:-
- out object represents output stream.
- out objects are used for sending arguments to print methods.
- Instance of:javax.servlet.jsp.JSPWriter
-Scope:page scope
4) session:-
- session object is used to track client's information across the session.
- Instance of: javax.servlet.http.HttpSession
Scope:session scope.

5) application:-
- application object represent the context for the JSP page.
- application object is accessible to any object used within JSP page.
- Instance of:javax.servlet.ServletConfig
- Scope:page scope.

6) config:-
- config object provides access to the initialization parameters
- Instance of : javax.servlet.ServletConfig
- Scope : page scope

7) page:-
- page refers to the instance of JSP implementation class, i.e the JSP itself.
- accessed using 'this' reference.
- Instance of : javax.lang.Object
- Scope:page scope.

8) pageContext:-
- pageContext encapsulates other implicit objects.
- If a class is given pageContext reference it get access to all the objects from all the scope
- Instance of : javax.servlet.jsp.PageContext
- Scope:page scope.
9) exception:-
- Refers to runtime exception that resulted in invoking the errorPage.
- Available only in error page.
- errorPage:- a JSP which has is errorPage attribute true in page directive.
- Instance of :java.lang.Throwable
- Scope:page scope.

 Scriplets

-Any piece of code written in scriplet goes into service() method.
-Any complex or simple java code can be written in srciplet.
-Scriplet are meant for embedding java code.


-Scriplet never get translated.
-Hence a very simple but logical point to remember for scriplet is that Scriplet NEVER CAUSE TRANSITION ERRORS.
-Scriplet CAN BE BROKEN by STATIC content.<% Java Code %>
<%------------
------------
------------%>

-Nothing but pure java code goes in the dotted area.
-Any data declared become local to service().

TomJSP.jsp/j3
 
<html>
<body>
<%
      String name=request.getParameter ("name");
     if(name.equalsIgnoreCase("Tom"))
       {
          out.println("Hi Tom!!!");
          out.println("How are You ?");
       }
else
      {
         out.println("Who You ?");
         out.println("I don't know You");
      }
%>
</body>
</html>

URL:http://localhost:8080/learningkattaWebApp/j3 ?name=Tom

ScripletTomJSP.jsp/j4
 
<html>
<head> Scriplet Tom </head>
<body>
<b>
       A JSP to demonstrate that SCRIPLET can be broken by static content
</b>
<% String name=request.getParameter("name");
      if(name.equals("tom"))
          {
%>  
<b> 
Hi Tom! How are you ?  
</b>
<br>
<%
      }      
      else
     {  
%>
<b>
Who you ? I don't know you ?  <%= name %>
<%
       }




%>
</body>
</html>

Data Declaration and Method Definition


 Data Declaration and Method Definition

-There may arise a case when a programmer requires to use his own method.
-But till yet, we have seen that whatever we write goes in servlet method (service ()).
-As JSP Declaration doesn't provide any output they are used in conjuction with JSP Expression and JSP Scriplets.

<%! Data Declaration; %>
<%! Method Definition()
{
}
%>

<%! int count=0; %>
<%! public String m1()
{
return "Hello";
}
%>
-Method returning some values are allowed in JSP Declaration.
http://localhost:8080/learningkattaWebApp/j2?name=Tom

HelloDeclarationJSP.jsp
 
<html>
<body>

Data Declaration and Method Definition

b) Data Declaration and Method Definition
-There may arise a case when a programmer requires to use his own method.
-But till yet, we have seen that whatever we write goes in servlet method (service ()).
-As JSP Declaration doesn't provide any output they are used in conjuction with JSP Expression and JSP Scriplets.




<%! Data Declaration; %>
<%! Method Definition()
{
}
%>
<%! int count=0; %>
<%! public String m1()
{
return "Hello";
}
%>
-Method returning some values are allowed in JSP Declaration.
http://localhost:8080/learningkattaWebApp/j2?name=Tom

HelloDeclarationJSP.jsp
 


<%! 
public String sayHello(String name)
{
return "Hello" + name;
}
%>
Message:<%= sayHello(request.getParameter("name") %?>


<%! 
public String sayHello(String name)
{
return "Hello" + name;
}
%>
Message:<%= sayHello(request.getParameter("name") %?>
</body>
</html>

Expressions-JSP


-JSP expression automatically print out whatever is being sent between the tags.
-Expressions are evaluated and output is sent to the browser.
-Expressions are later resolved and consumed by HTML itself.
<%= expression %>[Anything which comes on right hand side int i=1;
int z=x+y;
Date dt =new Date();



Point To REMEMBER:
NO semi-colon at the end.
Ease of using Expressions.
Without expression:
 
<%@ page import="java.util.* %>
<html>
<body>
Date: <% out.println(new Date());%>
</body>
</html>

With expression:
 
<%@ page import="java.util.*" %>
<html>
<body>
Today's Date:<%=new Date() %>
</body>
</html>

-Whenever container encounters expression, Container takes everything typed between the <%= %> and put it as an argument in out.println() <%= new Date() %>Becomes
out.println(new Date());
Tip for Students:
You people always by mistake put up a semi-colon at the end which result in
<%= new Date(); %>
Becomes
out.println(new Date(););
Which becomes error then.
Hence,No semi-colon(;) at the end of Expression.
FirstJSP.jsp
 
<%@ page import="java.util.*" %>
<html>
<body>
<%@ include file="Header.html" %>
<b>
<Hello User!!!Welcome to the world of  JSP !!
</b>




Current Date : <%= new Date() % > 
<%@ include file="Footer.html"  %>
</body>
</html>

include Directive
-include directive are given after <html> and before </html>.
-It makes the static inclusion of .html/.jsp file.
-These files are include during translation.

Syntax:
<%@ include file="somename.html" %>
-Include .html/.jsp file should not contain <html> and </html>.


Header.html
 
<body>
<h6>Welcome To Asterix Solution</h6><br>
<hr>
</body>

Footer.html
 
<body>
<hr>
<br>
<h6>This website is a copyright</h6>
</body>

IncludeJSP.jsp
 
<%@ page language="Java" %>
<html>
<body>




<%@ include file="Header.html" %>
<p> Please login..........</p>
>%@ include file="Footer.html" %>
</body>
</html>

a)Page Directive
-This tag is always given above tag.
-Controls resultant translated page.
-No output.
Syntax:
<%@ page attribute="value" attribute="value" %>



Attribute of page directive.i) language
-By default java is used.
<%@ page language="Java" %>

|

-It is used for future consideration, where JSP might support language other than java.
ii) import 
-import package required by this JSP page.
-This is the only attribute which can be repeated more than once.
<%@ page language="Java" import="java.util.*" import="java.sql.*" %>
OR
<%@ page language="Java" import="java.util.*, java.sql.*" %>

iii) buffer-JSP does not uses PrintWriter, but uses JSPWriter.
-Buffer can be "none","8 kb","12 kb" as per requirement.
<%@page buffer="15 kb" %>

iv) autoflush-Defines whether the buffered output is flushed automatically.
-Default value is true.
-If false is passed, an IOException is generated.
<%@ page autoflush="true" %>

v)isErrorPage -Defines whether current page represent JSP error page.
-Default value is "false",but if it's change to true,page has access to implicit exception object.
<%@ page isErrorPage="true" %>

vi) errorPage-Defines the URL to which Exception should be sent.
-The target JSP's isErrorPage value should be true.
<%@ page errorPage="MyExceptionPage.jsp" %>

vii) session-Defines whether page will have implicit session object.
-Default value is "true".
<%@ page session="true" %>
equivalent to getSession(true);
<%@ page session="false" %>
equivalent to getSession(false);

viii) isThreadSafe-Defines whether the generated servlet need to implement the SingleThreadModel.
-Default value is "true".

public void jspInit()
- This method is invoked when JspPage is intialised.
- This method is called once in the life-time of JSP Page.
- To put Jsp in service, jspInit() must get completed successfully.

public void _jspService(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException
- The _jspService() corresponds to the body of JSP page.
- This method is defined automatically by the Container & this should not be defined by JSP page author.
- This method is called many a times in its life cycle .

public void jspDestroy()
- This method is invoked when Jsp Page is about to be destroyed.

JSP Comments
- Comments can be used in JSP.
- Two different types of comments are allowed in JSP.

JSP ARCHITECTURE - Whenever a request arises for .jsp file.


JSP-ENGINE will :
i) Translate .jsp file into a .java file.
ii) Compiles the file into a servlet file.

Container will:
iii) Load the servlet class.
iv) Instantiate it using default constructor.
v) Invokes jspInit()
Required that :
a) jspInit() does not throw any exception.
b) jspInit() returns in stipulated time.
vi) Put the servlet in service.
vii) Creates request & response object.
viii) Starts the thread, invoke _jspService() & passes request & response object as arguments.
ix) Retreive the request parameter, perform processing, send responses to the client using writer object.
x) Close the writer object.
xi) When Container shut downs jspDestroy() is invoked.
SERVLETS V/S JSP

1)Servlet
- Servlet does not have any separation between dynamic & static contents.
JSP
- JSP has a clean separation between dynamic & static content.

2)Servlet
- Servlet does not have support for implicit objects.
JSP
- JSP supports implicit objects.

3)Servlet
- Servlet supports any protocol including Http.
JSP
- JSP supports only Http protocol.

4)Servlet
- Servlets are pure java program stored with extension (.java).
JSP
- JSPs are document-centric stored with extension(.jsp)

5)Servlet
- If any changes are made in .class file. It has to be redeployed
JSP
- Whenever any changes are made to (.jsp) file, JSP ENGINE Retranslates & recompiles, hence no redeployment.

WHY JSP?
Servlet follows Component architecture, follows request response model.



- All the code goes inside service() / doGet () / doPost().
- This makes Servlet monolithic in nature.
- It is a tough job to write all the code in same method.
- Hence there emerged a need for a clear separation between CONTENT GENERATION & CONTENT REPRESENTATION.
- Using JSP Separation found was something like this.

Java Server Pages- JSP stands for Java Server Pages.
- JSP is a text document with any name which can contain 100% HTML tags & additional tags to embed java code.
- It is a java technology which allows software developer to dynamically generate HTML, XML or other types of document in response to Web client request.
- This document is stored in WEB-ROOT of a WEB-APPLICATION.
- Whenever the request comes for any jsp for the first time, JSP ENGINE (which) is part of Container translates .jsp into a .java file.
- Translated .java file is nothing but a 100% HttpServlet.
- Whenever any changes are made in .jsp file. JSP ENGINE retranslates & Recompile it.





ADVANTAGES OF JSP1)WRITE ONCE, RUN ANYWHERE
- JSP technology is platform independent.
- JSP can be written on any platform, it can run from any platform & can
Be accessed from any web-browser on any platform.

2)HIGH QUALITY TOOL SUPPORT
- An explicit goal of Java Server Pages design is to enable the creation of high quality portable tools.

3)REUSE OF COMPONENTS & TAG LIBRARIES
- JSP uses reusable components such as
JAVA BEANS
ENTERPRISE JAVA BEANS
TAG LIBRARIES 

- This save development time as well as gives cross-platform power & flexibility of Java programming.

4)SEPERATION OF DYNAMIC & STATIC CONTENT
- JSP enables separation of dynamic contents from static contents that is inserted in static template.
- This makes work easier & hence diminishes the dependency of WEB-DESIGNER over WEB-DEVELOPER & vice-versa.

5)SUPPORTS SCRIPTING & ACTIONS
- JSP supports scripting elements as well as actions.
- Action permits ENCAPSULATION.
- Scripting provides mechanism to glue-together functionalities.