Sie sind auf Seite 1von 19

MCS-051 solved assignment july

2017 - january 2018 session


MCS-051

Q 1: Write a MDB (Message Driven Bean) for news agency that has to capture the data
from various news sources. The newly written MDB should accept the XML format of
the news. The XML data needs to be parsed and stored in the database. The news format
is as follows:

<news_id> </ news_id>

<sources> </source>

<date> </date>

<type_of_news> </type_of_news>
o m
<priority> <priority>

o t .c
<news_content> </news_content>
s p
lo g
. b
Solution :

s i te
o u
<%@page contentType="text/html; charset=iso-8859-1" language="java"
import="java.sql.*" errorPage=""%>

ig n
.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

w
"http://www.w3.org/TR/html4/loose.dtd">
w
w
<html >

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Untitled Document</title>

<style type="text/css">

<!--

.style1 { font-family:"Times New Roman", Times, serif; color: #99CC00;}


.style2 { font-family:"Times New Roman", Times, serif; color: #99CC00; }

.style3 { color: #FFFFFF;}

.style4 { font-size:14px; color: #0099FF; }

.style5 { color: #0099FF;}

.style6 { font-size:14px; color: #00CCFF;}

.style7 { color: #00CCFF; }

body { background-color:#FFFFFF;}

</style>

</head>

<body>
o m
<h1 class="style1">Daily News</h1>

o t .c
<form name="form1" method="post" action="">
s p
<span class="style2">News Id.:</span>
lo g
. b
te
<input type="text" name="textfield">

</form>
s i
o u
<form name="form2" method="post" action="">

ig n
w .
<p><span class="style4">Source:</span><span class="style5"></span><span
class="style3">aa</span>

w w
<input type="text" name="textfield3">

</p>

<p><span class="style5">Date:<span
class="style3">:</span></span><span class="style3">aaaa</span>

<input type="text" name="textfield2">

</p>
</form>

<form name="form3" method="post" action="">

<span class="style6">Type of news</span>

<input type="text" name="textfield4">

</form>

<form name="form4" method="post" action="">

<p class="style7">News content</p>

<p>

<textarea name="textarea" rows="4"></textarea>

</p>
o m
</form>

o t .c
<p>&nbps;</p>
s p
</body>
</html>
lo g
. b
s i te
2. Write and run Servlet code to fetch and display all the fields of a student table stored in
an Oracle database with attributes: (students id, student-name, student - address,
program, semester )

o u
Answer :-

ig n
w .
import javax.servlet.http.*;
import javax.servlet.*;

w w
import java.io.*;
import java.sql.*;
import javax.sql.*;

public class FatehRecordServlet extends


HttpServlet {
int p;
Integer page_no;
static String ta-
ble;
public void service(HttpServletRequest req, HttpServletResponse res)throws
ServletException,IOException

{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html><body>");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection c=DriverManager.getConnection("jdbc:oracle:thin:@localhost:
1521:xe","dbuser","dbpassword") ;
Statement st=c.createStatement();
String s="select *from student";
ResultSet r=st.executeQuery(s);
out.println("<html><body>"); out.println("<table
bgcolor='yellow' border='1'>");
o m
while(r.next())
{
o t.c
s
out.println("<tr>"); out.println("<td>"+r.getString(students_id)
p
+"</td>");

lo g
out.println("<td>"+r.getString(studentstudent_name)+"</

. b
td>"); out.println("<td>"+r.getString(student_address)+"</

te
td>"); out.println("<td>"+r.getString(program)+"</td>");

out.println("</tr>");
s i
out.println("<td>"+r.getString(semester)+"</td>");

}
o u
ig n
out.println("</table>");
out.println("</body></html>");

}
w .
w { w
catch (Exception ex)

out.println(ex);
}
}
}

3. Write an application to create a XML document from an employee database stored


in an Oracle database. The XML document should contain the following fields:
(employee-id, employee-name, employee-address, employee-email,employee-sex, age and
the last twelve month salary summary).

Answer:- cus-
tomer.xml file :-

<?xml version="1.0" ?>


<?xml version="1.0" encoding="ISO-8859-1" ?>
<!-- customer - customer.xml
-->
<!-- Storing the customer details in XML document
-->
<employee>
<employee-id>101</employee-id> <employee-name>Ramesh</employee-
name> <employee-address>Sector-31 Noida</employee-address>
<employee-email>emp101@gmail.com</employee-email> <employee-
o m
sex>Male</employee-sex>
<age>25</age>
o t .c
<salary-summary>the last twelve month salary summary</salary-summary>
</ employee >
s p
lo g
4. Suppose there is a table named as product in Oracle database with attributes as : prod-

. b
uct id, product name, product quality, product price, model and its description . Write

s i te
JAVA program to insert, delete and display records of the table using JDBC.

import java.sql.*; class


o u
CURDOperation {

ig n
w .
/*CURD
C- create

w w U-update
R-retrive
D-delete
*/

public static void main(String[] args)


{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
c=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","dbuser","dbpassword")
;
Statement st=c.createStatement();
//create table
st.executeUpdate("create table product (product_id varchar(20),product_name
varchar(20), product_quality varchar(20),product_quality varchar(20),product_price
varchar(20),model_desc varchar(200))");
//insert record
st.executeUpdate("insert into product values('101','oracle','stand','25000','enterprise
version with description')");
//insert record 2
st.executeUpdate("insert into product values('102','oracle1','stand1','125000','enterprise
1.2 version with description')");
//delete record
st.executeUpdate("delete product where product_id='102'");
Statement s=c.createStatement();

m
ResultSet r=s.executeQuery("select *from product");
while(r.next())
{
.c o
// retrive all record form prodcut table and display to console
o t
p
System.out.println(r.getString(1)+"\n "+r.getString(2)+" \n "+r.getString(3)+" \n
"+r.getString(4)+" \n "+r.getString(5));
}
g s
}
catch(Exception e)
. b lo
te
{
System.out.println(e);
s i
}
}
o u
}

ig n
w .
5. Describe with suitable program segment how to include file and applets in a JSP page.

w w
Answer :-

index.jsp file :-

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Mouse Drag</title>
</head>
<body bgcolor="khaki">
<h1>Mouse Drag Example</h1>
<jsp:plugin align="middle" height="500" width="500" type="applet"
code="MouseDrag.class"
name="clock" codebase="."/>
</body>
</html>

MouseDrag Applet class

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{

public void init(){


addMouseMotionListener(this);
o m
setBackground(Color.red);
}
o t .c
public void mouseDragged(MouseEvent me)
s p
{ Graphics g=getGraphics();
g.setColor(Color.white);
lo g
g.fillOval(me.getX(),me.getY(),20,20);
. b
}

s i
public void mouseMoved(MouseEvent me) te
{}

o u
}

ig n
w .
w w
6. Write a web based student registration application where the students can register on-
line with their enrollment numbers. The registered students should be able to login on
after getting registered. You are required to use JSP, Servelet and JDBC.

Index.html

<html>
<head>
<title>registration</title>
</head>
<body>
<form method="post" action="reg">
NAME:<input type="text"name="t1"/><br>
ENROLLMENT:<input type="text"name="t2"/><br>
PASSWORD:<input type="password"name="t3"/><br>
<input type="submit"value="send"/><br>
</form>
<a href='login.html'>if already registered plz login</a>
</body>
</html>

login.html

<html>
<head>
<title>login</title>
</head>
<body>

o m
.c
<form method="post" action="login">
<h2>ENTER VALID USER NAME AND PASSWORD</h2>
<p><strong>USER NAME:</strong>
o t
<input type="text"name="t1"/><br>
sp
<strong>PASSWORD:</strong>
<input type="password"name="t2"/><br>
lo g
<input type="submit"value="Login"/><br>
</p>
. b
</form>

s i te
<a href='index.html'>new user create account</a>
</body>
o u
n
</html>

w
web.xml . ig
w w
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>regform</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/reg</url-pattern>
</servlet-mapping>

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

regform.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class regform extends HttpServlet{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException{
res.setContentType("text/html");

o m
.c
PrintWriter out=res.getWriter();
String n=req.getParameter("t1");
String e=req.getParameter("t2");
o t
String p=req.getParameter("t3");
s p
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
lo g
. b
Connection con=DriverManager.getConnection("jdbc:odbc:school");
PreparedStatement st=con.prepareStatement("insert into student values(?,?,?)");
st.clearParameters();
st.setString(1,n);
s i te
u
st.setInt(2,Integer.parseInt(e));
o
n
st.setString(3,p);

ig
st.executeUpdate();

.
con.close();

w
w}
w
}catch(Exception ex){
ex.printStackTrace(System.out);

out.write("ur account has been created, <a href='login.html'>u can login now</a>");

}
}

login.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class login extends HttpServlet{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String n=req.getParameter("t1");
String p=req.getParameter("t2");

try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:school");
PreparedStatement st=con.prepareStatement("select * from student where name=? and
pass=?");
st.clearParameters();
st.setString(1,n);
st.setString(2,p);
ResultSet rs=st.executeQuery();
o m
.c
boolean b=rs.next();
if(b==true){
out.write("WELCOME");
o t
s p
}
else{
lo g
b
out.write("Login failed <a href='login.html'>TRY AGAIN</a>");

.
}
con.close();
s i te
o u
ig n
}catch(Exception ex){
ex.printStackTrace(System.out);

}
}

w .
}

w w
7. Explain the difference between Session and Cookie.
Answer :-

Cookies are used to identify sessions. Visit any site that is using cookies and pull up either
Chrome inspect element and then network or FireBug if using Firefox.
You can see that there is a header sent to a server and also received called Cookie. Usually it
contains some personal information (like an ID) that can be used on the server to identify a
session. These cookies stay on your computer and your browser takes care of sending them to
only the domains that are identified with it.

If there were no cookies then you would be sending a unique ID on every request via GET or
POST. Cookies are like static id's that stay on your computer for some time.
A session is a group of information on the server that is associated with the cookie information.
If you're using PHP you can check the session.save_path location and actually "see sessions".
They are either files on the server filesystem or backed in a database.

Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.

8. What are the different components to be used while writing SSL client application ?
Discuss. Write sample codes for SSL client and SSL Client Servelet and explain it.

Answer:-
o m
Secure Sockets Layer (SSL)

o t .c
s p
The Secure Sockets Layer protocol, or SSL, sits between the application-level protocol (in this
case HTTP) and the low-level transport protocol (for the Internet, almost exclusively TCP/IP). It

lo g
handles the details of security management using public key cryptography to encrypt all
client/server communication. SSL was introduced by Netscape with Netscape Navigator 1. It has

. b
since become the de facto standard for secure online communications and forms the basis of the

i te
Transport Layer Security (TLS) protocol currently under development by the Internet

s
Engineering Task Force. SSL Version 2.0, the version first to gain widespread acceptance,

o u
includes support for server certificates only. It provides authentication of the server,
confidentiality, and integrity. Here's how it works:

ig n
w .
1. A user connects to a secure site using the HTTPS (HTTP plus SSL) protocol. (You can
detect sites using the HTTPS protocol because their URLs begin with https: instead of

w w http:.)
2. The server signs its public key with its private key and sends it back to the browser.
3. The browser uses the server's public key to verify that the same person who signed the
key actually owns it.
4. The browser checks to see whether a trusted certificate authority signed the key. If one
didn't, the browser asks the user if the key can be trusted and proceeds as directed.
5. The client generates a symmetric ( DES) key for the session, which is encrypted with the
server's public key and sent back to the server. This new key is used to encrypt all
subsequent transactions. The symmetric key is used because of the high computational
cost of public key cryptosystems.

All this is completely transparent to servlets and servlet developers. You just need to obtain an
appropriate server certificate, install it, and configure your server appropriately. Information
transferred between servlets and clients is now encrypted. Voila, security!
SSL Client Authentication

Our security toolbox now includes strong encryption and strong server authentication, but only
weak client authentication. Of course, using SSL 2.0 puts us in better shape because SSL-
equipped servers can use the basic authentication methods discussed at the beginning of this
chapter without concern for eavesdropping. We still don't have proof of client identity, however-
-after all, anybody could have guessed or gotten a hold of a client username and password.

SSL 3.0 fixes this problem by providing support for client certificates. These are the same type
of certificates that servers use, but they are registered to clients instead. As of this
writing, VeriSign claims to have distributed more than 750,000 client certificates. SSL 3.0 with
client authentication works the same way as SSL 2.0, except that after the client has
authenticated the server, the server requests the client's certificate. The client then sends its
signed certificate, and the server performs the same authentication process as the client did,
comparing the client certificate to a library of existing certificates (or simply storing the

the client user to enter a password before they will send the certificate.
o m
certificate to identify the user on a return visit). As a security precaution, many browsers require

o t .c
Once a client has been authenticated, the server can allow access to protected resources such as

s p
servlets or files just as with HTTP authentication. The whole process occurs transparently,
without inconveniencing the user. It also provides an extra level of authentication because the

lo g
server knows the client with a John Smith certificate really is John Smith (and it can know which
John Smith it is by reading his unique certificate). The disadvantages of client certificates are

. b
that users must obtain and install signed certificates, servers must maintain a database of all

i te
accepted public keys, and servers must support SSL 3.0 in the first place. As of this writing, most
do, including the Java Web Server.
s
o u
n
SSL Client Application Components

ig
w .
At a minimum, an SSL client application includes the following components:

w w
Java client

Typically, a Java client performs these functions:

o Initializes an SSLContext with client identity, trust, a HostnameVerifier, and


a TrustManager.
o Loads a keystore and retrieves the private key and certificate chain
o Uses an SSLSocketFactory
o Uses HTTPS to connect to a JSP served by an instance of WebLogic Server
HostnameVerifier

The HostnameVerifier implements


the weblogic.security.SSL.HostnameVerifier interface.

HandshakeCompletedListener
The HandshakeCompletedListener implements
the javax.net.ssl.HandshakeCompletedListener interface. It is used by the SSL client to
receive notifications about the completion of an SSL handshake on a given SSL
connection.

TrustManager

The TrustManager implements the weblogic.security.SSL.TrustManager interface.

package abc;

import java.net.URL;
o m
import java.io.*;

o t .c
import javax.net.ssl.HttpsURLConnection;
s p
lo g
. b
te
public class JavaHttpsExample

{
s i
o u
ig n
.
public static void main(String[] args) throws Exception {

w
w w
String httpsURL = "https://your.https.url.here/";

URL myUrl = new URL(httpsURL);

HttpsURLConnection conn = (HttpsURLConnection)myUrl.openConnection();

InputStream is = conn.getInputStream();

InputStreamReader isr = new InputStreamReader(is);

BufferedReader br = new BufferedReader(isr);

String inputLine;
while ((inputLine = br.readLine()) != null) {

System.out.println(inputLine);

br.close();

o m
.c
9. Write a template code for implementation of EJB client. What are the restriction on
what EJB can do ?

o t
s p
lo g
EJB is an acronym for enterprise java bean. It is a specification provided by Sun Microsystems
to develop secured, robust and scalable distributed applications.

. b
te
To get information about distributed applications, visit RMI Tutorial first.

s i
To run EJB application, you need an application server (EJB Container) such as Jboss,

o u
Glassfish, Weblogic, Websphere etc. It performs:

ig n
a. life cycle management,

w .
b. security,

w w
c. transaction management, and
d. object pooling.

EJB application is deployed on the server, so it is called server side component also.

EJB is like COM (Component Object Model) provided by Microsoft. But, it is different from
Java Bean, RMI and Web Services.

Types of Enterprise Java Bean

There are 3 types of enterprise bean in java.

Session Bean

Session bean contains business logic that can be invoked by local, remote or webservice client.
Message Driven Bean

Like Session Bean, it contains the business logic but it is invoked by passing message.

Entity Bean

It encapsulates the state that can be persisted in the database. It is deprecated. Now, it is replaced
with JPA (Java Persistent API).

EJB and Webservice

In EJB, bean component and bean client both must be written in java language.

If bean client need to be written in other language such as .net, php etc, we need to go
with webservices (SOAP or REST). So EJB with web service will be better option.

o m
Disadvantages of EJB
o t .c
1. Requires application server
s p
lo g
2. Requires only java client. For other language client, you need to go for webservice.

b
3. Complex to understand and develop ejb applications.
.
AdderImplRemote.java

s i te
package com.abc;
o u
n
import javax.ejb.Remote;

ig
@Remote
w .
w w
public interface AdderImplRemote {
int add(int a,int b);
}

AdderImpl.java
package com.abc;
import javax.ejb.Stateless;

@Stateless(mappedName="st1")
public class AdderImpl implements AdderImplRemote {
public int add(int a,int b){
return a+b;
}
}
2) Create stateless bean client

The stateless bean client may be local, remote or webservice client. Here, we are going to create
remote client. It is console based application. Here, we are not using dependency injection. The
dependency injection can be used with web based client only.

File: AdderImpl.java
o m
package com.abc;
import javax.naming.Context;
o t .c
import javax.naming.InitialContext;
s p
public class Test {
lo g
. b
public static void main(String[] args)throws Exception {

te
Context context=new InitialContext();

s i
AdderImplRemote remote=(AdderImplRemote)context.lookup("st1");

}
o u
System.out.println(remote.add(32,32));

}
ig n
w .
w w
10. What are the important features of entity beans. Distinguish between Bean managed
and Container managed persistence for Entity Beans. Write the methods required for
entity beans.

Answer :-

Bean managed and Container managed persistence for Entity Beans


Entity Bean Features

m
An entity bean represents a business object in a persistent storage mechanism. Some

.c o
examples of business objects are customers, orders, and products. In the J2EE SDK, the
persistent storage mechanism is a relational database. Typically, each entity bean has an

o t
underlying table in a relational database, and each instance of the bean corresponds to a
row in that table.

s p
Key Features of Entity Beans
lo g
These are the key features of entity beans:
. b

i te
PersistenceEntity bean persistence can be managed by the EJB container, or the bean

s
itself. If a bean uses container-managed persistence, the EJB container automatically

u
generates the necessary database access calls. The code that you write for the entity
o
n
bean does not include these calls. With bean-managed persistence, you must write the

ig
database access code and include it in the bean.

w .
Shared AccessThroughout its lifecycle, an entity bean instance can support multiple
clients, although not at the same time. Because the clients might want to change the

w w
same data, it is important that entity beans work within transactions. Typically, the EJB
container provides transaction management. In this case, you specify the transaction
attributes in the bean's ejb-jar.xml file that control how transactions are managed. You
do not have to code the transaction boundaries in the beanthe container marks the
boundaries for you. For information about transaction management.
Primary KeyEach entity bean has a unique object identifier. A customer entity bean,
for example, might be identified by a customer number. The unique identifier, or
primary key, enables the client to locate a particular entity beanRelationshipsLike a
table in a relational database, an entity bean may be related to other entity beans. You
implement relationships differently for entity beans with bean-managed persistence and
for those with container-managed persistence. With bean-managed persistence, the
code that you write implements the relationships. But with container-managed
persistence, the EJB container takes care of the relationships for you. For this reason,
relationships in entity beans with container-managed persistence are often referred to
as container-managed relationships.

11. What are different recovery procedures in security implementation?


Discuss.
Answer :-

o m

t .c

s p

lo g

. b

s i te
o u

ig n

w .

w w

o m
o t.c
sp
lo g
. b
s ite
ou
ig n
w .
ww

Das könnte Ihnen auch gefallen