Wednesday, 6 April 2016

STRUTS 2 FRAMEWORK

The struts 2 framework is used to develop MVC-based web application.
The struts framework was initially created by Craig McClanahan and donated to Apache Foundation in May, 2000 and Struts 1.0 was released in June 2001.
The current stable release of Struts is Struts 2.3.16.1 in March 2, 2014.
This struts 2 tutorial covers all the topics of Struts 2 Framework with simplified examples for beginners and experienced persons.

Struts 2 Framework

The Struts 2 framework is used to develop MVC (Model View Controller) based web applications. Struts 2 is the combination ofwebwork framework of opensymphony and struts 1.
  1. struts2 = webwork + struts1  
The Struts 2 provides supports to POJO based actions, Validation Support, AJAX Support, Integration support to various frameworks such as Hibernate, Spring, Tiles etc, support to various result types such as Freemarker, Velocity, JSP etc.
Struts 2 provides many features that were not in struts 1. The important features of struts 2 framework are as follows:
  1. Configurable MVC components
  2. POJO based actions
  3. AJAX support
  4. Integration support
  5. Various Result Types
  6. Various Tag support
  7. Theme and Template support

1) Configurable MVC components

In struts 2 framework, we provide all the components (view components and action) information in struts.xml file. If we need to change any information, we can simply change it in the xml file.

2) POJO based actions

In struts 2, action class is POJO (Plain Old Java Object) i.e. a simple java class. Here, you are not forced to implement any interface or inherit any class.

3) AJAX support

Struts 2 provides support to ajax technology. It is used to make asynchronous request i.e. it doesn't block the user. It sends only required field data to the server side not all. So it makes the performance fast.

4) Integration Support

We can simply integrate the struts 2 application with hibernate, spring, tiles etc. frameworks.

5) Various Result Types

We can use JSP, freemarker, velocity etc. technologies as the result in struts 2.

6) Various Tag support

Struts 2 provides various types of tags such as UI tags, Data tags, control tags etc to ease the development of struts 2 application.

7) Theme and Template support

Struts 2 provides three types of theme support: xhtml, simple and css_xhtml. The xhtml is default theme of struts 2. Themes and templates can be used for common look and feel.

Before developing the web applications, we need to have idea about design models. There are two types of programming models (design models)
  1. Model 1 Architecture
  2. Model 2 (MVC) Architecture


Model 1 Architecture

Servlet and JSP are the main technologies to develop the web applications.
Servlet was considered superior to CGI. Servlet technology doesn't create process, rather it creates thread to handle request. The advantage of creating thread over process is that it doesn't allocate separate memory area. Thus many subsequent requests can be easily handled by servlet.
Problem in Servlet technology Servlet needs to recompile if any designing code is modified. It doesn't provide separation of concern. Presentation and Business logic are mixed up.
JSP overcomes almost all the problems of Servlet. It provides better separation of concern, now presentation and business logic can be easily separated. You don't need to redeploy the application if JSP page is modified. JSP provides support to develop web application using JavaBean, custom tags and JSTL so that we can put the business logic separate from our JSP that will be easier to test and debug.
model 1 architecture
As you can see in the above figure, there is picture which show the flow of the model1 architecture.
  1. Browser sends request for the JSP page
  2. JSP accesses Java Bean and invokes business logic
  3. Java Bean connects to the database and get/save data
  4. Response is sent to the browser which is generated by JSP

Advantage of Model 1 Architecture

  • Easy and Quick to develop web application

Disadvantage of Model 1 Architecture

  • Navigation control is decentralized since every page contains the logic to determine the next page. If JSP page name is changed that is referred by other pages, we need to change it in all the pages that leads to the maintenance problem.
  • Time consuming You need to spend more time to develop custom tags in JSP. So that we don't need to use scriptlet tag.
  • Hard to extend It is better for small applications but not for large applications.

Model 2 (MVC) Architecture

Model 2 is based on the MVC (Model View Controller) design pattern. The MVC design pattern consists of three modules model, view and controller.
Model The model represents the state (data) and business logic of the application.
View The view module is responsible to display data i.e. it represents the presentation.
Controller The controller module acts as an interface between view and model. It intercepts all the requests i.e. receives input and commands to Model / View to change accordingly.
mvc architecture

Advantage of Model 2 (MVC) Architecture

  • Navigation control is centralized Now only controller contains the logic to determine the next page.
  • Easy to maintain
  • Easy to extend
  • Easy to test
  • Better separation of concerns

