So far discussion gave an idea what is the workflow of Struts and what Design Patterns are implemented. Before we use Struts w.r. to WebApplication development lets see few advantages of Struts.
- Presenting Dynamic web content to the web clients in a faster, simpler and easier manner.
- As it is built on top of Servlet & JSP specifications we can deploy the Struts applications in any web or application servers.
- Provides Infrastructures, so we take the advantage of Declarative Exception handling, Declarative validations and also Programmatic validations(at server side).
- As Struts is open source, customization is not a deal. Meaning we can have further UserExtensions.
- Helps in designing the view pages followed with implementing Composite view design pattern(i.e Struts with Tiles framework).
Requirement is validating User name and password.
- Write a Login.html
- Write a web.xml
- Write an Action Class? How?
->Your class should be sub type of org.apache.struts.action.Action
->Override the execute() behavior which takes the following inputs
-->ActionMapping
-->ActionForm
-->HttpServletRequest
-->HttpServletResponse
-->throws clause is throws "Exception"
->Output type of execute() behavior is ActionForward.
->Write a struts configuration file.
->Write a jsp document as a view page.
What is the Directory Structure to arrange the above?
As Struts is a web Application framework it uses the same directory structure that we used for Servlets and jsp.
Login.Html
web.xml
<web-app>
<servlet>
<servlet-name> st1 </servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> st1 </servlet-name>
<url-pattern>*.stech</url-pattern>
</servlet-mapping>
</web-app>
LoginAction.java
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class LoginAction extends Action{
public ActionForward execute(ActionMapping am,ActionForm af, HttpServletRequest req, HttpServletResponse res)throws Exception{
//retrive the client sent parameters
String name=req.getParameter("uname");
String pass=req.getParameter("pass");
//now validate the username and password
// not recommanded database logic in the Action
//use controlflow statements
if(name.equals("user1")&&pass.equals("pass1"))
return am.findForward("success");
return am.findForward("failure");
}//execute
}//Action class
struts-config.xml :
<struts-config>
<action-mappings>
<action type="LoginAction" path="/login">
<forward name="success" path="/welcome.jsp"/>
<forward name="failure" path="/Login.html"/>
</action>
</action-mappings>
</struts-config>
welcome.jsp:
Welcome to Java at:: <%=request.getParameter("uname")%>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
for classpath we need the following jars to compile the program.
servlet-api.jar
struts-core-1.3.8.jar
url:
localhost:2010/ex1/Login.html

