You are on page 1of 49

3.1.1.

STRUTS WEB FRAMEWORK


Aim:
To build a simple MVC application that displays a login page and returns a
success page upon submitting data that passes validation.

1. Procedure:
2. Choose File | New Project.
3. Under Categories, select Web. Under Projects, select Web Application and
click Next 

4. On this page, under the Project Name section, type login and select the


location of the project. Click Next.
5. In the next panel, you can choose the server that will host this application,
the Java EE version and the context path. For this example, choose
GlassFish v3 server, Java EE 6 Web and do not modify the default context
path. Click Next.
6. In the Frameworks panel, select Struts 1.3.8  This is a major step because
you indicate to NetBeans your intention to use Struts. Click Finish
Creating the Login.jsp Page from WelcomeStruts.jsp
1. Rename the welcomeStruts.jsp page by right clicking on its name in
the Projects tab (under the Web Pages folder) and chooseRename. Type the
new name without an extension and press OK.
2. Go to index.jsp and modify the redirect to login.jsp like this:
<jsp:forward page="Login.do"/>
3. Open the struts-config.xml file and navigate to the Global
Forwards section. Notice that you can navigate to any section from this
descriptor by using the NetBeans Navigator, which automatically appears by
default in the lower-lefthand corner.
Figure : NetBeans IDE Navigator Panel

4. Modify the single global forward like this:


<global-forwards>
<forward name="login" path="/Login.do"/>
</global-forwards>

5. Navigate to the Action Mappings section and modify the single action like
this:
<action-mappings>
<action path="/Login" forward="/login.jsp"/>
</action-mappings>

Now that you have completed the renaming and fixed the navigation to
your login.jsp page, it's time to add some real content to it. In this case, you will
render a simple login form mapped in a simple HTML table (note that you can
speed up the development of this table by using the NetBeans Palette if it is not
clear that you can activate it from the Window menu).

When you type in the Source Editor, NetBeans provides you with code completion
for Struts tags, as well as the Struts Javadoc. You can also invoke code completion
manually by pressing Ctrl-Space. Figure 4 presents a simple capture of inserting a
Struts form into your page.
 
 
Figure . Sample of Struts Code Completion and Javadoc

Now, the login.jsp page code looks like this (typical Struts application


code):

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<html:html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login page</title>
</head>
<body style="background-color: white">
<html:form action="/login">
<html:errors property="wrongemail" />
<html:errors property="wrongpass" />
<table border="1">
<thead>
<tr>
<th>Login to your site</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Email:</td>
<td><html:text property="email" /></td>
</tr>
<tr>
<td>Password:</td>
<td><html:password property="pass" /></td>
</tr>
</tbody>
</table>
<html:submit value="Login" />
</html:form>
</body>
</html:html>

Creating the Success.jsp Page
When the user has successfully logged in, you must redirect the application
flow to the requested page. In this case, you render a success.jsp page, which is a
very simple confirmation of the login credentials. Follow these steps:
1. Create a new JSP page. In the Projects tab, expand the login project and
right-click on the Web Pages folder. Select the New | JSP ... option from the
contextual menu and type "success" in the File Name section of the New JSP
File wizard. Press Finish.
2.
2. Modify the generated code like below (remember to explore the NetBeans
Palette, code completion for Struts tags and Struts Javadoc):
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Successfully</title>
</head>
<body>
<h1>Login Successfully Done</h1>
<p>Email: <bean:write name="LoginActionForm" property="email"
/>.</p>
<p>Password: <bean:write name="LoginActionForm" property="pass"
/>.</p>
</body>
</html>

Creating the Failure.jsp Page
When the provided credentials are wrong, you redirect the application flow
to a page calledfailure.jsp. This is generated in the same manner as success.jsp and
it looks like this:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Failure</title>
</head>
<body>
<h1>Login Failure</h1>
<p>Email: <bean:write name="LoginActionForm" property="email" />.</p>
<p>Password: <bean:write name="LoginActionForm" property="pass" />.</p>
</body>
</html>

