Documente Academic
Documente Profesional
Documente Cultură
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); */
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 {
import java.sql.*;
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;
public 9:04 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka.jdbc;
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(); }
}
07/14
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");
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>
public 8:42 AM
javaconnector in lib
classes in classes
web.xml in wen-inf
07/17
public 9:10 AM
Sunil (Organizer, Presenter)to Everyone
import java.io.; import javax.servlet.; import javax.servlet.http.*;
9019117772
jdbc vs dao
07/19
JSTL
The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP
development
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
2.jsp
public 8:04 AM
Sunil (Organizer, Presenter)to Everyone
3.jsp
5.jsp
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
public 8:04 AM
Sunil (Organizer, Presenter)to Everyone
7.jsp
8.jsp
9.jsp
10.jsp
11.jsp
<%@taglib uri="http://java.sun.com/jstl/sql_rt" prefix="sql" %> <%@taglib
uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
07/20
package co.edureka;
public class Student { private Integer studid; private String sname, email, mobile;
public Student(){}
<hibernate-mapping>
<property name="mobile"/>
</class>
</hibernate-mapping>
<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="hibernate.dialect">
org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
package co.edureka;
package co.edureka;
import java.util.Scanner;
package co.edureka;
/*package co.edureka;
package co.edureka;
package co.edureka;
package co.edureka;
import java.util.List;
package co.edureka;
import java.util.List;
package co.edureka;
import java.util.List;
7/21
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
batch.hbm.xml
Inside hibernate.cfg.xml
Relations.java
package co.edureka;
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.
public 8:09 AM
<property name="hbm2ddl.auto">update</property>
public 8:21 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;
public 8:21 AM
Sunil (Organizer, Presenter)to Everyone
<mapping class="co.edureka.Employee" />
public 8:22 AM
7/24
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">
public 7:34 AM
Sunil (Organizer, Presenter)to Everyone
import org.springframework.beans.factory.BeanFactory; import
org.springframework.context.support.ClassPathXmlApplicationContext;
package co.edureka;
public 8:08 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;
public 8:08 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;
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
public 7:25 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public 7:26 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
}
}
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">
public 7:26 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;
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));
public Employee(){}
public Employee(int empno, String ename, double sal) { super(); this.empno = empno;
this.ename = ename; this.sal = sal; }
public 8:23 AM
Sunil (Organizer, Presenter)to Everyone
; }
EmployeeDAO.java
package co.edureka;
import org.springframework.jdbc.core.JdbcTemplate;
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";
public 8:23 AM
Sunil (Organizer, Presenter)to Everyone
Create Spring Bean configuration file
applicationContext.xml
Application : Main.java
public 8:24 AM
Sunil (Organizer, Presenter)to Everyone
package co.edureka;
import java.util.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>
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>
<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;
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
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;
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>
public class CreateXML { public static void main(String[] args) throws Exception
{ DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder parser=factory.newDocumentBuilder(); Document
doc=parser.newDocument();
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);