Vous êtes sur la page 1sur 29

HTTP REQUEST

Ex. No.: 8.a Name: M Vignesh


Date: Reg. No. 30707104112

import java.net.*;

import java.io.*;

import javax.swing.*;

import java.awt.*;

public class SourceViewer3

public static void main (String[] args)

try

URL u = new URL(args[0]);

HttpURLConnection uc = (HttpURLConnection)

u.openConnection( );

int code = uc.getResponseCode( );

String response = uc.getResponseMessage( );

System.out.println("HTTP/1.x " + code + " " + response);

for (int j = 1; ; j++)

String header = uc.getHeaderField(j);

String key = uc.getHeaderFieldKey(j);

if (header == null || key == null) break;

System.out.println(uc.getHeaderFieldKey(j) + ": " + header);

InputStream in = new BufferedInputStream(uc.getInputStream( ));

Reader r = new InputStreamReader(in);

int c;
while ((c = r.read( )) != -1)

System.out.print((char) c);

catch (MalformedURLException ex)

System.err.println(args[0] + " is not a parseable URL");

catch (IOException ex)

{
System.err.println(ex);

OUTPUT:

C:\IPLAB>javac SourceViewer3.java
C:\IPLAB>java SourceViewer3 http://www.hotmail.com

HTTP/1.x 302 Found


Date: Wed, 06 Oct 2010 14:51:40 GMT
Server: Microsoft-IIS/6.0
P3P: CP="BUS CUR CONo FIN IVDo ONL OUR PHY SAMo TELo"
xxn: -2
MSNSERVER: H: BAY0-DP4-2 V: 15.3.2529.827 D: 2010-08-27T20:01:22
Location: https://login.live.com/login.srf?
wa=wsignin1.0&rpsnv=11&ct=1286376700&rver=6.0.5285.0&wp=MBI&
wreply=http:%2F%2Fmail.live.com
%2Fdefault.aspx&lc=1033&id=64855&mkt=en-US
Set-Cookie: KSC=; domain=.mail.live.com; expires=Thu, 01-Jan-1970
12:00:01 GMT; path=/
Set-Cookie: kr=; domain=.mail.live.com; expires=Thu, 01-Jan-1970
12:00:01 GMT; path=/
Set-Cookie: afu=; domain=.mail.live.com; expires=Thu, 01-Jan-1970
12:00:01 GMT; path=/
Set-Cookie: bsc=; domain=.mail.live.com; expires=Thu, 01-Jan-1970
12:00:01 GMT; path=/
Set-Cookie: rru=; domain=.mail.live.com; expires=Thu, 01-Jan-1970
12:00:01 GMT; path=/
Set-Cookie: prc=; domain=.mail.live.com; expires=Thu, 01-Jan-1970
12:00:01 GMT; path=/
Set-Cookie: mt=; domain=.mail.live.com; expires=Thu, 01-Jan-1970
12:00:01 GMT; path=/
Set-Cookie: KVC=; domain=.mail.live.com; expires=Thu, 01-Jan-1970
12:00:01 GMT; path=/
Set-Cookie: DWN=; domain=.mail.live.com; expires=Thu, 01-Jan-1970
12:00:01 GMT; path=/
Cache-Control: no-cache, no-store
Pragma: no-cache
Expires: -1
Content-Type: text/html; charset=utf-8
Content-Length: 315
<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="https://login.live.com/login.srf?
wa=wsignin1.0&amp;rpsnv=11&amp;ct=1286376700&amp;rver=6.0.528
5.0&amp;wp=MBI&amp;wreply=http:%2F%2Fmail.live.com
%2Fdefault.aspx&amp;lc=1033&amp;id=64855&amp;mkt=en-
US">here</a>.</h2>
</body>
</html>
SMTP
Ex.No: Name: M Vignesh

Date: Reg.No:30707104112

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class Assimilator {
public static void main(String[] args) {
try {
Properties props = new Properties( );
props.put("mail.host", "mail.rajalakshmi.org");
Session mailConnection = Session.getInstance(props, null);
Message msg = new MimeMessage(mailConnection);
Address billgates = new InternetAddress("billgates@microsoft.com", "Bill Gates");
Address bhuvangates = new InternetAddress("webadmin@rajalakshmi.org");
msg.setContent("Wish You a Happy New Year 2008", "text/plain");
msg.setFrom(billgates);
msg.setRecipient(Message.RecipientType.TO, bhuvangates);
msg.setSubject("Greetings");
Transport.send(msg);
}
catch (Exception ex) {
ex.printStackTrace( );
}
}
}
Output:-
C:\IPLAB>javac Assimilator.java
C:\IPLAB>java Assimilator
File Transfer Protocol
Ex.No: 8.c Name: M Vignesh
Date: Reg.No:30707104112

// FileServer.java
import java.net.*;
import java.io.*;
public class FileServer {
ServerSocket serverSocket;
Socket socket;
int port;
FileServer() {
this(9999);
}
FileServer(int port) {
this.port = port;
}
void waitForRequests() throws IOException
{
serverSocket = new ServerSocket(port);
while (true)
{
System.out.println("Server Waiting...");
socket = serverSocket.accept();
System.out.println("Request Received From " +socket.getInetAddress()
+"@"+socket.getPort());
new FileServant(socket).start();
System.out.println("Service Thread Started");
}
}
public static void main(String[] args) {
try {
new FileServer().waitForRequests();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
// FileClient.java
import java.net.*;
import java.io.*;
public class FileClient
{
String fileName;
String serverAddress;
int port;
Socket socket;
FileClient() {
this("localhost", 9999, "Sample.txt");
}
FileClient(String serverAddress, int port, String fileName) {
this.serverAddress = serverAddress;
this.port = port;
this.fileName = fileName;
}
void sendRequestForFile() throws UnknownHostException, IOException {
socket = new Socket(serverAddress, port);
System.out.println("Connected to Server...");
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.println(fileName);
writer.flush();
System.out.println("Request Sent...");
getResponseFromServer();
socket.close();
}
void getResponseFromServer() throws IOException {
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String response = reader.readLine();
if(response.trim().toLowerCase().equals("filenotfound")) {
System.out.println(response);
return;
}
else {
BufferedWriter fileWriter = new
BufferedWriter(new FileWriter("Recdfile.txt"));
do {
FileWriter.write(response);
FileWriter.flush();
}
while((response=reader.readLine())!=null);
FileWriter.close();
}
}
public static void main(String[] args) {
try {
new FileClient().sendRequestForFile();
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
// FileServent.java
import java.net.*;
import java.io.*;
public class FileServant extends Thread {
Socket socket;
String fileName;
BufferedReader in;
PrintWriter out;
FileServant(Socket socket) throws IOException {
this.socket = socket;
in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
}
public void run() {
try {
fileName = in.readLine();
File file = new File(fileName);
if (file.exists()) {
BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
String content = null;
while ((content = fileReader.readLine()) != null) {
out.println(content);
out.flush();
System.out.println("File Sent...");
}
Else {
System.out.println("Requested File Not Found...");
out.println("File Not Found");
out.flush();
}
socket.close();
System.out.println("Connection Closed!");
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace(); }}
public static void main(String[] args) { }
}
Output:

C:\IPLAB>javac FileServer.java
C:\IPLAB>javac FileClient.java
C:\IPLAB>javac FileServent.java
C:\IPLAB>copy con Sample.txt
Welcome to FTP
C:\IPLAB>java FileServer
Server Waiting...
C:\IPLAB>java FileClient
Connected to Server...
Request Sent...
C:\IPLAB>java FileServer
Server Waiting...
Request Received From /127.0.0.1@2160
Service Thread Started
Server Waiting...
File Sent...
Connection Closed!
C:\IPLAB>type Recdfile.txt
Welcome to FTP
Invoking Servlets from HTML form
Ex. No.: Reg. No.
30707104112
Date: Name: M Vignesh

<!-- PostParam.html -->

<HTML>
<BODY>
<CENTER>
<FORM name = "postparam" method = "post"
action="http://localhost:8080/examples/servlet/PostParam">
<TABLE>
<tr>
<td><B>Employee </B> </td>
<td><input type = "textbox" name="ename" size="25"
value=""></td>
</tr>
<tr>
<td><B>Phone </B> </td>
<td><input type = "textbox" name="phoneno" size="25"
value=""></td>
</tr>
</TABLE>
<INPUT type = "submit" value="Submit">
</body>
</body>
</html>

PostParam.java

import java.io.*;

import java.util.*;
import javax.servlet.*;

public class PostParam extends GenericServlet {

public void service(ServletRequest

request,ServletResponse response) throws ServletException, IOException {

PrintWriter pw = response.getWriter();

Enumeration e = request.getParameterNames();

while(e.hasMoreElements()) {

String pname = (String)e.nextElement();

pw.print(pname + " = ");

String pvalue = request.getParameter(pname);

pw.println(pvalue);

pw.close();

OUTPUT:
INVOKING SERVLETS FROM APPLET

Ex.No: Name: M Vignesh

Date: Reg.No:30707104112

Ats.html
<HTML>
<BODY>
<CENTER>
<FORM name = "students" method = "post"
action="http://localhost:8080/Student/Student">
<TABLE>
<tr>
<td><B>Roll No. </B> </td>
<td><input type = "textbox" name="rollno" size="25"
value=""></td>
</tr>
</TABLE>
<INPUT type = "submit" value="Submit">
</FORM>
<CENTER>
</BODY>
</HTML>

AppletToServlet.java

import java.io.*;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.net.*;

/* <applet code="AppletToServlet" width="300"


height="300"></applet> */

public class AppletToServlet extends Applet implements ActionListener


{
TextField toSend;
TextField toGet;
Label l1;
Label l2;
Button send;
Intermediate s;
String value;
ObjectInputStream is;
ObjectOutputStream os;
public void init()
{
toSend=new TextField(10);
add(toSend);
toGet=new TextField(10);
add(toGet);
l1=new Label("value sent");
l2=new Label("value received");
add(l1);
add(l2);
send=new Button("Click to send to servlet");
send.addActionListener(this);
add(send);
validate();
s=new Intermediate();
}
public void actionPerformed(ActionEvent e)
{
value=toSend.getText();
sendToServlet();
}
public void sendToServlet()
{
try
{
URL url=new

URL("http://localhost:8080"+"/servlet/ServletToApplet");
URLConnection con=url.openConnection();
s.setFname(value);
writeStuff(con,s);
s=new Intermediate();
Intermediate p=readStuff(con);
if(p!=null)
{
value=p.getFname();
toGet.setText("value:"+value);
validate();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public void writeStuff(URLConnection connection, Intermediate value)
{
Try
{
connection.setUseCaches(false);
connection.setRequestProperty("CONTENT_TYPE”, "application/octet-stream");
connection.setDoInput(true);
connection.setDoOutput(true);
os=new ObjectOutputStream(connection.getOutputStream());
os.writeObject(value);
os.flush();
os.close();
}
catch(Exception y){}
}
public Intermediate readStuff(URLConnection connection)
{
Intermediate s=null;
Try
{
is=new
ObjectInputStream(connection.getInputStream());
s=(Intermediate)is.readObject();
is.close();
}
catch(Exception e){}
return s;
}
}

ServletToApplet.java

import java.util.*;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class ServletToApplet extends HttpServlet
{
String valueGotFromApplet;
public void init(ServletConfig config) throws ServletException
{
System.out.println("Servlet entered");
super.init();
}
public void service(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException
{
try
{
System.out.println("service entered");
ObjectInputStream ois=new ObjectInputStream(request.getInputStream());
Intermediate ss=(Intermediate)ois.readObject();
valueGotFromApplet=ss.getFname();
System.out.println(valueGotFromApplet);
response.setContentType("application/octet- stream");
ObjectOutputStream oos=new
ObjectOutputStream(response.getOutputStream());
oos.writeObject(ss);
oos.flush();
oos.close();
}
catch(Exception e){System.out.println(e);
}
}
public String getServletInfo()
{
return "...";
}
}

Intermediate.java
import java.io.*;

public class Intermediate implements Serializable


{
String fname;
public String getFname()
{
return fname;
}
public void setFname(String s)
{
fname=s;
}
}

OUTPUT:

D:\servlet\WEB-INF\classes>javac Intermediate.java
D:\servlet\WEB-INF\classes>javac AppletToServlet.java
D:\servlet\WEB-INF\classes>javac ServlettoApplet.java
D:\servlet\WEB-INF>type web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<!-- JSPC servlet mappings start -->
<servlet>
<servlet-name>ServletToApplet</servlet-name>
<servlet-class>ServletToApplet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletToApplet</servlet-name>
<url-pattern>/ServletToApplet</url-pattern>
</servlet-mapping>
<!-- JSPC servlet mappings end -->
</web-app>

D:\servlet>jar -cvf ServletToApplet.war .


added manifest
adding: ats.html(in = 97) (out= 76)(deflated 21%)
adding: WEB-INF/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/AppletToServlet.class(in = 3055) (out= 1627)(deflated 46%)
adding: WEB-INF/classes/AppletToServlet.java(in = 1952) (out= 776)(deflated 60%)
adding: WEB-INF/classes/Intermediate.class(in = 433) (out= 273)(deflated 36%)
adding: WEB-INF/classes/Intermediate.java(in = 188) (out= 126)(deflated 32%)
adding: WEB-INF/classes/ServletToApplet.class(in = 1660) (out= 859)(deflated 48% )
adding: WEB-INF/classes/ServletToApplet.java(in = 975) (out= 424)(deflated 56%)
adding: WEB-INF/web.xml(in = 698) (out= 315)(deflated 54%)

Step 1: Open Web Browser and type


Step 2: http://localhost:8080
Step 3: Select Tomcat Manager
Step 4: Deploy the war file and Run
JDBC Connectivity
Ex. No.: Reg. No.
30707104112
Date: Name: M Vignesh

import java.sql.*;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class studentdata1 extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.print("<html><head>");

out.print("</head><body>");

out.println("<h1>STUDENT DATA</h1>");

out.println("<h3> Press the button to retrieve data form data </h3>");

out.print("<form action=\"");

out.print( req.getRequestURI() );

out.print("\" method=\"post\">");

out.print("<input type=\"submit\" ");

out.print("value=\" \"> ");

out.print("Display Records</form>");

out.print("</body></html>");

out.close();

public void doPost(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.print("<html><head>");
out.print("</head><body>");

out.print("<font color=green>SID\t Name\tTotal</font>\n");

// connecting to database

Connection con = null;

Statement stmt = null;

ResultSet rs = null;

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con = DriverManager.getConnection("jdbc:odbc:student");

stmt = con.createStatement();

rs = stmt.executeQuery("SELECT * FROM student");

// displaying records

while(rs.next()) {

out.print(rs.getObject(1).toString());

out.print("\t");

out.print(rs.getObject(2).toString());

out.print("\t");

out.print(rs.getObject(3).toString());

out.print("\n");

} catch (SQLException e) {

throw new

ServletException("Servlet Could not display records.", e);

} catch (ClassNotFoundException e) {

throw new

ServletException("JDBC Driver not found.", e);

} finally {

try {

if(rs != null) {

rs.close();
rs = null;

if(stmt != null) {

stmt.close();

stmt = null;

if(con != null) {

con.close();

con = null;

} catch (SQLException e) {}

out.print("<p\"><a href=\"");

out.print( req.getRequestURI() );

out.print("\">Back</a></p>");

out.print("</body></html>");

out.close();

OUTPUT:
ONLINE EXAMINATION – THREE TIER
ARCHITECTURE
Ex. No. 10.b Reg. No. 30707104112

DATE: 8.10.10 Name: M Vignesh

Ques.html

<html>

<head><title>database test </title></head>

<body>

<center>

<h1>online examination </h1>

</center>

<form action="http://localhost:8080/examples/servlet/online" method="POST">

<div align="left"> <br>

<b>Name: </b> <input type="text" name="Name" size="50"><br>

</div>

<br><br>

<b>1.Every host implements transport layer</b><br>

<input type="radio" name="group1"value="true">true

<input type="radio" name="group1"value="false">false

<br><br>

<b>2. Servlet is server side script</b><br>

<input type="radio" name="group2"value="true">true

<input type="radio" name="group2"value="false">false

<br><br>

<input type="submit" value="submit"><br><br>

</form>

</body>

</html>
Online.java

import java.io.*;

import java.sql.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;

public class online extends HttpServlet

String message,Name,ans1,ans2;

int total=0;

Connection connect;

Statement stmt=null;

ResultSet re=null;

public void doPost(HttpServletRequest req,HttpServletResponse res)throws


ServletException,IOException

try {

String url="jdbc:odbc:student12";

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

connect=DriverManager.getConnection(url," "," ");

message="connection success";

catch(ClassNotFoundException cn){

cn.printStackTrace();

catch(Exception sq)

{sq.printStackTrace();

Name=req.getParameter("Name");
ans1=req.getParameter("group1");

ans2=req.getParameter("group2");

if(ans1.equals("true"))

total+=2;

if(ans2.equals("false"))

total+=2;

try {

Statement stmt=connect.createStatement();

String query="INSERT INTO Table1 ("+"name,score"+") VALUES


('"+Name+"','"+total+"')";

int result=stmt.executeUpdate(query);

stmt.close();

catch(SQLException e){}

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.println("<html><head>");

out.println("</head><body>");

out.println("<h3>Updated</h3><br><br>");

out.println("<b>Content of the database</b>");

out.println("<table border=5>");

try {

Statement stmt=connect.createStatement();

String query="SELECT * FROM Table1";

re=stmt.executeQuery(query);

out.println("<th>"+"Name"+"</th>");

out.println("<th>"+"Marks"+"</th>");

while(re.next()) {

out.print("<tr>");
out.println("<td>"+re.getString(1)+"</td>");

out.println("<td>"+re.getInt(2)+"</td>");

out.print("</tr>");

out.print("</table>");

catch(SQLException ex){}

finally {

try {

if(re!=null)

re.close();

if(stmt!=null)

stmt.close();

if(connect!=null)

connect.close();

catch(SQLException e){}

out.print("<center>");

out.print("<h2>thanks </h2>");

out.print("</center>");

out.print("</body></html>");

out.close(); } }

OUTPUT: