• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

Struts

Struts 2 validation framework

July 2, 2012 By j2eereference Leave a Comment

Here let’s see how struts2 validation happens with XML configuration.

Lets take an example of a login page , here we will check any of the fields are blank using struts 2 validation framework.

For this we need the following files.

  • web.xml                                    (WEB-INF)
  • struts.xml                                 (WEB-INF\classes)
  • struts.properties(Optional)  (WEB-INF\classes)
  • LoginAction.java                     (WEB-INF\classes\com\j2eereference\struts2\action)
  • LoginAction-validation.xml  (WEB-INF\classes\com\j2eereference\struts2\action)
  • UserVO.java                              (WEB-INF\classes\com\j2eereference\struts2\vo)
  • login.jsp                                     (\)

The Struts 2 validation framework uses xml based configuration file. The file name should be < your action class name> -validation.xml. In our case our action class name is Login.java, so our validation configuration file will be Login-validation.xml.

One important thing we need to notice that the validation XML should be saved in the same location of your LoginActionClass ,  In our example its under WEB-INF\classes\com\j2eereference\struts2\action

Now lets see each of the above files closely.

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
&nbsp;id="WebApp_ID" version="2.5">
<display-name>j2eereference</display-name>
 
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

struts.xml

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
  <action name="loginAction" method="validateUser">
     <result name="input">/login.jsp</result>
     <result name="success">/success.jsp</result>
     <result name="failure">/failure.jsp</result>
&nbsp; </action>
</package>
</struts>

 

LoginAction.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.j2eereference.struts2.action;
 
import javax.servlet.http.HttpSession;
import com.j2eereference.struts2.vo.UserVO;
import com.opensymphony.xwork2.ActionSupport;
 
public class LoginAction extends ActionSupport {
 
private static final long serialVersionUID = 1L;
private UserVO userVO;
private String returnValue;
 
HttpSession session;
 
public String validateUser()
{
String userName=userVO.getLoginUserName();
String password=userVO.getLoginUserName();
/* Call your business logic layer do the validation,as per the result assign
success or failure to the variable returnValue */
 
return returnValue;
    }
 
    public UserVO getUserVO() {
return userVO;
}
public void setUserVO(UserVO userVO) {
this.userVO = userVO;
}
 
}

 

LoginAction-validation.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="userVO.loginUserName">
<field-validator type="requiredstring">
<message>User Name is required.</message>
</field-validator>
</field>
 
<field name="userVO.password">
<field-validator type="requiredstring">
<message>Password is required.</message>
</field-validator>
</field>
</validators>

UserVo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.j2eereference.struts2.vo;
 
public class UserVO {
 
private String loginUserName;   
private String password;
 
public String getLoginUserName() {
return loginUserName;
}
public void setLoginUserName(String loginUserName) {
this.loginUserName = loginUserName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
 
}

login.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<html xmlns="http://www.w3.org/1999/xhtml">
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<head>
<title>j2eereference</title>
</head>
<body>
<s:form name="loginForm" method="post" action="loginAction">
<table&nbsp; width=50%>
<s:fielderror cssStyle="color: red;font-family:Arial, Verdana, sans-serif;font-size:12px;"/>
<tr>
<td>&nbsp;</td><td>User Name</td><td><s:textfield name="userVO.loginUserName"/></td>
</tr>
<tr>
<td>&nbsp;</td><td>Password</td><td><s:password name="userVO.password"/> </td>
</tr>
<tr>
<td>&nbsp;</td><td></td><td align=right><s:submit/></td>
</tr>
</table>
</s:form>
</body>
</html>

struts.properties     :  This file is for setting the theme . If we are not setting this, struts will set the default theme.

1
struts.ui.theme=simple

Now lets see the screen shot by running  the application

Here when you click on the submit button without entering the password , you will get an error message on top saying that password is required.

Here you can notice that

  • The error messages we are defining in the LoginAction-validation.xml .
  • Color and style of the message in jsp using the struts tag as below.
    1
    <s:fielderror cssStyle="color: red;font-family:Arial, Verdana, sans-serif;font-size:12px;"/>

Filed Under: Struts

Mailing Application in Struts2

June 5, 2012 By j2eereference Leave a Comment

A Mailing application in Struts 2 is given below, This application sends an email to the recipients .You need to download and install the mail.jar and place the mail.jar file in your WEB-INF\lib folder and then create action class

Create Action

 Create an Action class that contains method for sending the email. Let us create a new class  called sendMail.java with the following contents.

private static void sendMail(final String username, final String password,String sender, String destination, String subject,String messageText) {

Properties props = new Properties();

props.put(“mail.smtp.auth”, “true”);
props.put(“mail.smtp.starttls.enable”, “true”);
props.put(“mail.transport.protocol”, “smtp”);
props.put(“mail.smtp.host”, “smtp.gmail.com”);
props.put(“mail.smtp.port”, “587”);

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});

try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(destination));
message.setSubject(subject);
message.setText(messageText);

Transport.send(message);

System.out.println(“Done”);

} catch (MessagingException e) {
throw new RuntimeException(e);
}
}

Now let us create a JSP main.jsp which contains email related informations.

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″ pageEncoding=”ISO-8859-1″%>

<%@ taglib prefix=”s” uri=”/struts-tags”%>

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>

<html>

<head>

<title>Email Registration</title>

</head>

<body>

<form action=”sentMailAction” method=”post”>

<label for=”sender”>Sender</label><br/> <input type=”text” name=”sender”/><br/>

<label for=”password”>Password</label><br/> <input type=”password” name=”password”/><br/>

<label for=”destination”>Destination</label><br/> <input type=”text” name=”destination”/><br/>

<label for=”subject”>Subject</label><br/> <input type=”text” name=”subject”/><br/>

<label for=”msgText”>MessageText</label><br/> <input type=”text” name=”msgText”/><br/>

<input type=”submit” value=”Send Email”/>

</form>

</body>

</html>

Now we can create a view page to see success,

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″ pageEncoding=”ISO-8859-1″%>

<%@ taglib prefix=”s” uri=”/struts-tags”%>

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>

<html>

<head>

<title>Email Success</title>

</head>

<body>

Your email to <s:property value=”destination”/> was sent successfully.

</body>

</html>

Lets put everything together using struts.xml configuration file.

<?xml version=”1.0″ encoding=”UTF-8″?>

<!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”>

<struts>

<constant name=”struts.devMode” value=”true” />

<package name=”helloworld” extends=”struts-default”>

<action name=”sentMailAction” class=”com.sendMail”>

<result name=”success”>/success.jsp</result>

<result name=”error”>/error.jsp</result>

</action>

</package>

</struts>

Filed Under: Struts

Struts 2 Tiles

June 4, 2012 By j2eereference Leave a Comment

What is Tiles?

Tiles is a view layer framework for Java EE applications that allows to separate pages,according to Composite View design Pattern.It is a templating framework which simplifies the development of web application user interfaces.

To use Tiles in your application you need,

  • a Java Runtime Environment following the Java SE 5.0 specifications;
  • a servlet container that supports Servlet 2.4 and JSP 2.0

The JAR files needed are,

  • the tiles-core-VERSION.jar and tiles-api-VERSION.jar

and tiles dependencies JAR

  • Jakarata Commons BeanUtils 1.7.0 or above;
  • Jakarata Commons Digester 1.8 or above;
  • Jakarata Commons Logging 1.1 or above.

The implementation of Tiles around the Composite View pattern consists of the Template,Attribute and Definition concepts.A template is the layout part of a page.An attribute is a gap in a template that needs to be filled in your application.A definition is a composition to be rendered to the end user.

Here is an Example to integrate Struts 2 and Tiles using the Struts2 tiles plugin.

Above is a classic Tiles Layout,we can replicate this structure by creating a JSP page called baseLayout as follows,

<%@ taglib uri=”http://tiles.apache.org/tags-tiles” prefix=”tiles” %>

<table>

<tr>

<td colspan=”2″>

<tiles:insertAttribute name=”header” />

</td>

</tr>

<tr>

<td>

<tiles:insertAttribute name=”menu” />

</td>