Creating an ActionForm Bean


A Struts ActionForm bean is perfect for storing the provided credentials
between requests (or any data provided through a form). Since you need to store
the email and the password, which are two strings, your bean will be pretty short
and simple (note that in Struts parlance, "an ActionForm is a JavaBean optionally
associated with one or more ActionMappings. Such a bean will have had its
properties initialized from the corresponding request parameters before the
corresponding Action.executemethod is called."). Here are the steps for creating it:
1. In the Projects tab, right-click on the login project and select New |
Other ... from the contextual menu.
2. In the New File wizard's Categories list, select the Struts category, and
from the File Typeslist, select the Struts ActionForm Bean type and
press Next (see Figure 5).
 
 
Figure:. Adding a Struts ActionForm Bean

3. Now you have to type a name for the new action form. For example, type
"LoginActionForm" in the Class Name section. Also, choose
the com.myapp.struts package from the Package list (see Figure 6).
Click Finish.

Figure:  Configure Struts ActionForm Bean

4. When you press the Finish button, NetBeans will generate the new action
form for you and display it in the Source Editor. By default, this class
provides it with a String called name and an int called number, along with
getter/setter methods for them called delete all, because you need to add the
email and the password! Also, if you check the struts-config.xml, you can
see the new form bean added under the Form Beans section:
<form-bean name="LoginActionForm"
type="com.myapp.struts.LoginActionForm"/>

5. In the LoginActionForm, add two properties like this:


private String email;
private String pass;

6. Add getter/setter methods for these two properties. Go below this code and
right-click in an empty spot. From the contextual menu, select Insert
Code ... and Getter and Setter .... In the Generate Getters and
Setters window, select the two properties and press Generate. Now, you
should see the corresponding methods in your code.
For now, comment the validate method and read further. You will deal with this
method in validation section.

Implementing the Business Logic in Struts Style


Next task is to generate an Action class and implement the executemethod.
In Struts parlance: "when a request is received, the Controller invokes
anAction class. The Action class consults with the Model (or, preferably, a
Facade representing your Model) to examine or update the application's state."
Theexecute method is the "brain" of your application, because here you tell the
application what to do.

1. In the Projects tab, right-click on the login project and select New |


Other ... from the contextual menu.
2. In the New File wizard's Categories list, select the Struts category and
from the File Typeslist, select Struts Action type and press Next.
3. Now you have to type a name for the new action. For example,
type LoginAction in the Class Name section. Also, choose
the com.myapp.struts package from the Package.
4. Type /login in the Action Path section. This value must be the same as the
one provided in the action attribute of the <html:form> tag in login.jsp.
Click Next.
5. In this window, you have to associate the Action with an ActionForm. By
default, the IDE did that for you, but notice that this can be accomplished
manually by selecting the correspondingActionForm from the
list ActionForm Bean Name.
6. In addition:
 Type /login.jsp for the Input Resource field, or use
the Browse button.
 Set the Scope to Request.
. Click Finish.

Now, you should see the generated code of your action in the Source Editor. If
you look in struts-config.xml, you will notice the new added entry under Action
Mappings, like this:

<action input="/login.jsp" name="LoginActionForm" path="/login"


scope="request" type="com.myapp.struts.LoginAction"/>

Going further, you must add a behavior to the execute method. You have a


simple scenario: the login credentials should be an email address of
"admin@ucen.com" and a password of "admin123." If the provided credentials
match these, then you forward the user tosuccess.jsp, if not to failure.jsp. The code
looks like this after you have used the generated code and added the needed lines:

/* forward name="success" path="" */


private static final String SUCCESS = "success";
private static final String FAILURE = "failure";

/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request you are processing.
* @param response The HTTP Response you are processing.
* @throws java.lang.Exception
* @return
*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginActionForm data = (LoginActionForm)form;
String email = data.getEmail();
String pass = data.getPass();
if ((email.equals("admin@yahoo.com")) && (pass.equals("admin"))){
return mapping.findForward(SUCCESS);
} else {
return mapping.findForward(FAILURE);
}
}