Disadvantage of Model 2 (MVC) Architecture

  • We need to write the controller code self. If we change the controller code, we need to recompile the class and redeploy the application.

Visit here to get the Example of MVC using Servlet and JSP.

Solution of Model 2 Architecture: Configurable MVC Components

It uses the declarative approach for defining view components, request mapping etc. It resolves the problem of Model 2 architecture. The Struts framework provides the configurable MVC support. In struts 2, we define all the action classes and view components in struts.xml file.

Tuesday, 5 April 2016

UPLOADING FILE TO THE SERVER USING JSP

There are many ways to upload the file to the server. One of the way is by the MultipartRequest class. For using this class you need to have the cos.jar file. In this example, we are providing the cos.jar file alongwith the code.

MultipartRequest class

It is a utility class to handle the multipart/form-data request. There are many constructors defined in the MultipartRequest class.

Commonly used Constructors of MultipartRequest class

  • MultipartRequest(HttpServletRequest request, String saveDirectory) uploads the file upto 1MB.
  • MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize) uploads the file upto specified post size.
  • MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize, String encoding)uploads the file upto specified post size with given encoding.


Example of File Upload in JSP

In this example, we are creating two files only, index.jsp and fileupload.jsp.

index.jsp

To upload the file to the server, there are two requirements:
  1. You must use the post request.
  2. encodeType should be multipart/form-data that gives information to the server that you are going to upload the file.

  1. <form action="upload.jsp" method="post" enctype="multipart/form-data">  
  2. Select File:<input type="file" name="fname"/><br/>  
  3. <input type="image" src="MainUpload.png"/>  
  4. </form>  

upload.jsp

We are uploading the incoming file to the location d:/new, you can specify your location here.

  1. <%@ page import="com.oreilly.servlet.MultipartRequest" %>  
  2. <%  
  3. MultipartRequest m = new MultipartRequest(request, "d:/new");  
  4. out.print("successfully uploaded");  
  5.   
  6. %>  

Example of Downloading file from the server using JSP

In this example, we are going to download the jsp file. But you may download any file. For downloading the file from the server, you should specify the content type named APPLICATION/OCTET-STREAM.

index.jsp

This file provides a link to download the jsp file.

  1. <a href="download.jsp">download the jsp file</a>  

download.jsp

In this example, we are downloading the file home.jsp which is located in the e: drive. You may change this location accordingly.

  1. <%    
  2.   String filename = "home.jsp";   
  3.   String filepath = "e:\\";   
  4.   response.setContentType("APPLICATION/OCTET-STREAM");   
  5.   response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");   
  6.   
  7.   java.io.FileInputStream fileInputStream=new java.io.FileInputStream(filepath + filename);  
  8.             
  9.   int i;   
  10.   while ((i=fileInputStream.read()) != -1) {  
  11.     out.write(i);   
  12.   }   
  13.   fileInputStream.close();   
  14. %>   


Monday, 4 April 2016

REGISTRATION FORM IN JSP

For creating registration form, you must have a table in the database. You can write the database logic in JSP file, but separating it from the JSP page is better approach. Here, we are going to use DAO, Factory Method, DTO and Singletion design patterns. There are many files:
  • index.jsp for getting the values from the user
  • User.java, a bean class that have properties and setter and getter methods.
  • process.jsp, a jsp file that processes the request and calls the methods
  • Provider.java, an interface that contains many constants like DRIVER_CLASS, CONNECTION_URL, USERNAME and PASSWORD
  • ConnectionProvider.java, a class that returns an object of Connection. It uses the Singleton and factory method design pattern.
  • RegisterDao.java, a DAO class that is responsible to get access to the database


Example of Registration Form in JSP

In this example, we are using the Oracle10g database to connect with the database. Let's first create the table in the Oracle database:

  1. CREATE TABLE  "USER432"   
  2.    (    "NAME" VARCHAR2(4000),   
  3.     "EMAIL" VARCHAR2(4000),   
  4.     "PASS" VARCHAR2(4000)  
  5.    )  
  6. /  
We have created the table named user432 here.

index.jsp

We are having only three fields here, to make the concept clear and simplify the flow of the application. You can have other fields also like country, hobby etc. according to your requirement.

  1. <form action="process.jsp">  
  2. <input type="text" name="uname" value="Name..." onclick="this.value=''"/><br/>  
  3. <input type="text" name="uemail"  value="Email ID..." onclick="this.value=''"/><br/>  
  4. <input type="password" name="upass"  value="Password..." onclick="this.value=''"/><br/>  
  5. <input type="submit" value="register"/>  
  6. </form>  

