Sunteți pe pagina 1din 34

07/10

public class WrapperTest {


public static void main(String[] args) {
System.out.println(Byte.MIN_VALUE);
System.out.println(Byte.MAX_VALUE);
System.out.println(Long.SIZE+" bits");
System.out.println(Long.BYTES+" byte");
int n1=25;
Integer n2=n1;
int n3=n2;
System.out.println(n1+"\t"+n2+"\t"+n3);
Integer i1=new Integer(25);
Integer i2=new Integer("25");
System.out.println(i1+"\t"+i2);
byte b=i1.byteValue();
float f=i1.floatValue();
System.out.println(b+"\t"+f);
Integer i3=Integer.valueOf("25");
System.out.println(i3);
}
}

import java.io.File;
public class FileTest1 {
public static void main(String[] args) {
File f=new File("src/co/edureka/WrapperTest.java");
System.out.println(f.exists());
if(f.exists()) {
System.out.println(f.getName());
System.out.println(f.getPath());
System.out.println(f.getAbsolutePath());
System.out.println(f.length()+" bytes");
System.out.println(f.canRead());
System.out.println(f.canWrite());
System.out.println(f.isHidden());
System.out.println("File - "+f.isFile());
System.out.println("Directory - "+f.isDirectory());
long l=f.lastModified();
java.util.Date d=new java.util.Date(l);
System.out.println("File is modified on : "+d);
}
}
}
import java.io.FileOutputStream;
public class WriteToFile {
public static void main(String[] args) throws Exception{
FileOutputStream fos=new FileOutputStream("src/java.txt") String str="Java is a
program language.\nJava is mainly used for developing\nPlatform Independent
applications.\nAn application developed in one operating system\nwill run in any
other operating system."; byte[] data=str.getBytes(); fos.write(data); fos.close();
System.out.println("file created"); }
}

import java.io.BufferedReader;
import java.io.FileInputStream; import java.io.InputStreamReader;
public class ReadFromFile {
public static void main(String[] args) throws Exception { FileInputStream fis=new
FileInputStream("src/java.txt"); /* System.out.println("No of bytes to be read =
"+fis.available()); System.out.println((char)fis.read());
System.out.println((char)fis.read()); System.out.println("No of bytes to be read =
"+fis.available()); */ /* int n=fis.read(); while(n!=-1)
{ System.out.print((char)n); n=fis.read(); Thread.sleep(100); } */
public 8:59 AM
Sunil (Organizer, Presenter)to Everyone
/* byte[] b=new byte[fis.available()]; fis.read(b); String s=new String(b);
System.out.println(s); */

InputStreamReader source=new InputStreamReader(fis); BufferedReader br=new


BufferedReader(source); String line=br.readLine(); while(line!=null)
{ System.out.println(line); line=br.readLine(); Thread.sleep(1500); }
fis.close(); }
}

07/11

import java.util.ArrayList;
import java.util.List;
public class ArrayListTest1 {
public static void main(String[] args) {
List<String> names=new ArrayList<>();
names.add("Sunil");
names.add("Ajay");
names.add("Srinivas");
names.add("Sumith");
System.out.println("No of Participants = "+names.size());
System.out.println(names);
names.add(0,"edureka");
System.out.println(names);
names.set(1,"Joseph");
System.out.println(names);
String name=names.get(3);
System.out.println(name);
names.remove(3);
System.out.println(names);
}
}

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListIterator;
public class ArrayListTest2 {

public static void main(String[] args) throws Exception { ArrayList<Integer> al=new


ArrayList<>(); for(int i=10;i<=16;i++){ al.add(i); } System.out.println(al);
//Tech-1 using for loop for(int i=0;i<al.size();i++){ int n=al.get(i);
System.out.print(n+"\t"); } System.out.println();
public 8:18 AM
Sunil (Organizer, Presenter)to Everyone
System.out.println(); Thread.sleep(1000);

//Tech-3 using Iterator Iterator<Integer> it=al.iterator(); while(it.hasNext())


{ Integer n=it.next(); System.out.print(n+"\t"); } System.out.println();
Thread.sleep(1000); //Tech-4 using ListIterator ListIterator<Integer>
lit=al.listIterator(); while(lit.hasNext()){ Integer n=lit.next();
System.out.print(n+"\t"); } System.out.println(); Thread.sleep(1000);
while(lit.hasPrevious()){ int n=lit.previous(); System.out.print(n+"\t"); }
System.out.println(); Thread.sleep(1000); //Tech-5 using Enumeration
Enumeration<Integer> en=Collections.enumeration(al); while(en.hasMoreElements())
{ System.out.print(en.nextElement()+"\t"); }
public 8:18 AM
Sunil (Organizer, Presenter)to Everyone
System.out.println(); Thread.sleep(1000);

Iterator<Integer> it1=al.iterator(); while(it1.hasNext()){ Integer n=it1.next();


System.out.print(n+"\t"); //it1.remove(); } System.out.println();
Thread.sleep(1000); System.out.println(al); System.out.println();
Thread.sleep(1000); Collections.reverse(al); for(int x : al)
System.out.print(x+"\t"); } }
}
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import
java.util.Set;

public class Bank {

public static void main(String[] args) throws Exception{ HashMap<String, Double>


accs=new HashMap<String, Double>(); accs.put("Sunil",11250.00);
accs.put("Anil",12500.00); accs.put("Ramesh",15000.50);
accs.put("Shankar",25000.00); System.out.println(accs); System.out.print("Account
Holders : "); Set<String> acHolders=accs.keySet(); for(String name : acHolders)
{ System.out.print(name+"\t"); } System.out.println(); Thread.sleep(1000);
public 9:09 AM
Sunil (Organizer, Presenter)to Everyone
double bal=accs.get("Sunil"); System.out.println("A/c Balance of Sunil = "+bal);
bal+=1500.00; accs.put("Sunil", bal); System.out.println(accs);
System.out.println("---------------------------------------");

Set<Map.Entry<String, Double>> entries=accs.entrySet(); Iterator<Map.Entry<String,


Double>> it=entries.iterator(); while(it.hasNext()){ Map.Entry<String, Double>
entry=it.next(); System.out.println(entry.getKey()+" - "+entry.getValue());
Thread.sleep(1000); } }
}

import java.sql.*;

class CreateTable { public static void main(String[] args) throws Exception


{ Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","java27","java27"
); Statement st=con.createStatement(); String sql="create table emp(empno number(5)
primary key, ename varchar(30), sal number(10,2))"; try{ st.execute(sql);
System.out.println("DB Table created.."); } catch(Exception e)
{ System.out.println("Exception : "+e.toString()); } st.close(); con.close(); }
}
public 8:46 AM
Sunil (Organizer, Presenter)to Everyone
java -classpath C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc5.jar;.;
CreateTable

package co.edureka.jdbc;

import java.sql.Connection; import java.sql.DriverManager; import