Configure the Forwards Entries


As you can see, your action class contains two forwarding
conditions, SUCCESS and FAILURE. In this section, you configure these
forwards in the struts-config.xml file as follows (Without these configurations,
Struts will not know what JSP pages to associate to the forwarding conditions. You
know that SUCCESS should be associated
to success.jsp and FAILURE to failure.jsp, and now Struts will also know that.):
1. In struts-config.xml, right-click anywhere in the action entry
for LoginActionForm and choose Struts | Add Forward from the contextual
menu (notice that in this contextual menu you have an entire set of Struts
components that can be added through the IDE wizards).

2. In the Forward Name section, type "success." In the Resource File,


type /success.jsp or use the Browse button to navigate to this page (see
Figure 7). Click Add.
 
Figure : Add a Struts Forward

Repeat this process for FAILURE, but select the /failure.jsp page and type


"failure" in the Forward Name section. Now, in struts-config.xml, you should have
this:

<action input="/login.jsp" name="LoginActionForm"


path="/login" scope="request" type="com.myapp.struts.LoginAction">
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/failure.jsp"/>
</action>

Implementing the Validate Method of the LoginActionForm


Bottom of LoginActionForm, you have a validate method generated by the
IDE (you will find a comment there, which you have to uncomment first). This
method allows you to put more reusable validation in ActionForm and return non-
empty ActionErrors from validate to trigger redisplay of input data.

Next, you add a basic validation over the provided login credentials:
@Override
public ActionErrors validate(ActionMapping mapping, HttpServletRequest
request) {
ActionErrors errors = new ActionErrors();
if (getEmail() == null || getEmail().length() < 6) {
errors.add("wrongemail", new ActionMessage("errors.email", "This email"));
}
if (getPass() == null || getPass().length() < 5) {
errors.add("wrongpass", new ActionMessage("errors.minlength",
"Password", "6"));
}
return errors;
}

Output:

 
Figure: Running the Login Application Sample
Result:
Thus the simple MVC application that displays a login page and returns a
success page upon submitting data that passes validation executed successfully.
2.1.1. HTTP REQUEST

Aim:
To write a java socket program to demonstrate HTTP Request.

Algorithm:
 Import all the necessary packages
 Create an URL to the server specifying the html page
 Get the host and port details from the URL
 Request the file from the server using GET method of HTTP Request
 Receive the response from the server
 Display the response on the console

Program:
HTTP SERVER:(https.java)
import java.io.*;
import java.net.*;
import java.lang.*;
public class https
{
public static void main(String args[]) throws Exception
{
ServerSocket ssoc=new ServerSocket(1111);
System.out.println("Server waits for client:\n");
Socket so=ssoc.accept();
System.out.println("client connected to Server :\n");

BufferedReader br=new BufferedReader(new


InputStreamReader(so.getInputStream()));

PrintWriter pw=new PrintWriter(so.getOutputStream(),true);


BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

int ch;
do
{
ch=Integer.parseInt(br.readLine());
String file;
byte line[]=null;
File f;
switch(ch)
{
case 1: System.out.println("1.head");
file=br.readLine();
f=new File(file);
int index=file.lastIndexOf(".");
String type=file.substring(index+1);
pw.println(type);
long length=f.length();
pw.println(length);
break;
case 2: System.out.println("2.post");
file=br.readLine();
System.out.println("message from client:\n");
System.out.println(file);
break;
case 3: System.out.println("3.get");
file=br.readLine();
FileInputStream fs=new FileInputStream(file);
while(fs.available()!=0)
{
if(fs.available()<1024)
line=new byte[fs.available()];
else
line=new byte[1024];
fs.read(line);
file=new String(line);
pw.println(file);
}
pw.println("***");
fs.close();
break;
case 4: System.out.println("4.delete");
file=br.readLine();
f=new File(file);
f.delete();
break;
default: System.out.println("5.exit");
System.exit(0);
}
}
while(ch<=4);
so.close();
ssoc.close();
}
}
HTTP CLIENT: (httpc.java)
import java.io.*;
import java.net.*;
import java.lang.*;
public class httpc
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket("localhost",1111);
BufferedReader br=new BufferedReader(new InputStreamReader(soc.getInputStream()));

