0% found this document useful (0 votes)
10 views

P3 java(2)

Practical Java

Uploaded by

whackedbysahibr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

P3 java(2)

Practical Java

Uploaded by

whackedbysahibr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Practical No.

: 03
Name: Sahib zubair temkar Date: / /
Class: TY BSC IT Subject: Advanced Java Technology Roll No.: 22

Aim: A) Create a Servlet application to upload and download a file.


i) File Upload
Code:
index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
Select File to Upload:<input type="file" name="file" id="file">
Destination <input type="text" value="/tmp" name="destination">
<br>
<input type="submit" value="Upload file" name="upload" id="upload">
</form>
</body>
</html>
FileUploadServlet.java
package fileservletapp;

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.*;

@MultipartConfig
public class FileUploadServlet extends HttpServlet {

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String path = req.getParameter("destination");
Part filePart = req.getPart("file");
String filename = filePart.getSubmittedFileName().toString();
out.print("<br><br><hr> filename: " + filename);
OutputStream os = null;
InputStream is = null;
try {
os = new FileOutputStream(new File(path + File.separator + filename));
is = filePart.getInputStream();
intread = 0;

while ((read = is.read()) != - 1) {


os.write(read);
}
out.println("<br>file uploaded sucessfully...!!!");
} catch (FileNotFoundException e) {
out.print(e);
}
}
}
Output:

ii) File Download


Code:
index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>File Download Application</h1>
Click <a href="DownloadServlet?filename=SampleChapter.pdf">Sample
Chapter</a> <br/><br/>
Click <a href="DownloadServlet?filename=TOC.pdf">Table Of Contents</a>
</body>
</html>
DownloadServlet.java
package filedownloadapp;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("APPLICATION/OCTET-STREAM");
String filename = request.getParameter("filename");
ServletContext context = getServletContext();

PrintWriter out;
//ServletOutputStream out = response.getOutputStream(); // any of the two works
try (InputStream is = context.getResourceAsStream("/" + filename)) {
//ServletOutputStream out = response.getOutputStream(); // any of the two works
out = response.getWriter();
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename
+ "\""); int i;
while ((i = is.read()) != - 1) {
out.write(i);
}
}
out.close();
}
}
Output:

Aim: B) Develop Simple Servlet Question Answer Application using Database.


Code:
SQL command
create database qadb;
use qabd;

create table quiz (qno varchar(5) PRIMARY KEY,question varchar(100), op1


varchar(50), op2 varchar(50), op3 varchar(50), op4 varchar(50), ans varchar(50));

insert into quiz values('001','What is the capital of India??','New


Delhi','Kolkata','Chennai','Mumbai','New Delhi');
insert into quiz values('002','Who was the First President of India??','Dr. Rajendra
Prasad','Dr. S. Radhakrishnan','Ram Nath Kovind','V. V. Giri','Dr. Rajendra Prasad');
insert into quiz values('003','What is ORM','Object Ratio Mean','Object Rotation
Measure','Object Relation Mapping','Oracle Request Management','Object Relation
Mapping');
insert into quiz values('004','Unit of Energy is ','Dozon','Kilo Meter ','Joul','Hertz','Joul');
insert into quiz values('005',' --- is the smallest memory unit.','bit','byte','Kilo Byte','Giga Byte','bit');

index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Welcome to Quiz Servlet </h1>
<h1><a href="QuizServlet" >CLICK TO START QUIZ</a></h1>
</body>
</html>

QuizServlet.java
package mypack;

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

public class QuizServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<form action=ShowResult >");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:derby://localhost:1527/quizdb", "root",
"123456789");
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("select * from quiz");
out.println("<table border=1 >");
int qno = 0;
while (res.next()) {
qno++;
out.println("<tr><td>" + res.getString(1) + "</td>");
out.println("<td>" + res.getString(2) + "</td></tr>");
out.println("<tr><td><input type=radio name=" + qno + "value=" +
res.getString(3) + "></td><td>" + res.getString(3) + "</td></tr>");
out.println("<tr><td><input type=radio name=" + qno + "value=" +
res.getString(4) + "></td><td>" + res.getString(4) + "</td></tr>");
out.println("<tr><td><input type=radio name=" + qno + "value=" +
res.getString(5) + "></td><td>" + res.getString(5) + "</td></tr>");
out.println("<tr><td><input type=radio name=" + qno + "value=" +
res.getString(6) + "></td><td>" + res.getString(6) + "</td></tr>");
}
} catch (Exception e) {
out.println(e);
}
out.println("</table>");
out.println("<input type=reset >");
out.println("<input type=submit value=SUBMIT >");
out.println("</form>");
}
}

ShowResult.java
package mypack;

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

public class ShowResult extends HttpServlet {

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:derby://localhost:1527/quizdb", "root",
"123456789");
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("select ans from quiz");
int count = 0, qno = 0;
while (res.next()) {
if (res.getString(1).equals(request.getParameter("" + (++qno)))) {
count++;
out.println("<h1>Correct </h1>");
} else {
out.println("<h1>Incorrect </h1>");
}
}
out.println("<h1>Your Score is " + count + " </h1>");
} catch (Exception e) {
out.println(e);
}
}
}

Output:
Aim: C) Create simple Servlet application to demonstrate Non-Blocking Read
Operation. Code:
index.html
<html>
<head>
<title>Non Blocking IO</title>
<meta charset="UTF-8">
<meta http-equiv="Refresh" content="0; URL=NonBlockingServlet">
</head>
<body>
</body>
</html>

NonBlockingServlet.java
package nonblkapp;

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class NonBlockingServlet extends HttpServlet {

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {

out.println("<h1>FileReader</h1>");
String filename = "/WEB-INF/booklist.txt";
ServletContext c = getServletContext();
InputStream in = c.getResourceAsStream(filename);
String path = "http://" + request.getServerName() + ":" +
request.getServerPort() + request.getContextPath()
+"/ReadingNonBloclingServlet";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setChunkedStreamingMode(2);
conn.setDoOutput(true);
conn.connect();
if (in != null) {
InputStreamReader inr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inr);
String text = "";
System.out.println("Reading started. .. ");
BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(conn.getOutputStream()));
while ((text = br.readLine()) != null) {
out.print(text + "<br>");
try {
Thread.sleep(1000);
out.flush();
} catch (InterruptedException ex) {
}
}
out.print("reading completed. ..");
bw.flush();
bw.close();
}
}
}
}
ReadingListener.java
package nonblkapp;

import java.io.IOException;
import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;

public class ReadingListener implements ReadListener {

private ServletInputStream input = null;


private AsyncContext ac = null;

ReadingListener(ServletInputStream in,AsyncContext c) {
input = in;
ac = c;
}

@Override
public void onDataAvailable() throws IOException {
}

@Override
public void onAllDataRead() throws IOException {
ac.complete();
}

@Override
public void onError(final Throwable t) {
ac.complete();
t.printStackTrace();
}
}

ReadingNonBlockingServlet.java
package nonblkapp;

import java.io.IOException;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "ReadingNonBlockingServlet", urlPatterns


= {"/ReadingNonBlockingServlet"}, asyncSupported = true)
public class ReadingNonBlockingServlet extends HttpServlet {

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
AsyncContext ac = request.startAsync();
ServletInputStream in = request.getInputStream();
in.setReadListener(new ReadingListener(in, ac));
}
}

Output:

You might also like