Professional Documents
Culture Documents
1. Procedure:
2. Choose File | New Project.
3. Under Categories, select Web. Under Projects, select Web Application and
click Next
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
<%@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>
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.
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"/>
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.
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:
/**
* 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);
}
}
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");
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()));
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()));
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);
}
Aim:
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.
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).
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 {
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;
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
Result:
Thus a simple web MVC application using the Spring Framework has been
executed successfully.