Nothing Special   »   [go: up one dir, main page]

AJP Lab Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 37

KG COLLEGE OF ARTS AND SCIENCE

Affiliated to Bharathiar University &


Accredited by NAAC ISO 9001: 2015 Certified Institution
KGiSL Campus, Saravanampatti,
Coimbatore-641035

PG Department of Software Systems & Computer Science

LAB MANUAL
ADVANCED JAVA PROGRAMMINGLAB
INDEX
Date Title of the Experiment
SI. No. Page No. Signature

WELCOME MESSAGE USING SERVLET


01

PURCHASE ORDER USING SERVLET


02

03 STUDENT MARK LIST USING JSP

04 PURCHASE ORDER USING JSP

05 EMPLOYEE PAY SLIP USING JSP

06 CALCULATOR USING APPLET

07 HANDLING FORM DATA USING SERVLET

08 TABLE HEADER

09 SESSION OBJECT USING JSP

10 CLIENT AND SERVER (SOCKET)


Pre-requisite: Basics in Java Programming

Course Objectives:

The main objectives of this course are to:

1.To enable the students to implement the simple programs using JSP, JAR.

2.To provide knowledge on using Servlets, Applets.

3.To introduce JDBC and navigation of records .

4.To understand RMI & its implementation.

5.To introduce to Socket programming.

Expected Course Outcomes:

On the successful completion of the course, student will be able to:

1. Understand to the implement concepts of Java using HTML forms, JSP & JAR.

2. Must be capable of implementing JDBC and RMI concepts.

3. Able to write Applets with Event handling mechanism.

4. To Create interactive web based applications using servlets and jsp K.

LIST OF PROGRAMS 75 hours

1. Display a welcome message usingServlet.

2. Design a Purchase Order form using Html form andServlet.

3. Develop a program for calculating the percentage of marks of a student usingJSP.

4. Design a Purchase Order form using Html form andJSP.

5. Prepare a Employee pay slip usingJSP.

6. Write a program using JDBC for creating a table, Inserting, Deleting records and listout therecords.

7. Write a program using Java servlet to handle formdata.

8. Write a simple Servlet program to create a table of all the headers it receives along withtheir associatedvalues.

9. Write a program in JSP by using sessionobject.

10. Write a program to build a simple Client Server application usingRMI.

11. Create an applet for a calculator application.

12. Program to send a text message to another system and receive the text message from the system (use socket programming).
1. WELCOME MESSAGE USING SERVLET

AIM:

To Display a welcome message using Servlet.


ALGORITHM:

Step1: Open Netbeans IDE.

Step 2: Select file – new project.

Step 3: Select javaweb – web application.

Step 4: Select next – give project name: Web page.

Step 5: Click next – finish.

Step 6: Right click on default packaged – new – servlet.

Step 7: Give name for servlet and click next – finish.

Step 8: Select add information. click finish.

Step 9: Type HTML codes for display a welcome message.

Step10: Specify attributes such as <u>, <li> to display in list formation.

Step11: Set color to font using font color tag.

Step12: Run the file.

Step13: Display welcome message.

PROGRAM:

MyServlet.java

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse; @WebServlet("/MyAction")

public class MyServlet extends HttpServlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

response.setContentType("text/html"); PrintWriter pw=response.getWriter(); pw.write("<h1> Welcome to Servlet <h1> <br>");

pw.write("<h2> you have successfully received your response <h2> <br>"); }

}
Index.html

<html> <head>

<meta charset="UTF-8">

<title>First servlet page</title>

</head>

<body>Welcome to servlet world <br><br>

<a href="MyAction">Click here</a>

</body> </html>
OUTPUT:
2. PURCHASE ORDER USING SERVLET

AIM:

Design a Purchase Order form using Html form and Servlet.

ALGORITHM:

Step 1: Start the process

Step 2: Create the index file.