PrintWriter pw=new PrintWriter(soc.getOutputStream(),true);

BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

System.out.println("server is connected:\n");
int ch;
do
{
System.out.println("COMMANDS");
System.out.println("\n 1.head \n 2.post \n 3.get \n4.delete\n 5.exit");
System.out.println("ENTER UR CHOICE:");
ch=Integer.parseInt(in.readLine());
byte line[]=null;
String file;
switch(ch)
{
case 1:pw.println("1");
file=in.readLine();
pw.println(file);
String type=br.readLine();
String length=br.readLine();
System.out.println("FILE:"+file+"\nTYPE:"+type+"\nLEN GTH:"+length);
break;

case 2: pw.println("2");
System.out.println("enter text to post");
file=in.readLine();
pw.println(file);
System.out.println("text is posted at server");
break;
case 3:pw.println("3");
System.out.println("enter file name to get");
file=in.readLine();
pw.println(file);
System.out.println("enter file name to save:");
file=in.readLine();
FileOutputStream fs=new FileOutputStream(file);
while(true)
{
String s=br.readLine();
if(s.equals("***"))
break;
int count=s.length();
if(count<1024)
line=new byte[1024];
line=s.getBytes();
fs.write(line);
}
fs.close();
System.out.println("\n file successfully tranfered:");
break;

case 4: pw.println("4");
System.out.println("enter the file to delete:");
file=in.readLine();
pw.println(file);
System.out.println("given file deleted:");
break;
default: pw.println("5");
System.exit(0);
}
}
while(ch<=4);
soc.close();
}
}
OUTPUT:
HTTP SERVER:
HTTP CLIENT:
Result:
Thus the java socket program to demonstrate HTTP Request has been
executed successfully.
2.1.2 FTP – FILE TRANSFER PROTOCOL

Aim:
To write a java program to demonstrate a simple FTP operation.

Algorithm:

Procedure:
FTP Client:
Step 1: Establish a connection with the server at a particular port
Step 2: Specify the name of the file to be read
Step 3: Receive the contents of the file from the server
FTP Server:
Step 1: Accept the connection with the client
Step 2: Listen to the port for the name of the file to be sent
Step 3: Send the file character by character
Step 4: Terminate the connection