process.jsp

This jsp file contains all the incoming values to an object of bean class which is passed as an argument in the register method of the RegisterDao class.

  1. <%@page import="bean.RegisterDao"%>  
  2. <jsp:useBean id="obj" class="bean.User"/>  
  3.   
  4. <jsp:setProperty property="*" name="obj"/>  
  5.   
  6. <%  
  7. int status=RegisterDao.register(obj);  
  8. if(status>0)  
  9. out.print("You are successfully registered");  
  10.   
  11. %>  

User.java

It is the bean class that have 3 properties uname, uemail and upass with its setter and getter methods.

  1. package bean;  
  2.   
  3. public class User {  
  4. private String uname,upass,uemail;  
  5.   
  6. public String getUname() {  
  7.     return uname;  
  8. }  
  9.   
  10. public void setUname(String uname) {  
  11.     this.uname = uname;  
  12. }  
  13.   
  14. public String getUpass() {  
  15.     return upass;  
  16. }  
  17.   
  18. public void setUpass(String upass) {  
  19.     this.upass = upass;  
  20. }  
  21.   
  22. public String getUemail() {  
  23.     return uemail;  
  24. }  
  25.   
  26. public void setUemail(String uemail) {  
  27.     this.uemail = uemail;  
  28. }  
  29.   
  30. }  

Provider.java

This interface contains four constants that can vary from database to database.

  1. package bean;  
  2.   
  3. public interface Provider {  
  4. String DRIVER="oracle.jdbc.driver.OracleDriver";  
  5. String CONNECTION_URL="jdbc:oracle:thin:@localhost:1521:xe";  
  6. String USERNAME="system";  
  7. String PASSWORD="oracle";  
  8.   
  9. }  

ConnectionProvider.java

This class is responsible to return the object of Connection. Here, driver class is loaded only once and connection object gets memory only once.

  1. package bean;  
  2. import java.sql.*;  
  3. import static bean.Provider.*;  
  4.   
  5. public class ConnectionProvider {  
  6. private static Connection con=null;  
  7. static{  
  8. try{  
  9. Class.forName(DRIVER);  
  10. con=DriverManager.getConnection(CONNECTION_URL,USERNAME,PASSWORD);  
  11. }catch(Exception e){}  
  12. }  
  13.   
  14. public static Connection getCon(){  
  15.     return con;  
  16. }  
  17.   
  18. }  

RegisterDao.java

This class inserts the values of the bean component into the database.

  1. package bean;  
  2.   
  3. import java.sql.*;  
  4.   
  5. public class RegisterDao {  
  6.   
  7. public static int register(User u){  
  8. int status=0;  
  9. try{  
  10. Connection con=ConnectionProvider.getCon();  
  11. PreparedStatement ps=con.prepareStatement("insert into user432 values(?,?,?)");  
  12. ps.setString(1,u.getUname());  
  13. ps.setString(2,u.getUemail());  
  14. ps.setString(3,u.getUpass());  
  15.               
  16. status=ps.executeUpdate();  
  17. }catch(Exception e){}  
  18.       
  19. return status;  
  20. }  
  21.   
  22. }  

Login and Logout Example in JSP

In this example of creating login form, we have used the DAO (Data Access Object), Factory method and DTO (Data Transfer Object) design patterns. There are many files:
  • index.jsp it provides three links for login, logout and profile
  • login.jsp for getting the values from the user
  • loginprocess.jsp, a jsp file that processes the request and calls the methods.
  • LoginBean.java, a bean class that have properties and setter and getter methods.
  • Provider.java, an interface that contains many constants like DRIVER_CLASS, CONNECTION_URL, USERNAME and PASSWORD
  • ConnectionProvider.java, a class that is responsible to return the object of Connection. It uses the Singleton and factory method design pattern.
  • LoginDao.java, a DAO class that verifies the emailId and password from the database.
  • logout.jsp it invalidates the session.
  • profile.jsp it provides simple message if user is logged in, otherwise forwards the request to the login.jsp page.


In this example, we are using the Oracle10g database to match the emailId and password with the database. The table name is user432 which have many fields like name, email, pass etc. You may use this query to create the table:

  1. CREATE TABLE  "USER432"   
  2.    (    "NAME" VARCHAR2(4000),   
  3.     "EMAIL" VARCHAR2(4000),   
  4.     "PASS" VARCHAR2(4000)  
  5.    )  
  6. /  