Step 3: Add the controls using form elements.
Step 4: Click on the source packages .In that select default package.
Step 5: Create a new servlet by right clicking default packages then click new option. In the pop up menu select the servlet option.
Step 6: Type the code for servlet.Run the project(Right click the project , click run option .
Step 7: Display the output.

PROGRAM:

Index.html
<html>
<head>
<title>Purchase order</title>
</head>
<body>
<h1>
Please tell about product</h1>
<form action=”NewServlet”>
Purchase Order No:<input type=”text” name=”productno”> Product Name : <input type=”text” name=”productname”> Address:<input type=”text”
name=”Address”><br>
Phone no:<input type=”text” name=”phoneno”><br>
<p>
Items to be ordered:
<select name=”JeanType”>
<option value=”Lenin”>Lenin</option>
<option value=”Otto”>OTTO</option>
<option value=”S-Kumar”>S-Kumar</option>
<option value=”V-Star”>V-Star</option>
<option value=”Jockey”>Jockey</option>
<option value=”Peter”>Peter</option>
<option value=”Pantaloon”>Pantaloon</option>
</select>
<br>
Ordered Date:<input type=”date” name=”od”> Amount:<input type=”number” name=”amt”>
<input type=”submit”>
</form>
</body>
</html>
NewServlet

import java.io.IOException;
import java.io.printWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NewServlet extends HttpServlet
{
Public void service(ServletRequest request,ServletResponse response)throws ServletException,IOException
{
String productno=request.getParameter(“productno”);
String productname=request.getParameter(“productname”);
String address=request.getParameter(“address”);
String phoneno=request.getParameter(“phoneno”);
String JeanType=request.getParameter(“JeanType”);
String od=request.getParameter(“od”);
int amt=Integer.parseInt(request.getParameter(“amt”));
response.setContentType(“text/html”);
PrintWriter pw=response.getWriter();
pw.write(“<h2>Following data received successfully..</h2><br>”);
pw.write(“<h2>Product no:”+productno+”</h2><br>”);
pw.write(“<h2>Product name:”+productname+”</ h2><br>”); pw.write(“<h2>Address:”+address+”</h2><br>”); pw.write(“<h2>Phoneno”+phoneno+”</h2><br>”);
pw.write(“<h2>JeanType”+JeanType+”</h2><br>”);
pw.write(“<h2>Ordered date”+od+”</h2><br>”);
pw.write(“<h2>Amount”+amt+”</h2><br>”);
pw.write(“</h2><br>”);
}
}
3. STUDENT MARKLIST USING JSP
AIM:
To develop a program for calculating the percentage of marks of a student using jsp

ALGORITHM:
Step1: Open Netbeans IDE.
Step2: Select file – new project.
Step3: Select javaweb – web application.
Step4: Select next – give project name: Web page.
Step5: Click next – finish.
Step6: Right click on default packaged – new – servlet.
Step7: Give name for servlet and click next – finish.
Step8: Select add information. click finish.

PROGRAM:

Index.html
<html>

<head>

<title>TODO supply a title</title>

</head>

<body><center>

<h1>Student marks</h1>

<form action="index.jsp" method="get">

<b>Enter Java Marks : <input type="text" name="java"> </b><br><br>

<b>Enter AI Marks : <input type="text" name="AI"></b><br><br>

<b>Enter AOS Marks :<input type="text" name="AOS"></b><br><br>

<b>Enter PHP Marks :<input type="text" name="PHP"></b><br><br>

<b>Enter WS Marks :<input type="text" name="WS"></b><br><br>

<b><input type="submit"></b></form></center>

</body> </html>

Index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<body>

<%

int java=Integer.parseInt(request.getParameter("java"));

int AI=Integer.parseInt(request.getParameter("AI"));

int AOS=Integer.parseInt(request.getParameter("AOS"));

int PHP=Integer.parseInt(request.getParameter("PHP"));

int WS=Integer.parseInt(request.getParameter("WS"));

int c=java+AI+AOS+PHP+WS;

out.println("Your total is"+c);

double avg=c/5;

if(avg > 90 )

out.println( "your grade is A \n");

else if (avg >= 80)

{
out.println("your grade is B \n");

} else if (avg >= 70)

out.println("your grade is C \n");

else if (avg >= 60)

{ out.println("your grade is D \n");

else

{ out.println("your grade is E

\n");

%>

</body></html>
4.PURCHASE ORDER USING JSP

AIM:
To design Purchase Order form using HTML form and jsp.

ALGORITHM:

Step1: Open Netbeans IDE.

Step2: Select file – new project.

Step3: Select javaweb – web application.

Step4: Select next – give project name: Web page.

Step5: Click next – finish.

Step6: Right click on default packaged – new – jsp.

Step7: Give name for jsp and click next – finish.

Step8: Select add information. click finish.

PROGRAM:

Index.html
<html>

<body>

<h1>Please tell me about yourself</h1>

<form action="pur.jsp" method="get">

Purchase order no: <input type="text" name="pid"> Company Name:<input type="text" name="cname"> Company Address:<input type="text" name="cadd"><br>

Company Location:<input type="radio" checked name="cl" value="Chennai">Chennai

<input type="radio" name="cl" value="Madurai">Madurai

<input type="radio" name="cl" value="Bangalore">Bangalore

<p>

Items to be ordered:

<select name="JeanType">

<option value="Lenin">Lenin</option>

<option value="Otto">Otto</option>

<option value="S-Kumar">S-Kumar</option>

<option value="V-Star">V-Star</option>

<option value="Jockey">Jockey</option>

<option value="Peter">Peter</option>

<option value="Pantaloon">Pantaloon</option>

</select>

<br>

Ordered Date:<input type="date" name="od"> Amount:<input type="number" name="amt">

<input type="submit">

</form>

</body> </html>
PUR.JSP
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<body>

<%

// Grab the variables from the form.

String pid = request.getParameter("pid");

String cname = request.getParameter("cname");

String cadd = request.getParameter("cadd");

String cl = request.getParameter("cl");

String JeanType = request.getParameter("JeanType");

String od= request.getParameter("od");

int amt = Integer.parseInt(request.getParameter("amt"));

%>

<%-- Print out the variables. --%>

<h1>Hello, <%=pid%><%=cname%> <%=cadd%>!</h1> I ordered following items <%=JeanType%>. From <%=cl%>. I expect your response as soon as possible

</body>

</html>
5. EMPLOYEE PAY SLIP USING JSP

AIM:

To prepare an Employee pay slip using JSP.

ALGORITHM:

Step 1: start the process.

Step 2: open Netbeans IDE.

Step 3: select java-&gt; java application.

Step 4: select text and design a employee pay slip from using html.

Step 5: Right click on Project name and payslip -&gt; new -&gt;jsp.

Step 6: Type coding and call the parameters.

Step 7: Run the program.

Step 8: Display employee pay slip with according to the user input value.

PROGRAM:

Index.html
<html>
<head>
<title>Employee Salary Statement</title>
</head>
<body>
<h3>Enter Employee Details:</h3>
<form action="emp20.jsp" method="POST" >
<table>
<tr><td>Employee Name:</td><td><input type="text" name="ename" autofocus></td></tr>
<tr><td>Employee Number:</td><td><input type=”text” number=”eno”></td></tr>
<tr><td>Department:</td><td><input type="text" name="dept"></td></tr>
<tr><td>Designation:</td><td><input type="text" name="des"></td></tr>
<tr><td>Basic Salary:</td><td><input type="text" name="bsal"></td></tr>
<tr><td>TA(%):</td><td><input type="text" name="ta"></td></tr>
<tr><td>DA(%):</td><td><input type="text" name="da"></td></tr>
<tr><td>HRA(%):</td><td><input type="text" name="hra"></td></tr>
<tr><td>PF(%):</td><td><input type="text" name="pf"></td></tr>
<tr><td>LIC(%):</td><td><input type="text" name="lic"></td></tr>
<tr><td><input type="submit" value="Evaluate"></td>
<td><input type="reset" value="Reset"></td></tr>
</table>
</body>
</html>

Emp20.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<%@ page import="java.sql.*" %>
</head>
<body bgcolor="beige">
<%
String ename=request.getParameter("ename");
String dept=request.getParameter("dept");
String des=request.getParameter("des");
double bsal=Double.valueOf(request.getParameter("bsal"));
double ta=Double.valueOf(request.getParameter("ta"));
double ta2=bsal*ta/100;
double da=Double.valueOf(request.getParameter("da"));
double da2=bsal*da/100;
double hra=Double.valueOf(request.getParameter("hra"));
double hra2=bsal*hra/100;
double pf=Double.valueOf(request.getParameter("pf"));
double pf2=bsal*pf/100;
double lic=Double.valueOf(request.getParameter("lic"));
double lic2=bsal*lic/100;
double allowance;
double deduction;
double gsal;
double netsal;
allowance = (bsal*ta)/100 + (bsal*da)/100 + (bsal*hra)/100; deduction = (bsal*pf)/100 + (bsal*lic)/100; gsal = bsal + allowance; netsal = gsal - deduction;

%>

<CENTER>

<table border=5 bgcolor="biege" height=600 width=400 >

<caption><h2><fontcolor="blue">XYZ Company Ltd.,<br>

SALARY STATEMENT</font></h2></caption>

<tr><td>Employee Name</td><td colspan=2><%=ename%></td></tr>

<tr><td>Department</td><td colspan=2><%=dept%></td></tr>

<tr><td>Designation</td><td colspan=2><%=des%></td></tr>

<tr><td>Basic Salary</td><td colspan=2><%=bsal%></td></tr>

<tr><th>Allowances</th><th>Percentage</th><th>Amount</th></tr>

<tr align=center><td>TA</td><td><%=ta%></td><td><%=ta2%></td></tr>

<tr align=center><td>DA</td><td><%=da%></td><td><%=da2%></td></tr>

<tr align=center><td>HRA</td><td><%=hra%></td><td><%=hra2%></td></tr>

<tr><th>Total Allowance:</th><td colspan=2><%=allowance%></td><tr>

<tr><th>Deductions</th><th>Percentage</th><th>Amount</th></tr>

<tr align=center><td>PF</td><td><%=pf%></td><td><%=pf2%></td></tr>

<tr align=center><td>LIC</td><td><%=lic%></td><td><%=lic2%></td></tr>

<tr><th>Total Deduction:</th><td colspan=2><%=deduction%></td><tr>

<tr><td>Gross Salary</td><td colspan=2><%=gsal%></td></tr>

<tr><td>Net Salary</td><td colspan=2><%=netsal%></td></tr>

</table></CENTER> </body></html>
6. JDBC WITH ORACLE

AIM:

To write a program using JDBC for creating a table, Inserting records and list out the records.

ALGORITHM:
Step 1: Setting Up Your MySQL User Account
Step 2: Create the Database
Step 3: Create a Java Project. File → New Project; a window will appear. Select Java from the Categories list and Java Application from the Projects list. Click Next.
Step 4: Add the Oracle JDBC Driver
Step 5: Creating the Application
Step 6: Execute the Application. Click Run→ Run Project, or press Ctrl+F11. This will compile and execute the project.

PROGRAM:

package OracleCon;

import java.sql.*;

class OracleCon{ public static void main(String args[]){ try{

//step1 load the driver class Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object

Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//step3 create the statement object

Statement stmt=con.createStatement();

//step4 execute query

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()) System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

//step5 close the connection object

con.close();

} catch(Exception e){ System.out.println(e);}

}
OUTPUT:

Oracle Database current date is 2019-03-20 14:47:01.0 BUILD SUCCESSFUL (total time: 1 second)
6. HANDLING DATA USING SERVLET

AIM :

To write a java servlet to handle form data.

ALGORITHM:

Step 1: Start the process.

Step 2: Open netbeans IDE 8.2.

Step 3: Go to file -&Click on the newproject .

Step 4: Click on the java web and then select web application.

Step 5: Enter the project name ,click on next-select the server name as Glassfish server and click finish.

Step 6: Open index.html type a coding to create simple form.

Step 7: Click on the source packages .In that select default package.

Step 8: Create a new servlet by right clicking default packages then click new option. In the pop up menu select servlet option.

Step 9: Type the code for servlet.Run the project(Right click the project , click run option (or) click the tool bar icon

Step 10: Display the output.

PROGRAM:

Index. html

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

Welcome to servlet Form handling

<br>

<br>

<form action="MyServlet">

User Name: <input type="text" name="uname"> <br> Password: <input type="password" name="pass"> <br> Email : <input type="text" name="email"> <br>

Gender : <input type="radio" name="gender" value="male" checked> Male <input type="radio" name="gender" value="female">

Female <input type="radio" name="gender" value="other"> <br> Course: <input type="checkbox" name="course" value="Java"> Java <input type="checkbox"

name="course" value="Dot Net"> Dot

Net <input type="checkbox" name="course" value="PHP"> PHP <br>

<input type="submit" value="Submit"> <input type="reset">

</form>

</body> </html>
MyServlet.java

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException

String un=request.getParameter("uname"); String pa=request.getParameter("password"); String em=request.getParameter("email");

String ge=request.getParameter("gender"); String[] co=request.getParameterValues("course"); response.setContentType("text/html"); PrintWriter

pw=response.getWriter(); pw.write("<h2>Data received successfully</h2><br>"); pw.write("<h3>User name:"+un+"</h3>"); pw.write("<h3>Password:"+pa+"</h3>");

pw.write("<h3>email:"+em+"</h3>"); pw.write("<h3>Gender:"+ge+"</h3>"); pw.write("<h3>Course"); for(String c:co)

{ pw.write(c+" ");

pw.write("</h3>");

}
7. TABLE HEADER

Aim:
To write a simple Servleprogram to create a table of all the headers it receives along with

their associated values.

ALGORITHM:

Step 1: start the process.

Step 2: open netbeans IDE 7.3.1

Step 3: Go to file -&gt; newproject .

Step 4: java -&gt;web -&gt;application.

Step 5: project name :handle next-&gt;finish.

Step 6: open.html type a coding to create simple form.

Step 7:Goto servlet -&gt; name.hdl and type alert message.

Step 8: Run the file.

Step 9: Display the output.

PROGRAM:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class NewServlet1 extends HttpServlet

public void doGet(HttpServletRequest request, HttpServletResponse response) throws

IOException, ServletException

response.setContentType("text/html"); PrintWriter out = response.getWriter();

out.println("HTTP headers sent by your client:"); out.println("<table border=1 width=50% height=50%>");

Enumeration enume = request.getHeaderNames(); while (enume.hasMoreElements())

String headerName = (String) enume.nextElement(); String headerValue = request.getHeader(headerName);

out.println("<tr><td>" + headerName + "</td><td>"); out.println("


<TD>" + request.getHeader(headerName) +"</td>" );
}

out.println("</TABLE>\n</BODY></HTML>");

}
9. SESSION OBJECT USING JSP

AIM:
To write a program in jsp by using session object.

ALGORITHM:

Step 1: start the process.

Step 2: open netbeans IDE 7.3.1

Step 3: Go to file & click newproject , give a name of the project.

Step 4: Type to start a session, Create a jsp file (index. Jsp). In the form element use the action attribute to navigate the user to the firstpage.jsp file after enter the username

and password.

Step 5: Verification of user name and password in first page.jsp file. Once the user name and password are correct , then navigate to the second page.jsp, else prompt the

user to enter the proper credentials.

Step 6: Second page.jsp displays the user name as an authorized user.

Step 7: Run the file.

Step 8: Display the output.

PROGRAM:

index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@ page isErrorPage="true" %>

<html>

<head>

<title>Session Management Example</title>

</head>

<body>

<form method="post" action="firstpage.jsp">

<font size=5>Enter your name<input type="text" name="name"></font><br><br>

<font size=5>Enter your password<input type="password" name="password">

</font><br><br>

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

</form>

</body>

</html>

Firstpage.jsp
<html>

<head>

<title>JSP Page </title>

</head>

<body>
<%

String name = request.getParameter("name");

String password = request.getParameter("password");

if (name.equals("mukesh") && password.equals("kumar"))

{ session.setAttribute("username", name); response.sendRedirect("secondpage.jsp");

else {

response.sendRedirect("index.jsp");

%>

</body>

</html>

Secondpage.jsp
<html>

<head>

<title>Welcome in the program of session</title>

</head>

<body>

<font size = 5>Hello <%= session.getAttribute("username") %> you are an authorized person</font>

</body>

</html>
10.CLIENT SERVER APPLICATION USING RMI

AIM:

To write a program to build a simple client server application using RMI.

ALGORITHM:

Step 1:Start the process.

Step 2:Open NetBeans IDE 7.3.1.

Step 3: Create the remote interface.

Step 4:Provide the implementation of the remote interface.

Step 5:Compile the implementation class and create the stub and skeleton object using the RMI tool.

Step 6:Start the registry service by RMI registery tool.

Step 7: Create and start the remote and client application.

Step 8:Compile and execute the application.

Step 9:Stop the process.

PROGRAM:

AddRem.java
public interface AddRem extends Remote
{
public int addNum(int n1,int n2)throws RemoteException;
}

AddRemImpl.java
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class AddRemImpl extends UnicastRemoteObject implements AddRem
{
public AddRemImpl() throws RemoteException{} public int addNum(int a,int b)
{
return(a+b);
}
}

server.java
import java.rmi.*;
import java.rmi.registry.Registry; import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject; import java.rmi.RemoteException;
public class server extends UnicastRemoteObject implements AddRem{
public server() throws RemoteException
{
super();
}
public int addNum(int n1,int n2)throws RemoteException
{
return n1+n2;
} public static void main(String
args[]){ try{
Registry reg=LocateRegistry.createRegistry(9999); reg.rebind("hi server", new server()); System.out.println("Server is running");
}
catch(Exception e){System.out.println(e);
}
}
}

Client.java
public class client
{
public static void main(String args[]) throws RemoteException, NotBoundException
{ client c=new client(); c.connectRemote();
}
private void connectRemote()throws RemoteException, NotBoundException
{
try{
Registry reg=LocateRegistry.getRegistry("localhost", 9999); AddRem ad=(AddRem)reg.lookup("hi server"); System.out.println("Addition is :"+ad.addNum(34,4));
}
catch(RemoteException e){ System.out.println(e);
}
}
}

OUTPUT:

Addition is 38.
11. CALCULATOR USING APPLET
AIM:
To create an applet for a calculator application.

ALGORITHM:

Step 1: – Create a blank Java project and name it Java Calculator. Uncheck the Main class option from the project tab.

Step 2: – To add a Jframe, right click the project name in the Project window.

Step 3: – To the right of the Jframe, there is a Palette with a set of controls on it. Click the Text Field and apply it on the blank Field form.

Step 4: – Select the Button and drag it to the Jframe form. Change the text and the Variable Name as we did for the text field.

Step5: – Change the Variable Name to btnOne as we did for the text Field. Enter the value 1 for the text by selecting the properties. Do the same for all the buttons by

changing the text and

the Variable Name.

Step6: – Double click on any of the button. This will take the user to the source section where the major coding of the program is done.

Step7: – Declare the following variables inside the main class.

SOURCE CODE:

package simplecalc;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Button;
import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Simplecalc extends Applet implements ActionListener {
public static final String[] TEXT = {"AC", "BSp", "%", "/", "7", "8", "9", "*", "4", "5", "6", "-",
"1", "2", "3", "+", "RSET", "0", ".", "="};
TextField t1;
TextField t2;
StringBuffer value = new StringBuffer(); public void init() {
Frame title = (Frame) this.getParent().getParent(); title.setTitle("Simple Calculator");
setLayout(null);
t1 = new TextField("", 4);
t1.setBounds(50, 10, 200, 50);
add(t1);
t2 = new TextField("", 4);

t2.setBounds(50, 60, 200, 50);


add(t2);
int x = 50; int y = 115;

int k = 1;
Button b[] = new Button[20];
for (int i = 0; i < TEXT.length; i++) { b[i] = new Button("" + TEXT[i]);
b[i].setBounds(x * k, y, 50, 50);
if (k % 4 == 0) { x = 50;
y += 50;
k = 0;
} k++;
add(b[i]); b[i].addActionListener(this);

}
}
public void paint(Graphics g) {
}
public void actionPerformed(ActionEvent e) { String s = e.getActionCommand();
if (s.equalsIgnoreCase("=")) { System.out.println("generating result"); t1.setText(calculate(value)); value.setLength(0);
} else if (s.equalsIgnoreCase("AC")) { System.out.println("AC: Resetting Input"); value.setLength(0);
t2.setText("");
} else if (s.equalsIgnoreCase("BSp")) { System.out.println("BSp: Erasing a character"); value.setLength(value.length() - 1); t2.setText(value.toString());
} else if (s.equalsIgnoreCase("RSET")) { System.out.println("Reset: Resetting Input output "); value.setLength(0);
t1.setText("");
t2.setText("");
} else {
value.append(s); t2.setText(value.toString());
}
}
public String calculate(StringBuffer sb) { ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); Object
result = null;
try {
result = engine.eval(sb.toString()); System.out.println(result);
} catch (ScriptException ex) {
System.out.println("Exception : Check again your operator sequence"); result = "Error";
}
return result.toString();
}
}
12.CLIENT AND SERVER (SOCKET)

AIM:

To write a program to send a text message to another system and receive the text message from the system (use socket programming)

ALGORITHM:

Step1: Open Netbeans IDE.

Step2: Select file – new project.

Step3: Select java – java application.

Step4: Select next – give project name: MyClient.

Step5: Click next – finish.

Step6: Type coding to send a message to server.

Step7: Declare a variable.

Step8: Make a connection using socket class and close the class.

Step9: Select file – new project- java-java application.

Step10: Give project name: MyServer - finish.

Step11: Type coding to receive a message from client.

Step12: Make a connection using server socket class.

Step13: Display a message and close class.

PROGRAM:

Myserver.java import java.io.*;

import java.net.*;

public class MyServer

public static void main(String[] args)

try

ServerSocket receive=new ServerSocket(6666); Socket s=receive.accept();//establishes connection

DataInputStream dis=new DataInputStream(s.getInputStream()); String str=(String)dis.readUTF(); System.out.println("message="+str);

dis.close(); s.close(); receive.close();

}catch(Exception e){System.out.println(e);}

}
Myclient.java

import java.io.*;

import java.net.*;

public class MyClient {

public static void main(String[] args) { try{

//String msg;

Socket sendsocket=new Socket("localhost",6666);

DataOutputStream dout=new DataOutputStream(sendsocket.getOutputStream()); dout.writeUTF("Hello Server"); dout.flush(); dout.close(); sendsocket.close();

catch(Exception e){System.out.println(e);}

OUTPUT:

You might also like