java.sql.Statement;

public class CreateTable {

public static void main(String[] args) throws Exception


{ Class.forName("com.mysql.jdbc.Driver"); Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","java27","ja
va27"); Statement st=con.createStatement(); String sql="create table emp(empno
int(5) primary key, ename varchar(30), sal float(10,2))"; try{ st.execute(sql);
System.out.println("DB Table Created"); } catch(Exception e)
{ System.out.println(e.toString()); } st.close(); con.close(); }
}

public 9:04 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka.jdbc;

import java.sql.Connection; import java.sql.DriverManager; import


java.sql.Statement;

public class InsertRecord {

public static void main(String[] args) throws Exception


{ Class.forName("com.mysql.jdbc.Driver"); Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","java27","ja
va27"); Statement st=con.createStatement(); //String sql="insert into emp
values(101,'Sunil',123.45)"; String sql="insert into emp values(102,'Anil',223.45),
(103,'Srinivas',334.56)"; try{ int n=st.executeUpdate(sql);
System.out.println("Employee Saved : "+n); } catch(Exception e)
{ System.out.println(e.toString()); } st.close(); con.close(); }
}

07/12

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class BatchExec {
public static void main(String[] args) throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root","");
Statement st=con.createStatement();
con.setAutoCommit(false);
st.addBatch("insert into emp values(101,'A',123.45)");
st.addBatch("insert into emp values(102,'B',223.45)");
st.addBatch("insert into emp values(103,'C',323.45)");
st.addBatch("update emp se sal=999.99");
try{
int[] n=st.executeBatch();
for(int x : n){
System.out.println("Records Affected : "+x);
}
con.commit();
}
catch(Exception e){
con.rollback();
System.out.println(e.getMessage());
}
st.close();
con.close();
}
}

07/13

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class PreparedTest {
public static void main(String[] args) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","java27","jav
a27");
PreparedStatement pst=con.prepareStatement("insert into emp(empno,ename,sal)
values(?,?,?)"); pst.setInt(1, 109); pst.setString(2, "edureka"); pst.setDouble(3,
999.99); int n=pst.executeUpdate(); System.out.println("Employee Saved");
pst.clearParameters(); pst.setInt(1, 110); pst.setString(2, "Pragathi");
pst.setDouble(3, 888.99); n=pst.executeUpdate(); System.out.println("Employee
Saved"); pst.close(); con.close(); }
}

create or replace procedure addNum(a IN number, b IN number, c OUT number) is begin


c := a+b; end; /
package co.edureka.jdbc;

import java.sql.CallableStatement; import java.sql.Connection; import


java.sql.DriverManager; import java.sql.Types;

public class Procedure {

public static void main(String[] args) throws Exception


{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","java27","jav
a27"); CallableStatement cst=con.prepareCall("{call addNum(?,?,?)}"); cst.setInt(1,
22); cst.setInt(2, 31); cst.registerOutParameter(3, Types.INTEGER); cst.execute();
System.out.println("Sum = "+cst.getInt(3)); cst.close(); con.close(); }
}

07/14

import javax.servlet.; import java.io.;

public class LifecycleServlet extends GenericServlet { public void


init(ServletConfig config) throws ServletException{ super.init(config);
System.out.println("Inside init method"); }

public void service(ServletRequest request, ServletResponse response) throws


ServletException, IOException{ System.out.println("Inside service method.."); }

public void destroy(){ System.out.println("Inside destroy"); } }

<web-app> <display-name>welcome to webapp@edureka</display-name>

<servlet> <servlet-name>lifeCycle</servlet-name> <servlet-


class>LifecycleServlet</servlet-class> </servlet>

<servlet-mapping> <servlet-name>lifeCycle</servlet-name> <url-pattern>/life</url-


pattern> </servlet-mapping> </web-app>

import javax.servlet.; import java.io.;

public class HtmlTextServlet extends GenericServlet {

public void service(ServletRequest request, ServletResponse response) throws


ServletException, IOException{ response.setContentType("text/html"); PrintWriter
out=response.getWriter();

out.println("<html><body bgcolor=pink><h1 align=center>"); out.println("edureka


limited</h1>"); out.println("<center><img src=images/edureka.jpg width=200
height=100></center>"); out.println("</body></html>");
}
}
<servlet> <servlet-name>html</servlet-name> <servlet-
class>HtmlTextServlet</servlet-class> </servlet> <servlet-mapping> <servlet-
name>html</servlet-name> <url-pattern>/html</url-pattern> </servlet-mapping>

<html> <head> <style type="text/css"> body { background-color:#4682b4; font-


family:verdana; } #wrapper { background-color:#8e4585; height:450px; width:950px;
margin:auto; margin-top:150px; border-radius:10px; padding:20px; } h1 { text-
align:center; font-size:25px; } table { width:400px; font-size:18px; background-
color:orange; border-radius:10px; padding:10px; } tr { height: 45px; } </style>
</head>

<body> <div id="wrapper"> <h1>edureka login</h1> <hr color=blue size=5 width=19%>


<br><br> <form action="login" method="post"> <table align=right> <tr> <td>User
Name</td> <td><input type="text" name="uid" size="30" autofocus="autofocus"
required="required" placeholder="enter user name"></td> </tr>

<tr> <td>Password</td> <td><input type="password" name="pwd" size="30"


required="required"> </td> </tr>

<tr> <td colspan="2" align="center"> <input type="submit" value="Login"> </td>


</tr></table></form></div></body></html>

import java.io.; import java.sql.; import javax.servlet.; import


javax.servlet.http.;