Program:
FTP SERVER:(ftpserver.java)
import java.net.*;
import java.io.*;
public class ftpserver
{
public static void main(String args[])
{
Socket s;
ServerSocket server;
FileInputStream fis;
BufferedReader br;
PrintWriter pw;
String filename;
int c;
try
{
server = new ServerSocket(1111);
System.out.println("Server waitfor for connection:\n");
s = server.accept();
System.out.println("Connection established:\n");
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream());
filename = br.readLine();
fis = new FileInputStream(filename);
while ((c=fis.read())!=-1)
{
pw.print((char)c);
pw.flush();
}
System.out.println(filename + " copied to destnation");
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
FTP CLIENT:(ftpclient.java)
import java.net.*;
import java.io.*;
public class ftpclient
{
public static void main (String args[])
{
Socket s;
BufferedReader in, br;
PrintWriter pw;
String spath,dpath;
FileOutputStream fos;
int c;
try
{
s = new Socket ("localhost",1111);
in = new BufferedReader (new InputStreamReader (System.in));
br = new BufferedReader (new InputStreamReader (s.getInputStream()));

pw = new PrintWriter(s.getOutputStream(), true);


System.out.println("\nEnter Sourcepath to copy file : ");
spath = in.readLine();
System.out.println("\nEnter DestinationPath to transfer : ");
dpath = in.readLine();
fos = new FileOutputStream(dpath);
pw.println (spath);
while ((c=br.read())!=-1)
{
fos.write((char)c);
fos.flush();
}
System.out.println("File trasfer completed:\n");
}
catch (Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
Result:
Thus the java program to demonstrate a simple FTP operation has been
executed successfully.
2.1.3. SMTP-SIMPLE MAIL TRANSFER PROTOCOL

Aim:
To write a java socket program to implement a simple SMTP client.

Algorithm:
Step 1: Import all necessary packages
Step 2: Establish a connection with the server
Step 3: Read the acceptance from the server
Step 4: Say HELO to the server
Step 5: Read the greeting from the server
Step 6: Send sender address to server
Step 7: Read the verification of sender from server
Step 8: Send recipient address to server
Step 9: Read the verification of recipient from server
Step 10: Send DATA command to the server
Step 11: Read the start indication from server
Step 12: Send the message to the server
Step 13: Read the acceptance of message from server
Step 14: Close the connection

Program:
/*import the packages needed for email and gui support*/
import java.net.*;
import java.io.*;
importjava.awt.*;
importjava.awt.event.*;
/*** This class defines methods that display the gui and handle the sending of
*mails to the Mail server. */
public class SMTP extends WindowAdapter implements ActionListener
{
private Button sendBut = new Button("Send Message");
private Label fromLabel = new Label(" From : ");
private Label toLabel = new Label(" To : ");
private Label hostLabel = new Label("Host Name : ");
private Label subLabel = new Label(" Subject : ");
privateTextFieldfromTxt = new TextField(25);
privateTextFieldtoTxt = new TextField(25);
privateTextFieldsubTxt = new TextField(25);
privateTextFieldhostTxt = new TextField(25);
privateTextAreamsgTxt = new TextArea();
private Frame clientFrame = new Frame("SMTP Client");
/*** Constructor with takes no parameters.
* this constructor displays the window for the user to assist in sending emails. */
public SMTP()
{
clientFrame.setLayout(new GridLayout(2,1));
Panel p1 = new Panel();
p1.setLayout(new GridLayout(4,1));
Panel p11 = new Panel();
p11.setLayout(new FlowLayout());
p11.add(hostLabel);
p11.add(hostTxt);
Panel p12 = new Panel();
p12.setLayout(new FlowLayout());
p12.add(fromLabel);
p12.add(fromTxt);
Panel p13 = new Panel();
p13.setLayout(new FlowLayout());
p13.add(toLabel);
p13.add(toTxt);
Panel p14 = new Panel();
p14.setLayout(new FlowLayout());
p14.add(subLabel);
p14.add(subTxt);
p1.add(p11);
p1.add(p12);
p1.add(p13);
p1.add(p14);
Panel p2 = new Panel();
p2.setLayout(new BorderLayout());
p2.add(msgTxt,BorderLayout.CENTER);
Panel p21 = new Panel();
p21.setLayout(new FlowLayout());
p21.add(sendBut);
p2.add(p21,BorderLayout.SOUTH);
clientFrame.add(p1);
clientFrame.add(p2);
clientFrame.setSize(400,500);
clientFrame.setVisible(true);
clientFrame.addWindowListener(this);
sendBut.addActionListener(this);
}
/** * This method is triggered when the close button of a window
* is closed. The method exits the application. */
public void windowClosing(WindowEvent we)
{
clientFrame.setVisible(false);
System.exit(1);
}
/** * This method is called in response to button clicks.
* The method reads the message to be sent, packs it in
* a Message object and sends it to the mail server. */
public void actionPerformed(ActionEventae)
{
try
{
Socket s=new Socket(hostTxt.getText(),25);
BufferedReaderbr=new BufferedReader(new
InputStreamReader(s.getInputStream()));
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
System.out.println("Connection is established");
pw.println("HELLO");
System.out.println(br.readLine());
pw.println("MAIL From:"+fromTxt.getText());
System.out.println(br.readLine());
pw.println("RCPT To:"+toTxt.getText());
System.out.println(br.readLine());
pw.println("DATA");
pw.println(msgTxt.getText()+"\n.\n");
System.out.println(br.readLine());
pw.println("QUIT");
pw.flush();
s.close();
System.out.println("Mail has been sent....");
}
catch(Exception e)
{
}
System.out.println("Connection Terminated");
}

/*** This is the main method . It instantiates an object of thisclass (SMTPClient) and adds
listeners for the frame windowand the buttons used in the gui. */
public static void main(String args[])
{
SMTP client = new SMTP();
}
}
Result:
Thus the Java socket program to implement a simple SMTP client has been
executed successfully.
2.1.4. POP3- Post Office Protocol

Aim:
To write a java socket program to implement a POP3 Client.

Algorithm:
Step 1: Get the host name, mailbox user name and password
Step 2: Establish the connection with the server
Step 3: Get the number of messages
Step 4: Retrieve a message whose number is specified by the user
Step 5: Repeat steps 3 and 4 until the user enters Q to quit

Program:
import java.io.*;
import java.net.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class POPClient extends Frame implements ActionListener
{
TextField user,pass,host,msgno;
TextArea msgta;
Button signin,disp,prev,next,exit;
int no_of_msg,n;
String str;
BufferedReader br1,br2;
PrintWriter pw;
Socket s=null;
publicPOPClient()
{
super("POP");
user=new TextField(20);
pass=new TextField(20);
host=new TextField(20);
msgno=new TextField(20);
msgta=new TextArea("",10,50);
signin=new Button("LOGIN");
disp=new Button("DISPLAY");
next=new Button("NEXT");
prev=new Button("PREVIOUS");
exit=new Button("EXIT");
no_of_msg=0;
str=" ";
n=0;
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
Panel p4 = new Panel();
setLayout(new GridLayout(3,1));
setSize(400,400);
p1.setLayout(new GridLayout(4,1));
Panel p11 = new Panel();
p11.add(new Label("User Name : "));
p11.add(user);
Panel p12 = new Panel();
p12.add(new Label("Password : "));
p12.add(pass);
Panel p13 = new Panel();
p13.add(new Label("Host Name : "));
p13.add(host);
Panel p14 = new Panel();
p14.add(signin);
p1.add(p11);
p1.add(p12);
p1.add(p13);
p1.add(p14);
p3.setLayout(new GridLayout(1,1));
p3.add(msgta);
p4.setLayout(new GridLayout(3,1));
Panel p41 = new Panel();
p41.add(new Label("Enter message number :"));
p41.add(msgno);
Panel p42 = new Panel();
p42.add(disp);
p42.add(new Label(" "));
p42.add(prev);
Panel p43 = new Panel();
p43.add(next);
p43.add(new Label(" "));
p43.add(exit);
p4.add(p41);
p4.add(p42);
p4.add(p43);
add(p1);
add(p4);
add(p3);
setVisible(true);
pass.setEchoChar('*');
signin.addActionListener(this);
disp.addActionListener(this);
prev.addActionListener(this);
next.addActionListener(this);
exit.addActionListener(this);
}

public void actionPerformed(ActionEventae)


{
try
{
if(ae.getSource()==signin)
{
s=new Socket(host.getText(),110);
br1=new BufferedReader(new
InputStreamReader(s.getInputStream()));
pw=new PrintWriter(s.getOutputStream(),true);
msgta.append(br1.readLine());
System.out.println("1");
pw.println("user "+user.getText());
System.out.println("2");
msgta.append("\n"+br1.readLine());
pw.println("PASS "+pass.getText());
System.out.println("3");
msgta.append("\n"+br1.readLine());
pw.println("list");
str=br1.readLine();
msgta.append("\n"+str);
StringTokenizerst=new StringTokenizer(str);
String tmpstr=st.nextToken();
tmpstr=st.nextToken();
no_of_msg=Integer.parseInt(tmpstr);
while(!(br1.readLine().equals(".")));
}
if(ae.getSource()==disp)
{
n=Integer.parseInt(msgno.getText());
display();
}
if(ae.getSource()==next)
{
n++;
display();
}
if(ae.getSource()==prev)
{
n--;
display();
}
if(ae.getSource()==exit)
{
if(s!=null)
s.close();
System.out.println("Connection terminated....");
System.exit(1);
}
}
catch(Exception c)
{
System.out.println(c);
}
}
void display()
{
msgta.setText("");
msgno.setText(String.valueOf(n));
if(n>0&&n<=no_of_msg)
{
System.out.println("N:"+n);
pw.println("retr "+n);
do
{
try
{
str=br1.readLine();
}
catch (Exception e)
{}
System.out.println("msg"+str);
msgta.append("\n"+str);
}while(!str.equals("."));
}
else
msgta.setText("You have "+no_of_msg+" mails");
}

public static void main(String args[])


{
POPClient p=new POPClient();
}
}
Result:
Thus the java socket program to implement a POP3 Client has been
executed successfully.
3.1.3. Web Application Using Spring

Aim:

To Implement a simple program using Spring.

Procedure:
Creating a Spring Web MVC Skeleton Project
Start by creating a new project for a web application using the Spring Framework.
1. Choose New Project from the IDE's File menu. Select the Java Web category, then
under Projects select Web Application. Click Next.
2. In Project Name, type in HelloSpring. Click Next.
3. In Step 3: Server and Settings, deselect the Enable Contexts and Dependency
Injection option. Confirm that the GlassFish server is selected in the Server drop-
down list. Click Next.
4. In Step 4, the Frameworks panel, select Spring Web MVC.
5. Select Spring Framework 3.x in the Spring Library drop-down list. 

Deselect JSTL option.


6. Click the Configuration tab and note that the wizard enables you to specify the
name and mapping of the Spring Dispatcher servlet. 

7. Click Finish.
Implementing a Service
1. Click the New File (   ) button in the IDE's toolbar
2. Select the Java category, then select Java Class and click Next.
3. In the New Java Class wizard that displays, type in HelloService for Class Name,
and enter service for Package Name to create a new package for the class.
4. Click Finish. The IDE creates the new class and opens it in the editor.
The HelloService class performs a very simple service. It takes a name as a parameter,
and prepares and returns a String that includes the name. In the editor, create the
following sayHello() method for the class (changes in bold).

public class HelloService {

public static String sayHello(String name) {


return "Hello " + name + "!";
}
}
Implementing the Controller and Model
1. Open the New File wizard by pressing Ctrl-N. Under Categories select Spring
Framework; under File Types select Simple Form Controller. 
 

2. Click Next.
3. Name the class HelloController and create a new package for it by
typing controller in the Package text field. Click Finish. The IDE creates the new
class and opens it in the editor.
4. Specify controller properties by uncommenting the setter methods that display by
default in the class template. To uncomment the code snippet, highlight the code
as in the image below, then press Ctrl-/ . 

 
Pressing Ctrl-/ toggles comments in the editor.
5. Make changes as follows (shown in bold).
public HelloController()
{
setCommandClass(Name.class);
setCommandName("name");
setSuccessView("helloView");
setFormView("nameView"); }
Note that an error is flagged for Name in the setCommandClass() method:

You now need to create the Name class as a simple bean to hold information for
each request.
6. In the Projects window, right-click on the project node and choose New > Java
Class. The New Java Class wizard displays.
7. Enter Name for the Class Name, and for Package select controller from the drop-
down list.
8. Click Finish. The Name class is created and opens in the editor.
9. For the Name class, create a field named value, then create accessor methods (i.e.,
getter and setter methods) for this field. Start by declaring the value field:
public class Name { private String value; }

In the editor, right-click on value and choose Insert Code. In the popup menu,
choose Getter and Setter. 

10. In the dialog that displays, select the value : String option, then click OK.
The getValue() and setValue() methods are added to the Name class:
public String getValue()
{
return value;
}
public void setValue(String value)
{
this.value = value;
}
11. Choose HelloController to switch back to the HelloController class.
12. Delete the doSubmitAction() method and uncomment the onSubmit() method.
The onSubmit() method enables you to create your own ModelAndView, which is
what is required here. Make the following changes:
@Override
protected ModelAndView onSubmit(
HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException errors) throws Exception {

Name name = (Name) command;


ModelAndView mv = new ModelAndView(getSuccessView());
mv.addObject("helloMessage", helloService.sayHello(name.getValue()));
return mv;
}

13. Fix import errors by right-clicking in the editor and choosing Fix Imports. 

Note. Confirm
that org.springframework.validation.BindException and org.springframework
.web.servlet.ModelAndView are selected in the Fix All Imports dialog box.
14. Click OK. The following import statement is added to the top of the file:
import org.springframework.web.servlet.ModelAndView;
15. Within HelloController, declare a private field named HelloService:
private HelloService helloService;

Then create a public setter method for the field:


public void setHelloService(HelloService helloService)
{
this.helloService = helloService;
}
Finally, right-click in the editor and choose Fix Imports. The following statement
is added to the top of the file:
import service.HelloService;
All errors should now be fixed.
16. Register HelloService in applicationContext.xml. Open applicationContext.xml in
the editor and enter the following bean declaration:
<bean name="helloService" class="service.HelloService" />

17. Register HelloController in dispatcher-servlet.xml. Open dispatcher-servlet.xml in


the editor and enter the following bean declaration:
<bean class="controller.HelloController" p:helloService-ref="helloService"/>
Implementing the Views
To implement the view for this project, you need to create two JSP pages. The first,
which you will call nameView.jsp, serves as the welcome page and allows users to input
a name. The other page, helloView.jsp, displays a greeting message that includes the
input name. Begin by creating helloView.jsp.
1. In the Projects window, right-click the WEB-INF > jsp node and choose New >
JSP. The New JSP File wizard opens. Name the file helloView.
2. Click Finish. The new JSP page is created in the jsp folder and opens in the editor.
3. In the editor, change the file's title to Hello, and change the output message to
retrieve the helloMessage of the ModelandView object that is created
inHelloController.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello</title>
</head>
<body>
<h1>${helloMessage}</h1>
</body>
4. Create another JSP page in the same manner as above, but name it nameView.
5. In the editor, add the following Spring tag library declaration to nameView.jsp.
<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
This imports the Spring tag library, which contains tags useful when implementing
views as JSP pages.
6. Change the contents of the <title> and <h1> tags to read: Enter Your Name.
7. Enter the following code beneath the <h1> tags:
<spring:nestedPath path="name">
<form action="" method="post">
Name:
<spring:bind path="value">
<input type="text" name="${status.expression}" value="${status.value}">
</spring:bind>
<input type="submit" value="OK">
</form>
</spring:nestedPath>

spring:bind allows you to bind a bean property. The bind tag provides a bind status
and value, which you use as the name and value of the input field

spring:nestedPath enables you to prepend a specified path to a bean. So, when


used with spring:bind as shown above, the path to the bean becomes:name.value..
8. In the Projects window, right-click the project node and choose Properties. The
Project Properties dialog displays. Under Categories select Run. In the Relative
URL field, type in /hello.htm, then click OK. 

At this moment you may wonder where the mapping


of hello.htm to HelloController is located. You have not added a mapping to
the urlMapping bean, as is the case for index.htm, the skeleton project's welcome
page. This is possible with a bit of Spring magic provided by the following bean
definition in dispatcher-servlet.xml:
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandl
erMapping"/>
This bean is responsible for automatically creating an URL mapping for all
controllers registered in the file. It takes the fully-qualified class name of the
controller (in our case, controller.HelloController) and strips the package name
and Controller suffix, then uses the result as a URL mapping. Therefore,
forHelloController it creates a hello.htm mapping. This magic however does not
work for controllers that are included in the Spring Framework, such
asParameterizableViewController. They require an explicit mapping.
9. In the Projects window right-click the project node and choose Run. This
compiles, deploys and runs the project. Your default browser opens,
displaying hello.htm as the project's nameView: 
Output: 

Result:
Thus a simple web MVC application using the Spring Framework has been
executed successfully.

You might also like