We assume that there are many records in this table.

index.jsp

It simply provides three links for login, logout and profile.

  1. <a href="login.jsp">login</a>|  
  2. <a href="logout.jsp">logout</a>|  
  3. <a href="profile.jsp">profile</a>  

login.jsp

This file creates a login form for two input fields name and password. It is the simple login form, you can change it for better look and feel. We are focusing on the concept only.

  1. <%@ include file="index.jsp" %>  
  2. <hr/>  
  3.   
  4. <h3>Login Form</h3>  
  5. <%  
  6. String profile_msg=(String)request.getAttribute("profile_msg");  
  7. if(profile_msg!=null){  
  8. out.print(profile_msg);  
  9. }  
  10. String login_msg=(String)request.getAttribute("login_msg");  
  11. if(login_msg!=null){  
  12. out.print(login_msg);  
  13. }  
  14.  %>  
  15.  <br/>  
  16. <form action="loginprocess.jsp" method="post">  
  17. Email:<input type="text" name="email"/><br/><br/>  
  18. Password:<input type="password" name="password"/><br/><br/>  
  19. <input type="submit" value="login"/>"  
  20. </form>  

loginprocess.jsp

This jsp file contains all the incoming values to an object of bean class which is passed as an argument in the validate method of the LoginDao class. If emailid and password is correct, it displays a message you are successfully logged in! and maintains the session so that we may recognize the user.

  1. <%@page import="bean.LoginDao"%>  
  2. <jsp:useBean id="obj" class="bean.LoginBean"/>  
  3.   
  4. <jsp:setProperty property="*" name="obj"/>  
  5.   
  6. <%  
  7. boolean status=LoginDao.validate(obj);  
  8. if(status){  
  9. out.println("You r successfully logged in");  
  10. session.setAttribute("session","TRUE");  
  11. }  
  12. else  
  13. {  
  14. out.print("Sorry, email or password error");  
  15. %>  
  16. <jsp:include page="index.jsp"></jsp:include>  
  17. <%  
  18. }  
  19. %>  

LoginBean.java

It is the bean class that have 2 properties email and pass with its setter and getter methods.

  1. package bean;  
  2.   
  3. public class LoginBean {  
  4. private String email,pass;  
  5.   
  6. public String getEmail() {  
  7.     return email;  
  8. }  
  9.   
  10. public void setEmail(String email) {  
  11.     this.email = email;  
  12. }  
  13.   
  14. public String getPass() {  
  15.     return pass;  
  16. }  
  17.   
  18. public void setPass(String pass) {  
  19.     this.pass = pass;  
  20. }  
  21.   
  22.   
  23. }  

Provider.java

This interface contains four constants that may differ from database to database.

  1. package bean;  
  2.   
  3. public interface Provider {  
  4. String DRIVER="oracle.jdbc.driver.OracleDriver";  
  5. String CONNECTION_URL="jdbc:oracle:thin:@localhost:1521:xe";  
  6. String USERNAME="system";  
  7. String PASSWORD="oracle";  
  8.   
  9. }  

ConnectionProvider.java

This class provides a factory method that returns the object of Connection. Here, driver class is loaded only once and connection object gets memory only once because it is static.

  1. package bean;  
  2. import java.sql.*;  
  3. import static bean.Provider.*;  
  4.   
  5. public class ConnectionProvider {  
  6. private static Connection con=null;  
  7. static{  
  8. try{  
  9. Class.forName(DRIVER);  
  10. con=DriverManager.getConnection(CONNECTION_URL,USERNAME,PASSWORD);  
  11. }catch(Exception e){}  
  12. }  
  13.   
  14. public static Connection getCon(){  
  15.     return con;  
  16. }  
  17.   
  18. }  

LoginDao.java

This class varifies the emailid and password.

  1. package bean;  
  2. import java.sql.*;  
  3. public class LoginDao {  
  4.   
  5. public static boolean validate(LoginBean bean){  
  6. boolean status=false;  
  7. try{  
  8. Connection con=ConnectionProvider.getCon();  
  9.               
  10. PreparedStatement ps=con.prepareStatement(  
  11.     "select * from user432 where email=? and pass=?");  
  12.   
  13. ps.setString(1,bean.getEmail());  
  14. ps.setString(2, bean.getPass());  
  15.               
  16. ResultSet rs=ps.executeQuery();  
  17. status=rs.next();  
  18.               
  19. }catch(Exception e){}  
  20.   
  21. return status;  
  22.   
  23. }  
  24. }