public class LoginServlet extends HttpServlet { static Statement st=null;

public void init(ServletConfig config) throws ServletException{ super.init(config);


try{ Class.forName("com.mysql.jdbc.Driver"); Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root","");
st=con.createStatement(); } catch(Exception e){e.printStackTrace();} }

public 8:41 AM
Sunil (Organizer, Presenter)to Everyone
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException{ String uid=req.getParameter("uid"); String
pwd=req.getParameter("pwd");

String sql="select * from users where username='"+uid+"' and password='"+pwd+"'";


try{ ResultSet rs=st.executeQuery(sql); if(rs.next()){ RequestDispatcher
rd=req.getRequestDispatcher("admin"); rd.forward(req,res); }
else{ res.setContentType("text/html"); PrintWriter out=res.getWriter();
out.println("<p style=text-align:right;font-size:20px;color:yellow>Invalid
Username/ Password</p>") RequestDispatcher
rd=req.getRequestDispatcher("Login.html"); rd.include(req,res); } } catch(Exception
e){e.printStackTrace();}
}

public void doPost(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException{ doGet(req,res); } }
public 8:41 AM
Sunil (Organizer, Presenter)to Everyone
import java.io.; import javax.servlet.; import javax.servlet.http.*;

public class AdminServlet extends HttpServlet { public void


doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException{ doPost(req,res); } public void doPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException{ res.setContentType("text/html"); PrintWriter out=res.getWriter();
out.println("<h1 align=center>WELCOME TO ADMIN PAGE@EDUREKA</h1><br><br>");
out.println("<h2>Hello, "+req.getParameter("uid")+"</h2>"); } }

public 8:41 AM
Sunil (Organizer, Presenter)to Everyone
<servlet> <servlet-name>admin</servlet-name> <servlet-class>AdminServlet</servlet-
class> </servlet> <servlet-mapping> <servlet-name>admin</servlet-name> <url-
pattern>/admin</url-pattern> </servlet-mapping>

<servlet> <servlet-name>login</servlet-name> <servlet-class>LoginServlet</servlet-


class> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-
pattern>/login</url-pattern> </servlet-mapping> </web-app>

public 8:42 AM
javaconnector in lib
classes in classes
web.xml in wen-inf

07/17

import java.io.; import javax.servlet.; public class LoginFilter implements Filter


{ public void init(FilterConfig config) throws ServletException{} public void
destroy(){} public void doFilter(ServletRequest req, ServletResponse res,
FilterChain fc) throws ServletException, IOException{ String
s1=req.getParameter("uid"); String s2=req.getParameter("pwd");
if(s1.equals("edureka") && s2.equals("edureka123")){ fc.doFilter(req,res); }
else{ RequestDispatcher rd=req.getRequestDispatcher("Login.html");
rd.forward(req,res); } } }

public 9:10 AM
Sunil (Organizer, Presenter)to Everyone
import java.io.; import javax.servlet.; import javax.servlet.http.*;

public class AdminServlet extends HttpServlet { public void


doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException{ doPost(req,res); } public void doPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException{ res.setContentType("text/html"); PrintWriter out=res.getWriter();
out.println("<h1 align=center>WELCOME TO ADMIN PAGE@EDUREKA</h1><br><br>");
out.println("<h2>Hello, "+req.getParameter("uid")+"</h2>"); } }

<form action="admin" method="post">

servlet> <servlet-name>admin</servlet-name> <servlet-class>AdminServlet</servlet-


class> </servlet> <servlet-mapping> <servlet-name>admin</servlet-name> <url-
pattern>/admin</url-pattern> </servlet-mapping>
<filter> <filter-name>fname</filter-name> <filter-class>LoginFilter</filter-class>
</filter> <filter-mapping> <servlet-name>admin</servlet-name> <filter-
name>fname</filter-name> </filter-mapping> </web-app>

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;

@WebServlet("/Form1") public class Form1 extends HttpServlet { private static final


long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out=response.getWriter(); out.println("<body bgcolor=cyan>");
out.println("<form action=Form2><h1>"); out.println("Name <input type=text name=t1
size=30><br><br>"); out.println("Age <input type=text name=t2 size=30><br><br>");
out.println("Address <input type=text name=t3 size=30><br><br>");
out.println("<input type=submit value=SUBMIT>");
out.println("</body></html>"); } }}
public 9:12 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;

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; import javax.servlet.http.HttpSession;

@WebServlet("/Form2") public class Form2 extends HttpServlet { private static final


long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out=response.getWriter(); String s1=request.getParameter("t1"); String
s2=request.getParameter("t2"); String s3=request.getParameter("t3");
public 9:12 AM
Sunil (Organizer, Presenter)to Everyone
HttpSession session=request.getSession(); session.setAttribute("Name",s1);
session.setAttribute("Age",s2); session.setAttribute("Address",s3);

/* Cookie c1=new Cookie("Name",s1); Cookie c2=new Cookie("Age",s2); Cookie c3=new


Cookie("Addrs",s3); c1.setMaxAge(60*60*24*180); response.addCookie(c1);
response.addCookie(c2); response.addCookie(c3); */ out.println("<body
bgcolor=cyan>"); out.println("<h1>Session - ID : "+session.getId()+"</h1>");
out.println("<form action=Form3><h1>"); out.println("Years of Exp <input type=text
name=t4 size=30><br><br>"); out.println("Lang Known <input type=text name=t5
size=30><br><br>"); /* out.println("<input type=hidden name=t1 value=\""+s1+"\">");
out.println("<input type=hidden name=t2 value=\""+s2+"\">"); out.println("<input
type=hidden name=t3 value=\""+s3+"\">"); */ out.println("<input type=submit
value=SUBMIT>"); out.println("</body></html>"); }
}

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; import javax.servlet.http.HttpSession;

@WebServlet("/Form3") public class Form3 extends HttpServlet { private static final


long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out=response.getWriter(); /* String s1=request.getParameter("t1");
String s2=request.getParameter("t2"); String s3=request.getParameter("t3"); */
String s4=request.getParameter("t4"); String s5=request.getParameter("t5");
public 9:12 AM
Sunil (Organizer, Presenter)to Everyone
/* Cookie c1=new Cookie("Exp",s4); Cookie c2=new Cookie("Lang",s5);

c1.setMaxAge(60*60*24*60); response.addCookie(c1); response.addCookie(c2); */


HttpSession session=request.getSession(); session.setAttribute("Exp",s4);
session.setAttribute("Lang",s5); out.println("<body bgcolor=cyan>");
out.println("<h1>Session - ID : "+session.getId()+"</h1>"); out.println("<form
action=Form4><h1>"); out.println("Exp Salary <input type=text name=t6
size=30><br><br>"); /* out.println("<input type=hidden name=t1 value=\""+s1+"\">");
out.println("<input type=hidden name=t2 value=\""+s2+"\">"); out.println("<input
type=hidden name=t3 value=\""+s3+"\">"); out.println("<input type=hidden name=t4
value=\""+s4+"\">"); out.println("<input type=hidden name=t5 value=\""+s5+"\">");
*/ out.println("<input type=submit value=SUBMIT>");
out.println("</body></html>"); }}

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


java.util.Enumeration;

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 javax.servlet.http.HttpSession;

@WebServlet("/Form4") public class Form4 extends HttpServlet { private static final


long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out=response.getWriter(); HttpSession session=request.getSession();
out.println("<body bgcolor=cyan>"); out.println("<h1>Session - ID :
"+session.getId()+"</h1><h1>"); Enumeration<String>
names=session.getAttributeNames(); while(names.hasMoreElements()){ String
name=names.nextElement(); String value=session.getAttribute(name).toString();

out.println(name+" - "+value+"<br>"); } /* Cookie[] cookies=request.getCookies();


for(Cookie cookie : cookies){ String name=cookie.getName(); String
value=cookie.getValue(); out.println(name+" - "+value+"<br>"); } / /
out.println("T1 - "+request.getParameter("t1")+"<br>"); out.println("T2 -
"+request.getParameter("t2")+"<br>"); out.println("T3 -
"+request.getParameter("t3")+"<br>"); out.println("T4 -
"+request.getParameter("t4")+"<br>"); out.println("T5 -
"+request.getParameter("t5")+"<br>"); */

out.println("T6 - "+request.getParameter("t6")); out.println("</body></html>"); }


}
https://register.gotowebinar.com/register/7991500482905067522

9019117772

Each entry(key valuepair) in a map is of the type Map.Entry

login id: 31120160055 pwd: Bits@97822

CRUD operation: Create Retrieve Update Delete

jdbc vs dao

07/19

JSTL
The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP
development

Download JSTL Tag Libraries from

http://tomcat.apache.org/download-taglibs.cgi

Download the 4 jar files and place it in the "lib" folder of our web application in
Tomcat

1.jsp

<h1> <%@taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <c:out


value="Welcome to edureka" />

2.jsp

<h1> <%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %> <c:set var="s"


value="edureka" /> <c:out value="${s}" /> <c:remove var="s" /> <br> <c:out
value="Value is ${s}" />

public 8:04 AM
Sunil (Organizer, Presenter)to Everyone
3.jsp

<h1> <%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %> <c:set var="a"


value="10" /> <c:set var="b" value="20" /> <c:out value="Product = ${a*b}" /> <br>
<c:set var="c" value="30" /> <c:out value="${(a<b) && (a<c)}" />
4.jsp

<h1> <%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %> <c:out


value="Name = ${param.t1}" />

<!-- http://localhost:65535/edureka/4.jsp?t1=Sunil -->

5.jsp

<h1> <%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>

public 8:04 AM
Sunil (Organizer, Presenter)to Everyone
<c:set var="var1" value="edureka" /> <c:if test="${empty var1}"> <c:out value="No
value for variable - 1" /> </c:if>

6.jsp

<h1> <%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %> <c:set


var="var1" value="edureka" /> <c:if test="${!empty var1}"> <c:out value="Value = $
{var1}" /> </c:if>

public 8:04 AM
Sunil (Organizer, Presenter)to Everyone
7.jsp

<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %> <h1> First 10


Natural Numbers are:<br>

<c:forEach var="i" begin="1" end="10" step="1"> <c:out value="${i}" /><br>


</c:forEach>

8.jsp

<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %> <h1> <c:forEach


var="i" items="One,Two,Three,Four,Five"> <c:out value="${i}" /><br> </c:forEach>

9.jsp

<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %> <h1> <c:forTokens


var="i" items="One.Two.Three.Four" delims="."> <c:out value="${i}" /><br>
</c:forTokens>

10.jsp

<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %> <h1> <c:choose>


<c:when test="${param.course=='C'}"> <c:out value="U Have selected for C language "
/> </c:when> <c:when test="${param.course=='CPP'}"> <c:out value="U Have selected
for C++ language " /> </c:when> <c:otherwise> <c:out value="No course opted" />
</c:otherwise> </c:choose>

<!-- http://localhost:65535/edureka/10.jsp?course=C -->

11.jsp
<%@taglib uri="http://java.sun.com/jstl/sql_rt" prefix="sql" %> <%@taglib
uri="http://java.sun.com/jstl/core_rt" prefix="c" %>

<sql:setDataSource var="ds" driver="oracle.jdbc.driver.OracleDriver"


url="jdbc:oracle:thin:@localhost:1521:XE" user="edureka" password="edureka" />

<sql:query var="result" dataSource="${ds}" sql="select empno,ename,sal from emp" />

<table border=1 width=60% align=center style=font-family:verdana;font-size:16px >


<tr> <th>EMP NO</th> <th>EMP NAME</th> <th>SALARY</th> </tr>

<c:forEach var="row" items="${result.rows}" > <tr> <td><c:out value="$


{row.empno}" /></td> <td><c:out value="${row.ename}" /></td> <td><c:out value="$
{row.sal}" /></td> </tr> </c:forEach>

<sql:transaction dataSource="${ds}"> sql:update update emp set sal=? where empno=?


<sql:param value="2222"/> <sql:param value="101" /> </sql:update>
</sql:transaction>

07/20

package co.edureka;

public class Student { private Integer studid; private String sname, email, mobile;

public Student(){}

public Student(String sname, String email, String mobile){ this.sname=sname;


this.mobile=mobile; this.email=email; }

public Student(Integer studid, String sname, String email, String mobile)


{ this.studid=studid; this.sname=sname; this.mobile=mobile; this.email=email; }

public Integer getStudid() { return studid; }

public void setStudid(Integer studid) { this.studid = studid; }

public String getSname() { return sname; }

public void setSname(String sname) { this.sname = sname; }

public String getEmail() { return email; }

public void setEmail(String email) { this.email = email; }

public String getMobile() { return mobile; }

public void setMobile(String mobile) { this.mobile = mobile; }

public String toString(){ return "Student :


"+this.studid+"\t"+this.sname+"\t"+this.email+"\t"+this.mobile; } }

in co.edureka package - student.hbm.xml


<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="co.edureka.Student" table="student">

<id name="studid" column="studid"> <generator class="increment"/> </id>

<property name="sname" type="string" column="sname"/>

<property name="email" column="email"/>

<property name="mobile"/>

</class>

</hibernate-mapping>

In src package - hibernate.cfg.xml

<?xml version="1.0"?> <!DOCTYPE hibernate-configuration PUBLIC


"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration> <session-factory> <property


name="hibernate.connection.driver_class">
oracle.jdbc.driver.OracleDriver</property>

<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>

<property name="hibernate.connection.username">java27</property> <property


name="hibernate.connection.password">java27</property>

<property name="hibernate.dialect">
org.hibernate.dialect.Oracle10gDialect</property>

<property name="show_sql">true</property>

<mapping resource="co/edureka/student.hbm.xml"/> </session-factory> </hibernate-


configuration>

package co.edureka;

import org.hibernate.SessionFactory; import


org.hibernate.boot.registry.StandardServiceRegistry; import
org.hibernate.boot.registry.StandardServiceRegistryBuilder; import
org.hibernate.cfg.Configuration;

public class HibernateUtils { public static SessionFactory getSessionFactory()


{ Configuration config=new Configuration(); config.configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder sb=new StandardServiceRegistryBuilder();
sb.applySettings(config.getProperties()); StandardServiceRegistry
registry=sb.build();

SessionFactory sf=config.buildSessionFactory(registry); return sf;


} }

package co.edureka;

import java.util.Scanner;

import org.hibernate.Session; import org.hibernate.SessionFactory; import


org.hibernate.Transaction;

public class InsertStudents {

public static void main(String[] args) { SessionFactory


sf=HibernateUtils.getSessionFactory(); Session session=sf.openSession();
Transaction t=session.beginTransaction(); Scanner sc=new Scanner(System.in); String
req="Y"; while(req.equalsIgnoreCase("Y")) { System.out.println("enter
sname,email,mobile"); String name=sc.next(); String email=sc.next(); String
mobile=sc.next(); Student st=new Student(name,email,mobile); session.save(st);
System.out.print("Do you want to save more students[Y/N]:\t") req=sc.next(); }
System.out.println("-------------------------------------"); t.commit();
session.close(); sf.close(); }
}

package co.edureka;

import org.hibernate.Session; import org.hibernate.SessionFactory;

public class SearchStudent {

public static void main(String[] args) { SessionFactory


sf=HibernateUtils.getSessionFactory(); Session session=sf.openSession(); /* Student
st=new Student(); session.load(st, new Integer(1021)); */ Student
st=(Student)session.get(Student.class, new Integer(1011)); if(st!=null)
System.out.println(st); else System.out.println("No matching student found!!");
session.close(); sf.close(); }
}

/*package co.edureka;

import org.hibernate.Session; import org.hibernate.SessionFactory;

public class SearchStudent {

public static void main(String[] args) { SessionFactory


sf=HibernateUtils.getSessionFactory(); Session session=sf.openSession(); /* Student
st=new Student(); session.load(st, new Integer(1021)); */ Student
st=(Student)session.get(Student.class, new Integer(1011)); if(st!=null)
System.out.println(st); else System.out.println("No matching student found!!");
session.close(); sf.close(); }
}
*/

package co.edureka;

import org.hibernate.Session; import org.hibernate.SessionFactory;

public class UpdateStudent {

public static void main(String[] args) { SessionFactory


sf=HibernateUtils.getSessionFactory(); Session session=sf.openSession();
session.beginTransaction(); /* Student st=new Student(111,"Sunil
Jose","sunil@yahoo.com","2211111111"); //session.update(st);
session.saveOrUpdate(st); */ Student st=(Student)session.get(Student.class, new
Integer(108)); if(st!=null){ System.out.println(st);
st.setMobile("9988774455"); //dirty object } else System.out.println("No matching
student found!!"); session.getTransaction().commit(); session.close();
sf.close(); }
}

saveorupdate vs dirty obj

package co.edureka;

import org.hibernate.Session; import org.hibernate.SessionFactory;

public class DeleteStudent {

public static void main(String[] args) { SessionFactory


sf=HibernateUtils.getSessionFactory(); Session session=sf.openSession();
session.beginTransaction(); Student st=(Student)session.get(Student.class, new
Integer(110)); if(st!=null){ System.out.println(st); session.delete(st); } else
System.out.println("No matching student found!!");
session.getTransaction().commit(); session.close(); sf.close(); }
}

package co.edureka;
import java.util.List;

import org.hibernate.Query; import org.hibernate.Session; import


org.hibernate.SessionFactory;

public class HQLTest1 {

public static void main(String[] args) throws InterruptedException { SessionFactory


sf=HibernateUtils.getSessionFactory(); Session session=sf.openSession(); Query
query=session.createQuery("from co.edureka.Student"); List<co.edureka.Student>
list=query.list(); for(Student st : list) { System.out.println(st);
Thread.sleep(1000); } session.close(); sf.close(); }
}

package co.edureka;

import java.util.List;

import org.hibernate.Query; import org.hibernate.Session; import


org.hibernate.SessionFactory;

public class HQLTest2 {

public static void main(String[] args) throws InterruptedException { SessionFactory


sf=HibernateUtils.getSessionFactory(); Session session=sf.openSession(); Query
query=session.createQuery("from co.edureka.Student where studid between ? and ?");
query.setInteger(0, 101); query.setInteger(1, 105); List<co.edureka.Student>
list=query.list(); for(Student st : list) { System.out.println(st);
Thread.sleep(1000); } session.close(); sf.close(); }
}

package co.edureka;

import java.util.List;

import org.hibernate.Query; import org.hibernate.Session; import


org.hibernate.SessionFactory;

public class HQLTest3 {

public static void main(String[] args) throws InterruptedException { SessionFactory


sf=HibernateUtils.getSessionFactory(); Session session=sf.openSession(); Query
query=session.createQuery("from co.edureka.Student where studid between :minid
and :maxid"); query.setInteger("minid", 103); query.setInteger("maxid", 106);
List<co.edureka.Student> list=query.list(); for(Student st : list)
{ System.out.println(st); Thread.sleep(1000); } session.close(); sf.close(); }
}
import java.util.List;

import org.hibernate.Criteria; import org.hibernate.Session; import


org.hibernate.SessionFactory; import org.hibernate.criterion.Order; import
org.hibernate.criterion.Restrictions;

public class CriteriaTest {

public static void main(String[] args) throws InterruptedException { SessionFactory


sf=HibernateUtils.getSessionFactory(); Session session=sf.openSession(); Criteria
criteria=session.createCriteria(Student.class);
criteria.addOrder(Order.desc("studid"));
criteria.add(Restrictions.between("studid",new Integer(105),new Integer(120)));
//criteria.add(Restrictions.like("sname", "g%"));
criteria.add(Restrictions.ilike("sname", "g%")); List<co.edureka.Student>
list=criteria.list() for(Student st : list) { System.out.println(st);
Thread.sleep(1000); } session.close(); sf.close(); }
}

7/21

Create two tables in Oracle Database server

sql>create table faculty(facid number(5) primary key, facname varchar(30));

sql>create table batch(batchid number(5) primary key, course varchar(70), facid


number(5) references faculty (facid));

Faculty.java

public class Faculty { private Integer facid; private String facname; private Set
batches = new HashSet(); //constructors //getter & setter methods }

Batch.java

public class Batch{ private Integer batchid; private Faculty faculty; private
String course; //constructors //getter & setter methods }

faculty.hbm.xml

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC


"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping> <class name="co.edureka.Faculty" table="faculty"


schema="java27"> <id name="facid" column="facid" > <generator class="assigned" />
</id>

<property name="facname" column="facname"/> <set name="batches" cascade="all">


<key> <column name="facid" precision="5" scale="0" /> </key> <one-to-many
class="co.edureka.Batch" /> </set> </class>
</hibernate-mapping>

batch.hbm.xml

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC


"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping> <class name="co.edureka.Batch" table="batch" schema="java27">


<id name="batchid" column="batchid"> <generator class="assigned" /> </id>

<property name="course" column="course"/> <many-to-one name="faculty"


class="co.edureka.Faculty" fetch="select"> <column name="facid" precision="5"
scale="0" /> </many-to-one> </class>
</hibernate-mapping>

Inside hibernate.cfg.xml

<mapping resource="co/edureka/student.hbm.xml"/> <mapping


resource="co/edureka/faculty.hbm.xml"/> <mapping
resource="co/edureka/batch.hbm.xml"/> </session-factory>

Relations.java

package co.edureka;

import java.util.HashSet; import java.util.Set;

import org.hibernate.Session; import org.hibernate.SessionFactory; import


org.hibernate.Transaction;

public class Relations {

public static void main(String[] args) { SessionFactory


sf=HibernateUtils.getSessionFactory(); Session session=sf.openSession();
Transaction t=session.beginTransaction(); Faculty faculty=new Faculty(101,"Sunil
Joseph"); Batch batch1=new Batch(1,"Java @ 26June ",faculty); Batch batch2=new
Batch(2,"Android @ 8June ",faculty); Batch batch3=new Batch(3,"Java @ 22July
",faculty); Set<Batch> batches=new HashSet<>(); batches.add(batch1);
batches.add(batch2); batches.add(batch3); faculty.setBatches(batches);
session.save(faculty); t.commit(); session.close(); sf.close(); }
}
Hibernate Caching
Caching is all about application performance optimization and it sits between your
application and the database to avoid the number of database hits as many as
possible to give a better performance for performance critical applications.

Hibernate Caching

First-level cache:
The first-level cache is the Session cache and is a mandatory cache through which
all requests must pass. The Session object keeps an object under its own power
before committing it to the database.

If you issue multiple updates to an object, Hibernate tries to delay doing the
update as long as possible to reduce the number of update SQL statements issued. If
you close the session, all the objects being cached are lost and either persisted
or updated in the database.
It is enabled by default by hibernate

Second-level cache:
Second level cache is an optional cache and first-level cache will always be
consulted before any attempt is made to locate an object in the second-level cache.
The second-level cache can be configured on a per-class and per-collection basis
and mainly responsible for caching objects across sessions.

Hibernate second level cache uses a common cache for all the session object of a
session factory. It is useful if you have multiple session objects from a session
factory.

public 8:08 AM
Sunil (Organizer, Presenter)to Everyone
SessionFactory holds the second level cache data. It is global for all the session
objects and not enabled by default.

Different vendors have provided the implementation of Second Level Cache.

EH Cache OS Cache Swarm Cache JBoss Cache


public 8:08 AM
Sunil (Organizer, Presenter)to Everyone
2 extra steps for second level cache example using EH cache

Add 3 configuration setting in hibernate.cfg.xml file


<property name="hibernate.cache.use_second_level_cache">true</property>
<property
name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property
name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegi
onFactory</property>

Add cache usage setting in hbm file <class name="co.edureka.Student"


table="student"> <cache usage="read-only"/>
public 8:09 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;

import org.hibernate.Session; import org.hibernate.SessionFactory;


public class SecondLevelCache {

public static void main(String[] args) throws Exception{ SessionFactory


sf=HibernateUtils.getSessionFactory(); Session session1=sf.openSession(); Session
session2=sf.openSession(); Student st1=(Student)session1.get(Student.class, new
Integer(101)); System.out.println(st1);
System.out.println("----------------------------"); Thread.sleep(1000) Student
st2=(Student)session2.get(Student.class, new Integer(101)); System.out.println(st2)
session1.close(); session2.close(); sf.close(); }
}

public 8:09 AM

Dynamic Table Creation: In hibernate.cfg.xml

<property name="hbm2ddl.auto">update</property>

public 8:21 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;

import javax.persistence.Column; import javax.persistence.Entity; import


javax.persistence.Id; import javax.persistence.Table;

@Entity @Table(name = "Employee", schema = "java27") public class Employee


{ private Integer empno; private String ename; private Double sal;

public Employee() {} public Employee(Integer empno, String ename, Double sal) {


this.empno = empno; this.ename = ename; this.sal = sal; } @Id @Column(name =
"empno", unique = true, nullable = false, length=5) public Integer getEmpno()
{ return empno; } public void setEmpno(Integer empno) { this.empno = empno; }
public 8:21 AM
Sunil (Organizer, Presenter)to Everyone
@Column(name="ename",length=25) public String getEname() { return ename; } public
void setEname(String ename) { this.ename = ename; }

@Column(name="sal",length=10, precision=2) public Double getSal() { return sal; }


public void setSal(Double sal) { this.sal = sal; }
}

public 8:21 AM
Sunil (Organizer, Presenter)to Everyone
<mapping class="co.edureka.Employee" />

public 8:22 AM

7/24

public class Student { private String name=null;


public Student(){ System.out.println("Inside default constructor"); } public
Student(String name){ this.name=name; System.out.println("Inside parameterized
constructor"); } public String getName(){ System.out.println("Inside getName..");
return this.name; } public void setName(String name){ this.name=name;
System.out.println("Inside setName.."); } public void sayHello()
{ System.out.println("Hello, "+this.name); }
}

public 7:34 AM
Sunil (Organizer, Presenter)to Everyone
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="stud1" class="Student" lazy-init="true" scope="prototype"> <property


name="name" value="Sunil" /> </bean> <bean id="stud2" class="Student" lazy-
init="true"> <constructor-arg> <value>Joseph</value> </constructor-arg> </bean>
</beans>

public 7:34 AM
Sunil (Organizer, Presenter)to Everyone
import org.springframework.beans.factory.BeanFactory; import
org.springframework.context.support.ClassPathXmlApplicationContext;

class Main { public static void main(String[] args) { BeanFactory factory=new


ClassPathXmlApplicationContext("beans.xml");

Student st1=(Student)factory.getBean("stud1"); st1.sayHello();


System.out.println("---------------------------"); Student
st2=factory.getBean("stud2",Student.class); st2.sayHello();
System.out.println("---------------------------"); Student
st3=(Student)factory.getBean("stud1"); st3.sayHello();
System.out.println("---------------------------"); Student
st4=(Student)factory.getBean("stud1"); st4.sayHello();
System.out.println("---------------------------"); }
}

package co.edureka;

public class Student { private String name=null;

public Student(){ System.out.println("Inside default constructor"); } public


Student(String name){ this.name=name; System.out.println("Inside parameterized
constructor"); } public String getName(){ System.out.println("Inside getName..");
return this.name; } public void setName(String name){ this.name=name;
System.out.println("Inside setName.."); } public void sayHello()
{ System.out.println("Hello, "+this.name); } public void myInit()
{ System.out.println("Inside user-defined init method"); } public void myDestroy(){
System.out.println("Inside user-defined destruction"); }
}
public 8:07 AM
Sunil (Organizer, Presenter)to Everyone
<?xml version="1.0" encoding="UTF-8"?> <beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="stud1" class="co.edureka.Student" init-method="myInit" destroy-


method="myDestroy"> <property name="name" value="Sunil"></property> </bean> <bean
id="stud2" class="co.edureka.Student" init-method="myInit" destroy-
method="myDestroy"> <constructor-arg value="Joseph"></constructor-arg> </bean>
<bean class="co.edureka.Processor"/>
</beans>

public 8:08 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;

import org.springframework.beans.BeansException; import


org.springframework.beans.factory.config.BeanPostProcessor;

public class Processor implements BeanPostProcessor {

@Override public Object postProcessAfterInitialization(Object arg0, String arg1)


throws BeansException { System.out.println("** After user-defined init method -
"+arg1); return arg0; } @Override public Object
postProcessBeforeInitialization(Object arg0, String arg1) throws BeansException
{ System.out.println("** Before user-defined init method - "+arg1); return arg0; }
}

public 8:08 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;

import org.springframework.context.ConfigurableApplicationContext; import


org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) { ConfigurableApplicationContext context=new


ClassPathXmlApplicationContext("context.xml");
System.out.println("-----------------------------------"); context.close(); }
}

public 8:08 AM

Spring DI - Collections
Apart from setting a single value for a property in XML, it is possible to set the
list of values to a property in XML through collections

List, Map and Set can be used for setting the collection values in XML
<bean> <property name="noSql"> <list> <value>HBase</value> <value>MongoDB</value>
<value>Neo4J</value> </list> </property> </bean>

<list>
<ref bean="ans1"/>
<ref bean="ans2"/>
</list>

<map>
<entry key="101" value="Sunil"></entry>
<entry key="102" value="Mahesh"></entry>
<entry key="102" value="Harsha"></entry>
</map>

<map>
<entry key-ref="answer1" value-ref="user1"></entry>
<entry key-ref="answer2" value-ref="user2"></entry>
</map>

7/25

package co.edureka; public class Edureka { public void method()


{ System.out.println("actual business logic"); } }

public 7:25 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class BeforeAdvisor implements MethodBeforeAdvice { public void


before(Method arg0, Object[] arg1, Object arg2) throws Throwable
{ System.out.println("Before the actual business logic - "+arg0.getName()); } }

public 7:26 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

public class AfterAdvisor implements AfterReturningAdvice{ @Override public void


afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws
Throwable { System.out.println("After the actual business logic -
"+arg1.getName());

}
}

public 7:26 AM
Sunil (Organizer, Presenter)to Everyone
<?xml version="1.0" encoding="UTF-8"?> <beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="edureka" class="co.edureka.Edureka"/> <bean id="ba"


class="co.edureka.BeforeAdvisor"/> <bean id="after"
class="co.edureka.AfterAdvisor"/> <bean id="proxy"
class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target"
ref="edureka"></property> <property name="interceptorNames"> <list>
<value>ba</value> <value>after</value> </list> </property> </bean>
</beans>

public 7:26 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;

import org.springframework.context.ApplicationContext; import


org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) { ApplicationContext context=new


ClassPathXmlApplicationContext("context.xml"); Edureka
edu=context.getBean("proxy",Edureka.class); edu.method(); }
}

Example: Spring-JDBC
Create a DB table in MySQL - Employee Database
mysql> use employee; mysql> create table emp(empno int(5) primary key, ename
varchar(30), sal float(10,2));

Create a Java Project in Eclipse

Convert that Project to Maven based Project

Include spring-context , spring-jdbc, mysql-connector/j dependencies in pom.xml


mvnrepository.com

Create a New Package : co.edureka

Create Employee class to represent in the DB Table Employee.java


package co.edureka;

public class Employee { int empno; String ename; double sal;

public Employee(){}

public Employee(int empno, String ename, double sal) { super(); this.empno = empno;
this.ename = ename; this.sal = sal; }

public int getEmpno() { return empno; }

public void setEmpno(int empno) { this.empno = empno; }

public String getEname() { return ename; }

public void setEname(String ename) { this.ename = ename; }

public double getSal() { return sal; }

public void setSal(double sal) { this.sal = sal

public 8:23 AM
Sunil (Organizer, Presenter)to Everyone
; }

public String toString() { return "Employee - "+empno+"\t"+ename+"\t"+sal; } }

EmployeeDAO.java
package co.edureka;

import org.springframework.jdbc.core.JdbcTemplate;

public class EmployeeDAO { private JdbcTemplate jt;

public JdbcTemplate getJt() { return jt; }

public void setJt(JdbcTemplate jt) { this.jt = jt; }

public void saveEmp(Employee emp) { String sql="insert into emp


values("+emp.getEmpno()+",'"+emp.getEname()+"',"+emp.getSal()+")"; int
n=jt.update(sql); System.out.println("Employee Saved-"+n); }

public void updateEmp(Employee emp) { String sql="update emp set


ename='"+emp.getEname()+"',sal="+emp.getSal()+" where empno="+emp.getEmpno();
int n=jt.update(sql); if(n>0){ System.out.println("Employee Updated"); } }

public void deleteEmp(int n) { String sql="delete from emp where empno="+n; int
x=jt.update(sql); if(x>0) System.out.println("Employee Deleted"); else
System.out.println("No matching employee found"); }

public 8:23 AM
Sunil (Organizer, Presenter)to Everyone
public List<co.edureka.Employee> getEmployees() { String sql="select * from emp";

List<co.edureka.Employee> l=jt.query(sql, new


ResultSetExtractor<java.util.List<Employee>>() { public List<Employee>
extractData(ResultSet rs) throws SQLException,DataAccessException { List<Employee>
list=new ArrayList<Employee>();
while(rs.next()) {
Employee e=new Employee();
e.setEmpno(rs.getInt(1));
e.setEname(rs.getString(2));
e.setSal(rs.getInt(3));
list.add(e);
}
return list;
} }); return l; } }

public 8:23 AM
Sunil (Organizer, Presenter)to Everyone
Create Spring Bean configuration file
applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?> <beans


xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">


<property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property
name="url" value="jdbc:mysql://localhost:3306/employee"/> <property name="username"
value="root"/> <property name="password" value=""/> </bean> <bean id="template"
class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"
ref="ds"/> </bean> <bean id="dao" class="co.edureka.EmployeeDAO"> <property
name="jt" ref="template"/> </bean>
</beans>

Application : Main.java
public 8:24 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;

import java.util.List;

import org.springframework.context.ApplicationContext; import


org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) { ApplicationContext context=new


ClassPathXmlApplicationContext("applicationContext.xml"); EmployeeDAO
dao=context.getBean("dao",EmployeeDAO.class); //Employee emp1=new
Employee(101,"Sunil",222.22); //dao.saveEmp(emp1); //dao.updateEmp(emp1);
//dao.deleteEmp(104); List<co.edureka.Employee> emps=dao.getEmployees();
for(Employee e : emps){ System.out.println(e); } }
}

include earlier code as well


package co.edureka;
import java.util.ArrayList; import java.util.List;

import org.springframework.orm.hibernate4.HibernateTemplate; import


org.springframework.transaction.annotation.Transactional;

public class EmployeeDAO { private HibernateTemplate template;

public HibernateTemplate getTemplate() { return template; } public void


setTemplate(HibernateTemplate template) { this.template = template; }
@Transactional(readOnly = false) public void saveEmployee(Employee e)
{ template.save(e); } @Transactional(readOnly = false) public void
updateEmployee(Employee e){ template.update(e); } @Transactional(readOnly = false)
public void deleteEmployee(Employee e){ template.delete(e); }
public 8:52 AM
Sunil (Organizer, Presenter)to Everyone
public Employee getById(int id){
Employee e=(Employee)template.get(Employee.class,id);
return e;
}

public List<Employee> getEmployees(){ List<Employee> list=new


ArrayList<Employee>(); list=template.loadAll(Employee.class); return list; }
}

public 8:53 AM
Sunil (Organizer, Presenter)to Everyone
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="co.edureka.Employee" table="emp">
<id name="empno" column="empno">
<generator class="assigned"></generator>
</id>
<property name="ename" column="ename"></property>
<property name="sal" column="sal"></property>
</class>
</hibernate-mapping>

public 8:53 AM
Sunil (Organizer, Presenter)to Everyone
<?xml version="1.0" encoding="UTF-8"?> <beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">

context:annotation-config/
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value

public 8:53 AM
Sunil (Organizer, Presenter)to Everyone
="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:XE" />
<property name="username" value="java27" />
<property name="password" value="java27" />
</bean>

<bean id="mysessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>employee.hbm.xml</value>
</list>
</property>

<property name="hibernateProperties"> <props> <prop


key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> <prop
key="hibernate.hbm2ddl.auto">update</prop> <prop
key="hibernate.show_sql">true</prop> </props> </property>
</bean>

public 8:53 AM
Sunil (Organizer, Presenter)to Everyone
<bean id="template" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>

<bean id="empdao" class="co.edureka.EmployeeDAO">


<property name="template" ref="template"></property>
</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>

<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property
name="sessionFactory" ref="mysessionFactory"/> </bean> </beans>

public 8:53 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;

import org.springframework.context.ApplicationContext; import


org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) { ApplicationContext context=new


ClassPathXmlApplicationContext("context.xml"); EmployeeDAO
dao=context.getBean("empdao",EmployeeDAO.class); Employee emp=new
Employee(101,"edureka",123.45); dao.saveEmployee(emp); }
}
7/28

Using Jersey-2 in Eclipse


Create a Maven Project in Eclipse change the Prespective to Java EE Integrate
Tomcat Server
File > New > Maven Project

Next Select "org.apache.maven.archetypes" maven-archetype-webapp Next Group Id:


co.edureka Artifact Id : REST2 Finish
In pom.xml - add the additional dependencies for Servlet and Jersey 2.x
mvnrepository.com > Search for "Jersey Container Servlet" & "servlet"

<dependencies> <dependency> <groupId>javax.servlet</groupId>


<artifactId>javax.servlet-api</artifactId> <version>3.1.0</version>
<scope>provided</scope> </dependency>

<dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-


container-servlet</artifactId> <version>2.23</version> </dependency>
</dependencies>

public 7:26 AM
Sunil (Organizer, Presenter)to Everyone
webapp/WEB-INF/web.xml <web-app> <servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>co.edureka</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>

Create a folder with name "java" inside src/main Java Resources > src/main/java

Create a Package with name : co.edureka

Create a Java class in co.edureka package with name : CustomerService


CustomerService.java

public 7:27 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;
import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@Path("/customers") public class CustomerService { @GET @Produces("text/html")


public Response method1() { String output = "<h1>Local Customer Service
Center</h1>"; return Response.status(200).entity(output).build(); }

@GET @Path("/nri") @Produces("text/html") public Response method2() { String output


= "<h1>NRI Customer Service Center</h1>"; return
Response.status(200).entity(output).build(); } }

public 7:27 AM
Sunil (Organizer, Presenter)to Everyone
Run As > Run on Server

In Browser http://localhost:65535/REST2/rest/customers
http://localhost:65535/REST2/rest/customers/nri

If Required:

Right click on Project Node > Run As > Maven Build > Goal : clean install
If any error : Eclipse > Window > Preferences > Java > Installed JREs : (Include
JDK Path)

Eclipse > Window > Preferences > Maven > Java EE Integration : Uncheck "Maven
Archiver generates files under the build directory

@PathParam
@GET @Path("{name}/{country}") @Produces("text/html") public Response
method3(@PathParam("name") String name, @PathParam("country") String country) {
String output = "<h1>Customer name - "+name+"<br> Country - "+country+"</h1>";
return Response.status(200).entity(output).build(); }

http://localhost:65534/REST2/rest/customers/Sunil/India

@QueryParam
@GET @Produces("text/html") public Response method4(@QueryParam("name") String
name, @QueryParam("country") String country) { String output = "<h1>Customer name -
"+name+"<br> Country - "+country+""; return
Response.status(200).entity(output).build(); }

http://localhost:65534/REST2/rest/customers?name=Sunil&country=India
index.jsp
<html> <head> <style> body{ background-color:#936; color:white }
table{ width:600px; background-color:maroon; font-size:20px; font-family:verdana;
border-radius:10px; padding:10px } tr{ height:45px; } </style> </head> <body> <form
action="rest/customers/addCustomer" method="post"> <table> <tr> <td>Customer
Name :</td> <td><input type="text" name="cname" size="30" autofocus required
placeholder="enter customer name"/> </td> </tr>
<tr> <td>Customer Address : </td> <td> <input type="text" name="caddress" size="30"
/> </td> </tr>
<tr> <td></td> <td><input type="submit" value="Add Customer" /> </td> </tr>
</table>
</form> </body> </html>

@POST @Path("/addCustomer") @Produces("text/html") public Response


add(@FormParam("cname") String name,@FormParam("caddress") String address){ String
output = "<h1>Customer information is saved with <br> Customer Name -
<u>"+name+"</u><br> and Address - <u>"+address+"</u></h1>"; return
Response.status(200).entity(output).build(); }

creating xml using eclipse


import java.io.FileOutputStream; import javax.xml.parsers.DocumentBuilder; import
javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory; import
javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text;

public class CreateXML { public static void main(String[] args) throws Exception
{ DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder parser=factory.newDocumentBuilder(); Document
doc=parser.newDocument();

Element root=doc.createElement("students"); doc.appendChild(root);

Element stud=doc.createElement("student"); root.appendChild(stud);


stud.setAttribute("sid","101");

public 8:31 AM
Sunil (Organizer, Presenter)to Everyone
Element name=doc.createElement("name"); Text namedata=doc.createTextNode("Sunil
Joseph"); name.appendChild(namedata); stud.appendChild(name);

Element age=doc.createElement("age"); Text agedata=doc.createTextNode("35");


age.appendChild(agedata); stud.appendChild(age);

TransformerFactory tfactory=TransformerFactory.newInstance(); Transformer


t=tfactory.newTransformer();

FileOutputStream fos=new FileOutputStream("D:/students.xml");


t.transform(new DOMSource(doc),new StreamResult(fos)); System.out.println("XML file
generated.."); } }