- Create a Java class called Product with the following properties: name, description,price. Create a listener that notifies (through System.out) whenever a user adds aproduct to a shopping cart (i.e. adds an object to the session object) or removes itagain. Hint: check out the class HttpSessionAttributeListener. Make it print the name and price of the object (hint: access the session through the HttpBindingEventobject). Also, let the listener print the total price of all objects saved in the session sofar (one way to accomplish this could be to keep a collection of all objects saved to the session – or just their keys – in the listener or an associated class).
File 1
--------
package model;
public class Product
{
public String name;
public String descr;
public float price;
public Product(String name,String descr,float price)
{
this.name=name;
this.descr=descr;
this.price=price;
}
}
File 2
-------
package web;
import javax.servlet.*;
import javax.servlet.http.*;
import model.*;
public class SessionListenerImplementationDemo implements HttpSessionAttributeListener
{
public void attributeAdded(HttpSessionBindingEvent sbEvent)
{
HttpSession mySession=sbEvent.getSession();
String attribName=sbEvent.getName();
Product p=(Product)sbEvent.getValue();
String attribVal=(String)sbEvent.getValue();
System.out.println("Attribute with attribute name "+attribName+" is added to session and value is"+attribVal);
System.out.println("Product Details added to the session");
System.out.println("Name: "+p.name);
System.out.println("Price:"+p.price);
}
public void attributeRemoved(HttpSessionBindingEvent sbEvent)
{
HttpSession mySession=sbEvent.getSession();
String attribName=sbEvent.getName();
Product p=(Product)sbEvent.getValue();
String attribVal=(String)sbEvent.getValue();
System.out.println("Attribute with attribute name "+attribName+" is removed from session and value is"+attribVal);
System.out.println("Detail of Product Removed from the session");
System.out.println("Name: "+p.name);
System.out.println("Price:"+p.price);
}
public void attributeReplaced(HttpSessionBindingEvent sbEvent)
{
}
}
File 3
-------
package web;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import model.*;
public class ServletEx21 extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
HttpSession mySession=req.getSession();
out.println("<html><body>");
try
{
Product p1=new Product("Corbey","Nice handset",6200);
Product p2=new Product("Galaxy","It has anroid os",12000);
Product p3=new Product("Champ","Good sound quality",4500);
mySession.setAttribute("Cell_1","Corbey");
mySession.setAttribute("Cell_2","Galaxy");
mySession.setAttribute("Cell_3","Champ");
mySession.removeAttribute("Cell_3");
// out.println("Hello World");
out.println("Session activity are tracked by this server.Check console or catalina folder");
}
catch(Exception e)
{
out.println(e);
}
out.println("Hello Test");
out.println("</body></html>");
}
}
Web.xml
---------
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>MyServletGetTracked</servlet-name>
<servlet-class>web.ServletEx21</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServletGetTracked</servlet-name>
<url-pattern>/Ex21</url-pattern>
</servlet-mapping>
<listener>
<description>sessionListener</description>
<listener-class>web.SessionListenerImplementationDemo</listener-class>
</listener></web-app> - Create a servlet filter that logs all access to and from servlets in an application and prints the following to System.out:
a. the time the request was received
b. the time the response was sent
c. how much time it took to process the request
d. the URL of the resource requested
e. the IP address of the visitor.import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class filterDemo implements Filter
{
String rs;
Date reqd;
Date resd;
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
String ip;
ServletContext context;
FilterConfig config;
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws ServletException,IOException
{
resd=new Date();
calendar1.set(reqd.getYear(),reqd.getMonth(),reqd.getDate());
calendar2.set(resd.getYear(),resd.getMonth(),resd.getDate());
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
Date ddate=new Date(diff);
HttpServletRequest req=(HttpServletRequest)request;
context.log("IP:--"+req.getRemoteAddr()+"---" +req.getRequestURL()+" request time::-"+reqd.toString()+" Response Time::-"+resd.toString()+"diff"+ddate.toString());
chain.doFilter(request,response);
}
public void init(FilterConfig config)
{
reqd=new Date();
this.config=config;
context=config.getServletContext();
}
public void destroy()
{
}
}
WEB.XML File::
--------------
<web-app>
<servlet>
<servlet-name>calculate</servlet-name>
<servlet-class>calculate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>calculate</servlet-name>
<url-pattern>/calculate</url-pattern>
</servlet-mapping>
<filter>
<filter-name>filterDemo</filter-name>
<filter-class>filterDemo</filter-class>
</filter>
<filter-mapping>
<filter-name>filterDemo</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> - Devlop a interest Calculation application in which user will provide all information in HTML form and that will be processed by servlet and response will be generated back to the user.
SERVLET ::
------------
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
class simpleinterest extends HttpServlet
{
int p,r,n;
float si;
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
p=Integer.parseInt(req.getParameter("txtp"));
r=Integer.parseInt(req.getParameter("txtr"));
n=Integer.parseInt(req.getParameter("txtt"));
si=(float)((p*r*n)/100);
String value=String.valueOf(si);
Cookie c = new Cookie("Simple Interest",value);
res.addCookie(c);
res.sendRedirect("http://localhost:8080/WTAD/jspfiles/simint.jsp");
}
}
HTML FILE ::
--------------
<!-- html form which get interest calcuation's Information -->
<html>
<head>
<title> SIMPLE INTEREST </title>
</head>
<body>
<form name="frmsi" action="http://localhost:8080/WTAD/simpleinterest" method="post">
<center><br>
Input Principle Amount :: <input type="text" name="txtp" value="input no only"><br>
Input Rate in persentage :: <input type="text" name="txtr" value="input no only"><br>
Input Time :: <input type="text" name="txtt" value="input no only"><br><br>
<script language="javascript">
var results = document.cookie.match ( '(^|;) ?' + "Simple Interest + '=([^;]*)(;|$)' ); if ( results )
document.writeln( unescape ( results[2] ) );
</script>
<input type="submit" name="cmdsi" value="CALCULATE">
<input type="reset" name="cmdrs" value="CLEAR">
</center>
</form>
</body>
</html> - Develop an application to demonstrate how the client (browser) can remember the last time it visited a page and displays the duration of time since its last visit. (Hint: use Cookie).
File 1
---------
<html>
<head>
<title>Ex24</title>
<script language="javascript">
function validate()
{
if(document.getElementById(1).value=="")
{
alert("Please insert username");
return false;
}
if(document.getElementById(2).value=="")
{
alert("Please insert password");
return false;
}
return true;
}
</script>
</head>
<body>
<br>
<h1>FACEBOOK</h1>
<hr>
<table border=1 align="right" hspace="20%">
<tr><td>
<form action="setTimeCookie.jsp" method="post" onSubmit="return validate();">
<table width=100%>
<tr>
<th colspan=2>Log in to FB<th>
</tr>
<tr>
<td>Username</td>
<td><input type="text" name="uname" id=1></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" id=2></td>
<tr>
<td colspan=2 align="Center"><input type="Submit" value="Submit"></td>
</tr>
</table>
</form>
</tr></td></table>
</body>
</html>
FILE 2:
--------
<html>
<head>
<title>
<title>
</head>
<body>
<%@page import="java.util.Date"%>
<%@page import="java.sql.*"%>
<%
String uname=request.getParameter("uname");
String pwd=request.getParameter("password");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("JDBC:ODBC:DATASOURCE");
Statement st=con.createStatement();
st.executeQuery("Select* from user");
ResultSet rs=st.getResultSet();
boolean found=false;
if(rs!=null)
{
while(rs.next())
{
if(uname.equals(rs.getString("username")) && pwd.equals(rs.getString("password")))
{
found=true;
Date now = new Date();
String timeStamp = now.toString();
Cookie cookies[]=request.getCookies();
String cookie1="username";
String cookie2="lastTime";
Cookie unameCookie=null;
Cookie timeCookie=null;
if(cookies!=null)
{
for(int i=0;i<cookies.length;i++)
{
if(cookies[i].getName().equals(cookie1))
{
unameCookie=cookies[i];
}
if(cookies[i].getName().equals(cookie2))
{
timeCookie=cookies[i];
}
}
}
%><h1><%="Welcome.."+uname%>
<br><%
if(timeCookie!=null && unameCookie!=null)
{
if(unameCookie.getValue().equals(uname))
{
%><%="Last time you had visited this site on "+timeCookie.getValue()+"."%>
<%
}
else
{
%>
<%="This is your first visit to our site"%>
<%
}
}
unameCookie=new Cookie("username",uname);
timeCookie=new Cookie("lastTime",timeStamp);
response.addCookie(unameCookie);
response.addCookie(timeCookie);
}
}
if(!found)
{
%><h1><%="Invalid username and/or password"%></h1>
<%
}
}
}
catch(Exception e)
{
%> <%=e%>
<%
}
%>
</body>
</html> - Develop An application to write a “page – composite” JSP that includes other pages or passes control to another page.
<!-- Write A JSP Page, which uses the include directive to show its header and footer -->
<html>
<head>
<title> </title>
</head>
<body>
<table border="1" align="center" cellpadding="0"cellspacing="0">
<tr>
<td align="center" id="header">
<jsp:include page="header.jsp"/>
</td>
</tr>
<tr height="500">
<td>
<script language="javascript">
var n1=parseInt(prompt("Input anyInteger no to N1:"));
var n2=parseInt(prompt("Input anyInteger No to N2:"));
if(n1>n2)
{
<jsp:forward page="small.jsp"/>
}
else
{
<jsp:forward page="small.jsp"/>
}
</script>
</td>
</tr>
<tr>
<td align="right" id="footer">
<jsp:include page="footer.jsp"/>
</td>
</tr>
</table>
</body>
</html> - You want to reduce the amount of java coding in your JSP Using Java Bean component.
STRINGBEAN.JAVA
----------------
public class StringBean
{
private String message="No message";
public String getMessage()
{
return(message);
}
public void setMessage(String m)
{
this.message=m;
}
}
STRINGBEANEXAMPLE.JSP
-----------------------
<html>
<head>
<title>Using JavaBean With JSP</title>
</head>
<body>
<center>
<table border=2>
<tr>
<th>Using JavaBean With JSP</th>
</tr>
</table>
</center>
<jsp:useBean id="strbean" class="StringBean" />
<ol>
<li>Initial Value :: <jsp:getProperty name="strbean" property="message" /></li>
<li><jsp:setProperty name="strbean" property="message" value="hello" />value after seeting value from jsp:<jsp:getProperty name="strbean" property="message" /></li>
</ol>
</body>
</html> - Develop a program to perform the database driven operation like insert, Delete,
Update and select. To perform the above operations create one table named
Employee.
Field Name Field Type
EmpId Integer
Empname Varchar
Emp_desig Varchar
Emp_J_Date Varchar
Emp_Salary Numericimport java.sql.*;
class Ex28
{
public static Connection con=null;
public static Statement s=null;
public static ResultSet rs=null;
public static ResultSetMetaData rsmdt=null;
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/emp","root","");
s=con.createStatement();
displayAllRecord();
System.out.println("Inserting one new Record...");
insertRecord();
System.out.println("After insert....");
displayAllRecord();
System.out.println("Deleting one record....");
deleteRecord(4);
System.out.println("After delete....");
displayAllRecord();
System.out.println("Updating one record..");
updateRecord(3);
System.out.println("After update....");
displayAllRecord();
rs.close();
s.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void displayAllRecord()
{
try
{
rs=s.executeQuery("Select * from employee");
rsmdt=rs.getMetaData();
System.out.println(rsmdt.getColumnCount());
for(int i=1;i<rsmdt.getColumnCount();i++)
{
System.out.print(rsmdt.getColumnName(i)+"||");
}
System.out.println();
System.out.println("==================================================================");
while(rs.next())
{
System.out.println();
System.out.print(rs.getString(1)+" || ");
System.out.print(rs.getString(2)+" || ");
System.out.print(rs.getString(3)+" || ");
System.out.print(rs.getString(4)+" || ");
System.out.print(rs.getString(5)+" || ");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void insertRecord()
{
try
{
String query="INSERT INTO `employee` ( `empid` , `empname` , `emp_desig` , `emp_j_dare` , `emp_salary` )VALUES ('7', 'dextors', 'Assistant Progremer', '12/6/2012', '45000')";
s.executeUpdate(query);
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void deleteRecord(int empid)
{
try
{
String query="DELETE FROM `employee` WHERE `empid`="+empid;
s.executeUpdate(query);
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void updateRecord(int empid)
{
try
{
String query="UPDATE `employee` SET `empname` = ‘MultiDextors',`emp_salary` = '51200' WHERE `empid` ="+empid;
s.executeUpdate(query);
}
catch(Exception e)
{
System.out.println(e);
}
}
} - Develop a Java application to perform the database driven operation like insert, Delete, Update and selection using PreparedStatement. To perform the above operations use the table from exercise 28.
import java.sql.*;
class Ex29
{
public static Connection con=null;
public static PreparedStatement ps=null;
public static ResultSet rs=null;
public static ResultSetMetaData rsmdt=null;
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/emp","root","");
displayAllRecord();
System.out.println("Inserting one new Record...");
insertRecord();
System.out.println("After insert....");
displayAllRecord();
System.out.println("Deleting one record....");
deleteRecord(4);
System.out.println("After delete....");
displayAllRecord();
System.out.println("Updating one record..");
updateRecord(3);
System.out.println("After update....");
displayAllRecord();
rs.close();
ps.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void displayAllRecord()
{
try
{
String query="Select * from employee";
ps=con.prepareStatement(query);
rs=ps.executeQuery();
rsmdt=rs.getMetaData();
//System.out.println(rsmdt.getColumnCount());
for(int i=1;i<rsmdt.getColumnCount();i++)
{
System.out.print(rsmdt.getColumnName(i)+"||");
}
System.out.println();
System.out.println("==================================================================");
while(rs.next())
{
System.out.println();
System.out.print(rs.getString(1)+" || ");
System.out.print(rs.getString(2)+" || ");
System.out.print(rs.getString(3)+" || ");
System.out.print(rs.getString(4)+" || ");
System.out.print(rs.getString(5)+" || ");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void insertRecord()
{
try
{
String query="INSERT INTO `employee` ( `empid` , `empname` , `emp_desig` , `emp_j_dare` , `emp_salary` )VALUES ('4', 'Manish Prajapati', 'Assistant Progremer', '12/6/2012', '45000')";
ps=con.prepareStatement(query);
ps.executeUpdate();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void deleteRecord(int empid)
{
try
{
String query="DELETE FROM `employee` WHERE `empid`= ? ";
ps=con.prepareStatement(query);
ps.setInt(1,empid);
ps.execute();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void updateRecord(int empid)
{
try
{
String query="UPDATE `employee` SET `empname` = ?,`emp_salary` = ? WHERE `empid` =?";
ps=con.prepareStatement(query);
ps.setString(1,"Raj Aryan");
ps.setFloat(2,250000);
ps.setInt(3,empid);
ps.execute();
}
catch(Exception e)
{
System.out.println(e);
}
}
} - Write a Java application to invoke a stored procedure using a CallableStatement. For this a stored procedure called incrementSalary may be developed to increase all the employees salary by a percentage specified in the parameter.
Code of Stored procedure.
-----------------------------------------------------------------------------------------
Run this on oracle or mysql
---------------------------------------------------------------
CREATE PROCEDURE salIncr(IN per INT)
BEGIN
update employee set emp_salary=emp_salary+emp_salary*per/100;
END
//
-----------------------------------------------------------------
One more imp note:
In mysql you can not use one connection obejct to create multiple objects of different types
of statement like callable,prepared.(code doesn’t work with single con that’s why telling so..not sure about it ).now what happens with oracle i don't know. Test it over oracle and give
feed back here. I think it will allow.*/
import java.sql.*;
public class Ex30
{
public static Connection con=null;
public static CallableStatement cbs=null;
public static ResultSet rs=null;
public static Statement s=null;
public static ResultSetMetaData rsmdt=null;
public static void main(String args[])
{
try
{
/* Code with xamp mysql server
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/emp","root","");
*/
//Code with full mysql server.
Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/emp";
Connection con = DriverManager.getConnection(url,"root","123456");
String query="call salIncr(20)";
cbs=con.prepareCall(query);
cbs.executeQuery();
cbs.close();
System.out.println("After execution of stored procedure");
displayAllRecord();
rs.close();
s.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void displayAllRecord()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/emp";
Connection con1 = DriverManager.getConnection(url,"root","123456");
s=con1.createStatement();
rs=s.executeQuery("Select * from employee");
rsmdt=rs.getMetaData();
System.out.println(rsmdt.getColumnCount());
for(int i=1;i<rsmdt.getColumnCount();i++)
{
System.out.print(rsmdt.getColumnName(i)+"||");
}
System.out.println();
System.out.println("==============================================");
while(rs.next())
{
System.out.println();
System.out.print(rs.getString(1)+" || ");
System.out.print(rs.getString(2)+" || ");
System.out.print(rs.getString(3)+" || ");
System.out.print(rs.getString(4)+" || ");
System.out.print(rs.getString(5)+" || ");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
BACK | NEXT |
Prepared By:
Student of B. H. Gardi College of Eng. & Tech., MCA Department
(Nisarg Juthani, Kajal Savjani, Desai Paresh, Ramoliya Nilesh, Thanki Ravi.....)
No comments:
Post a Comment