<td>

<tiles:insertAttribute name=”body” />

</td>

</tr>

<tr>

<td colspan=”2″> <tiles:insertAttribute name=”footer” />

</td>

</tr>

</table>

 

In deployment descriptor set up tiles definition.To configure tiles,an entry to listener is given in web.xml

<listener>

      <listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>

</listener>

<context-param>

    <param-name>tilesDefinitions</param-name>

    <param-value>/WEB-INF/tiles.xml</param-value>

</context-param>

An input configuration file /WEB-INF/tiles.xml is passed as argument. This file contains the Tiles definition for web application.

Create a file tiles.xml inside WEB-INF folder,

<?xml version=”1.0″ encoding=”UTF-8″ ?>

<!DOCTYPE tiles-definitions PUBLIC

“-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN”

“http://tiles.apache.org/dtds/tiles-config_2_0.dtd”>

<tiles-definitions>

      <definition name=”baseLayout” template=”/BaseLayout.jsp”>

           <put-attribute name=”title” value=”” />

           <put-attribute name=”header” value=”/Header.jsp” />

           <put-attribute name=”menu” value=”/Menu.jsp” />

           <put-attribute name=”body” value=”” />

           <put-attribute name=”footer” value=”/Footer.jsp” />

      </definition>

      <definition name=”/welcome.tiles” extends=”baseLayout”>

           <put-attribute name=”title” value=”Welcome” />

           <put-attribute name=”body” value=”/Welcome.jsp” />

       </definition>

       <definition name=”/boys.tiles” extends=”baseLayout”>

           <put-attribute name=”title” value=”Boys Form” />

           <put-attribute name=”body” value=”/boys.jsp” />

       </definition>

       <definition name=”/girls.tiles” extends=”baseLayout”>

           <put-attribute name=”title” value=”Girls Form” />

           <put-attribute name=”body” value=”/girls.jsp” />

       </definition>

</tiles-definitions>

Here in tiles.xml we create base Layout. This layout contains attributes such as Header, Title, Body, Menu and Footer.The layout is then extended and new definitions for Welcome page and boys/girls page is defined.

In struts.xml we defined result tag which maps a particular action with a JSP page. Now we will modify it and map the result with Tiles. Following will be the content of struts.xml file.

<!DOCTYPE struts PUBLIC

“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”

“http://struts.apache.org/dtds/struts-2.0.dtd”>

<struts>

<package name=”default” extends=”struts-default”>

<result-types>

<result-type name=”tiles”

class=”org.apache.struts2.views.tiles.TilesResult” />

</result-types>

<action name=”*Link” method=”{1}” class=”com.LinkAction”>

<result name=”welcome” type=”tiles”>welcome</result>

<result name=”boys.tiles” type=”tiles”>boys</result>

<result name=”girls.tiles” type=”tiles”>girls</result>

</action>

</package>

</struts>

Here is detailed coding for each jsp present in baseLayout :-

Header.jsp

<div align=”center” style=”font-weight:bold”> Attendance Details</div>

Menu.jsp

<%@taglib uri=”/struts-tags” prefix=”s”%>

<a href=”<s:url action=”boysLink”/>” >BOYS</a><br>

<a href=”<s:url action=”girlsLink”/>” >GIRLS</a><br

Footer.jsp

<div align=”center”>&copy j2eerefrence.com</div>

Welcome.jsp

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″

pageEncoding=”ISO-8859-1″%>

<!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=ISO-8859-1″>

<title>welcome</title>

</head>

<body>

Welcome to our attendance page.

</body>

</html>

boys.jsp

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>

<!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>JSP Page</title>

</head>

<body>

<p> Boys attendance details  goes here…</p>

</body>

</html>

girls.jsp

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>

<!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>JSP Page</title>

</head>

<body>

<p> Girls attendance details  goes here…</p>

</body>

</html>

Compile and run the project and find whether Header,Menu and Footer are applied properly and whether the body is changing according to Menu items.

Filed Under: Struts

Struts 2 Interceptors

May 30, 2012 By j2eereference Leave a Comment

