Q.1.
Advanced Java:
A)
Write a java program to blink image on the Frame continuously.
Answer :
import java.awt.*;
public class Slip6A extends Frame {
int f = 0;
public Slip6A() {
Blink s = new Blink();
s.start();
setSize(500, 500);
setVisible(true);
}
class Blink extends Thread {
public void run() {
while (true) {
f = (f + 1) % 2;
repaint();
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
}
}
public void paint(Graphics g) {
Toolkit t = Toolkit.getDefaultToolkit();
Image img = t.getImage("./car.png");
switch (f) {
case 0:
g.drawImage(img, 150, 100, this);
}
}
public static void main(String args[]) {
new Slip6A();
}
}
B)
Write a SERVLET program which counts how many times a user has visited a web
page. If user is visiting the page for the
first time, display a welcome message. If the
user is revisiting the page, display the
number of times visited. (Use Cookie)
Answer :
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class VisitCounterServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int visits = 0;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("visitCount")) {
visits = Integer.parseInt(cookie.getValue());
}
}
}
visits++;
Cookie visitCookie = new Cookie("visitCount", Integer.toString(visits));
response.addCookie(visitCookie);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (visits == 1) {
out.println("<html><head><title>Welcome</title></head><body>");
out.println("<h2>Welcome
to my website!</h2>");
out.println("</body></html>");
} else {
out.println("<html><head><title>Visit
Count</title></head><body>");
out.println("<h2>You
have visited this website " + visits + "
times.</h2>");
out.println("</body></html>");
}
out.close();
}
}
No comments:
Post a Comment