Interceptors can execute code before and after an Action is invoked .Interceptors sits in between the controller and the action ,and invoked by controller before and after invoking an action. It can perform actions such as Logging,Validation,File upload etc.

In Struts 2 , interceptors are called one after the other in a configured order for each invocation of an action class. The interceptors have an opportunity to interact with the input from user, and to interact with the action after it completes it’s processing.

The main method in an interceptor is the intercept() method. This method is passed an ActionInvocation object, which contains the action, and the context for the action. The intercept method returns a String that maps to a “result” in struts.xml file.

Let’s understand the use of interceptor with an example. In this example we are checking whether the user is already logged in or not before going to the action class . Assume that first time when a user logs in we are storing the user details in session attribute called user.

 

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.j2eereference.interceptor;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class SessionCheckInterceptor implements Interceptor {
 
private static final long serialVersionUID = 1L;
 
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession(true);
// Checking whether the user Object that had set at login time is null or not
 
if (session.getAttribute("user") == null) {
return "invalidsession";
}
return invocation.invoke(); // If user already logged in
}
 
@Override
public void destroy() {              
System.out.println("Destroying Interceptor");
}
 
@Override
public void init() {              
System.out.println("Initialising Interceptor");
     }
}

Now lets see the configuration in struts.xml.

 

XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
-----
---
 
<interceptors>
<interceptor name="SessionCheck" class="com.action.SessionCheckInterceptor">
</interceptor>
<interceptor-stack name="newStack">
<interceptor-ref name="SessionCheck"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
 
<!—-If we need to apply the interceptor for all the action classes-->
 
<default-interceptor-ref-name="checkSessionStack"/><global-results>
<result name="invalidSession">/login.jsp</result></global-results>
 
<!-- If we need to apply interceptor for a particular action -->
 
<action name="initAction" class="com.action.LoginAction"
method="init">
<interceptor-ref name="newStack">
</interceptor-ref>
<result name="invalidsession">/login.jsp</result>
<result name="success">/welcome.jsp</result>
</action>
 
---
---
</struts>


Filed Under: Struts

AutoCompleter using Struts 2

January 11, 2012 By j2eereference Leave a Comment

In this article we will explain how to use struts2 autocompleter tag. This tag is used for getting a dropdown list with options which has at least a partial match with the text we enter in the text box. If the user clicks on the dropdown button then all options will be showing in the dropdown list..

Lets see how can we create a sample application which gives the list of planet names in the dropdown list as below.

As and when the user give input in the text field , the planet names matching with the text entered will be displaying the drop down.

Make sure that you have struts2-dojo-plugin-2.1.8.jar file in your lib folder.

Add the following code into your struts.xml file.

<!DOCTYPE struts PUBLIC

“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”

“http://struts.apache.org/dtds/struts-2.0.dtd”>

 <struts>

    <package name=”default” extends=”struts-default”>                  

            <action name=”AjaxDemo”>

                  <result name=”success”>/ajaxDemo.jsp</result>

            </action>

      </package>    

</struts>

 

Create a list in the action class and populate them with planet names as shown in the “AutoCompleteAction” class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package j2eereference;
 
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
 
import com.opensymphony.xwork2.ActionSupport;
 
public class AutoCompleteAction extends ActionSupport {
private List planetList;
private String planets = "Mercury ,Venus ,Earth ,Mars ,Jupiter ,Saturn,Uranus,Neptune,Pluto";
 
public String execute()
{
 
planetList = new ArrayList();
StringTokenizer st = new StringTokenizer(planets, ",");
while (st.hasMoreTokens())
{
planetList.add(st.nextToken().trim());
}
 
return SUCCESS;
}
 
public List getPlanetList() {
return planetList;
}
}

Now let’s create ajaxDemo.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
&lt;%@ page contentType="text/html; charset=UTF-8"%&gt;
 
&lt;%@ taglib prefix="s" uri="/struts-tags"%&gt;
 
&lt;%@ taglib prefix="sx" uri="/struts-dojo-tags"%&gt;
 
&lt;html&gt;
 
&lt;head&gt;
 
&lt;title&gt;Welcome&lt;/title&gt;
 
&lt;s:head theme="ajax" /&gt;
 
&lt;/head&gt;
 
&lt;body&gt;
 
&lt;s:label name="stateName" value="Select Planet Name:" /&gt;
 
&lt;s:autocompleter list="planetList" name="planet"/&gt;
 
&lt;/action&gt;
 
&lt;/body&gt;
 
&lt;/html&gt;

 

In the above JSP you can notice that

1) We have included the tag library <%@ taglib prefix=”sx” uri=”/struts-dojo-tags”%>

2) <s:head theme=”ajax” /> – This is for getting the Ajax theme in our JSP page, like the background color while scrolling throgh the options etc.

3) <s:autocompleter list=”planetList” name=”planet”/>

This is for getting autocompleter list

Filed Under: Struts

Struts 2 – Configuration

January 4, 2012 By j2eereference Leave a Comment

Let’s understand the Struts 2 configuration with a simple example. We can have a form which has a text field to accept your name and on submit it should forward to a display page showing hello {YourName}.

Let’s have the following files for our example.

1)      web.xml

2)      struts.xml

3)      Helloworld.java

4)      input.jsp

5)      display.jsp

Now let’s see all the above components in details

Web.xml

The filter and the filter-mapping elements are used to setup the Struts 2 FilterDispatcher.

The filter is mapped to the URL pattern “/*“. This means all the incoming request that targets to the Struts 2 action will be handled by FilterDispatcher class.

1
2
3
4
5
6
7
8
9
&lt;filter&gt;
  &lt;filter-name&gt;struts2&lt;/filter-name&gt;
  &lt;filter-class&gt;org.apache.struts2.dispatcher.FilterDispatcher &lt;/filter-class&gt;
&lt;/filter&gt;
 
&lt;filter-mapping&gt;
  &lt;filter-name&gt;struts2&lt;/filter-name&gt;
  &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;

struts.xml

This is the struts configuration XML file. The struts.xml file contains the following action mapping.

1
2
3
4
5
6
7
&lt;struts&gt;
&lt;package name="default" extends="struts-default"&gt;
  &lt;action name="HelloWorld"&gt;
   &lt;result name="SUCCESS"&gt;/display.jsp&lt;/result&gt;
  &lt;/action&gt;
&lt;/package&gt;
&lt;/struts&gt;

input.jsp

Below is the input.jsp code which will take the input from the user.

For using the struts tags in the jsp page “struts-tags” taglib directive should be included.

1
&lt;%@taglib uri="/struts-tags" prefix="s" %&gt;

1
2
3
4
5
6
7
8
9
10
11
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Hello World&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;s:form action="HelloWorld" &gt;
&lt;s:textfield name="userName" label="User Name" /&gt;
&lt;s:submit /&gt;
&lt;/s:form&gt;
&lt;/body&gt;
&lt;/html&gt;

HelloWorld.java

Now let’s see the Helloworld.java which will take care of the request from the client. This class is very simple and it contains two properties one for the user name and the other for displaying the message.

 

1
public class HelloWorld {

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private String message;
private String userName;
public HelloWorld() {
}
 
public String execute() {
setMessage("Hello " + getUserName());
return "SUCCESS";
}
 
public String getMessage() {
return message;
}
 
public void setMessage(String message) {
this.message = message;
}
 
public String getUserName() {
return userName;
}
 
public void setUserName(String userName) {
this.userName = userName;
}
 
}

You can notice the following in the HelloWorld class

1) In the execute() method of the HelloWorld action we define the message to be displayed.

2) We need not have a separate form bean like struts 1 to access the form data. We can have a simple java class as action.

3) The action need not extend any class or implement any interface.

4) We need to have an execute() method which returns a String and has a public scope.

display.jsp

In the display page we display the “Hello User” message using the property tag.

1
2
3
4
5
6
7
8
9
&lt;%@taglib uri="/struts-tags" prefix="s" %&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;First struts 2 application&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;&lt;s:property value="message" /&gt;&lt;/h1&gt;
&lt;/body&gt;
&lt;/html&gt;

Filed Under: Struts

Struts framework

January 4, 2011 By j2eereference Leave a Comment

Struts is an open source MVC architecture created to make it easier for developers to build web applications based on Java Servlet and Java Server pages . In a J2EE based application, MVC architecture is used for separating business layer functionality  from Presentation layer functionality represented by JSPs (the view) using an intermediate servlet based controller.

The incoming HTTP requests are routed to a central controller, which in turn interprets and delegates the request to the appropriate request handlers.

 Struts also provides the following modules like   

Struts Validator for form validation.

Tiles for assembling composite views.

Internationalization

Exception Handling

Logging

Struts Components

1) Web.xml :

<servlet>

<servlet-name>action</servlet-name>

<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>action</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

Make sure that  all the  requests URI format will be like  

2) Action Class :

3) struts-config.xml:

4) Model in Struts:

This represents the business logic layer. Struts doesn’t offer anything to create the model layer of the web application.

5) View in Struts :

The view components in struts could be  Java Server pages, HTML etc.

 

Filed Under: Struts

MVC Architecture

January 4, 2011 By j2eereference Leave a Comment

Lets first find out why we need MVC architecture ?

The following JSP highlights some of the more common mistakes made by develors when writing an application. Here we are fetching employee details from the Database and displaying the result of the query in  the JSP

<@page import=”java.sql.*” %>

<table border=1>

<tr>

<td>EmpId </td>
<td>Emp Name</td>

</tr>

<%

Connection conn= null;
ResultSet rs=null;
Statemetnt stmnt=null;
try
{

Clas.forName(“com.mysql.jdbc.Driver”);

conn=DriverManager.getConnection(“jdbc:mysql://localhost:3306”, “userID”, “passwd”); 

StringBuffer query= new StringBuffer();
query.append(” select emp_id ,emp_name from”);
query.append(” employees”);

stmnt=conn.createStatement();
rs=stmnt.executeQuery(query.toString());
While(rs.next())
{

out.println(“<tr>”);

out.println(“<td>”);
out.println(rs.getString(“emp_name”)
out.println(“</td>”);

out.println(“<td>”);
out.println(rs.getString(“emp_id”));
out.println(“</td>”);

out.println(“</tr>”);

}

}
catch(SQLException sqe)
{
out.println(“Got SQL Exception”+ sqe.getMessage());
}
finally
{
if(stmnt !=null) try{ stmnt.close(); } catch(SQLException sqe){}
if(rs!=null) try{ r.close(); } catch(SQLException sqe){}
if(conn!=null) try{ conn.close(); } catch(SQLException sqe){}

}

%>

</table> 

In the above Example Presentation we can find the bellow issues

  1.  
    1. Business and data layers are not separated.
    2. Exposing the Database details like Db Name , userId , Password are embedded in the code.
    3. Expose the structure of Tables.
    4. In future if you want to change  your DB Name, DB server ,DB from mySQL to Oracle  etc. we need to make sure that all the database touch points were visited and updated.

These issues can be handle if we use MVC Architecture

The MVC pattern has three key components:

1) The Model Component

Responsible for the business domain state knowledge

2) The View Component

Responsible for a presentation view of the business domain

3) The Controller Component

Responsible for controlling flow and state of the user input

The MVC Model 

Depending on the type of architecture of your application, the model portion of the MVC  pattern can take many different forms. In a two-tier application, where the web tier interacts directly with a database, the model classes may be a set of regular Java objects. These objects may be populated manually from a result set returned by a database query or they can even be instantiated and populated automatically by an Object-to-Relational Mapping (ORM) framework like Hibernate 

The MVC View

 The views within the web tier MVC pattern typically consist of HTML and JSP pages.HTML pages are used to serve static content, while JSP pages can be used to serve bot static and dynamic content..  

The MVC Controller 

The controller portion of the web tier MVC design is generally a Java servlet. The Controller

 A web tier application performs the following tasks:

 1. Intercepts HTTP requests from a client.

2. Translates the request into a specific business operation to perform.

3. Either invokes the business operation itself or delegates to a handler.

4. Helps to select the next view to display to the client.

5. Returns the view to the client.

 

Filed Under: Struts

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.