Tutorial_Create Struts 2 Application in Eclipse
更新时间:2023-05-29 20:11:02 阅读量: 实用文档 文档下载
- tutorial词根词缀推荐度:
- 相关推荐
Things We NeedBefore we starts with our first Hello World Struts 2 Example, we will need few tools.
1. JDK 1.5 above (download)
2. Tomcat 5.x above or any other container (Glassfish, JBoss, Websphere, Weblogic etc) (download)
3. Eclipse 3.2.x above (download)
4. Apache Struts2 JAR files:(download). Following are the list of JAR files required for this mons-logging-1.0.4.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
struts2-core-2.0.12.jar
xwork-2.0.6.jar
Note that depending on the current version of Struts2, the version number of above jar files may change.Our Goal
Our goal is to create a basic Struts2 application with a Login page. User will enter login credential and ifauthenticated successfully she will be redirected to a Welcome page which will display message ”Howdy,<username>…!“. If user is not authenticated, she will be redirected back to the login page.
Getting Started
Let us start with our first Struts2 based application.
Open Eclipse and goto File -> New -> Project and select Dynamic Web Project in the New Project wizardscreen.
After selecting Dynamic Web Project, press
Next.
Write the name of the project. For example StrutsHelloWorld. Once this is done, select the target runtimeenvironment (e.g. Apache Tomcat v6.0). This is to run the project inside Eclipse environment. After this
press Finish.
Once the project is created, you can see its structure in Project Explorer.
Now copy all the required JAR files in WebContent -> WEB-INF -> lib folder. Create this folder if it does notexists.
Mapping Struts2 in WEB.xml
As discussed in the previous article (Introduction to Struts2), the entry point of Struts2 application will be theFilter define in deployment descriptor (web.xml). Hence we will define an entry
oforg.apache.struts2.dispatcher.FilterDispatcher class in web.xml.
Open web.xml file which is under WEB-INF folder and copy paste following code.
<?xml version="1.0" encoding="UTF-8"?><web-app id="WebApp_9" version="2.4" xmlns="/xml/ns/j2ee" xmlns:xsi="/2001/XMLSchema-instance" xsi:schemaLocation="/xml/ns/j2ee /xml/ns/j2ee/web- <display-name>Struts2 Application</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><welcome-file-list><welcome-file>Login.jsp</welcome-file></welcome-file-list></web-app>
The above code in web.xml will map Struts2 filter with url/*. The default url mapping for struts2 application will be/*.action. Also note that we have define Login.jsp as welcome file. Note: The FilterDispatcher filter is deprecated since Struts version 2.1.3. If you are using latest version of Struts2 (> 2.1.3) use StrutsPrepareAndExecuteFilter class instead.<filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dis
patcher.ng.filter.StrutsPrepareAndExecuteFilter</</filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping>
The Action ClassWe will need an Action class that will authenticate our user and holds the value for username and password. For this we will create a package net.viralpatel.struts2 in the source folder. This package will contain the action file.
Create a class called LoginAction in net.viralpatel.struts2 package with following content. package net.viralpatel.struts2; public class LoginAction{ private String username; private String password; public String execute(){ if (ername.equals("admin")&& this.password.equals("admin123")){ return"success";} else{ return"error";
} } public String getUsername() { return username; } public void setUsername(String username) { ername = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}
Note that, above action class contains two fields, username and password which will hold the values fromform and also contains an execute() method that will authenticate the user. In this simple example, we arechecking if username is admin and password is admin123.
Also note that unlike Action class in Struts1, Struts2 action class is a simple POJO class with requiredattributes and method.
The execute() method returns a String value which will determine the result page. Also, in Struts2 thename of the method is not fixed. In this example we have define method execute(). You may want to definea method authenticate() instead.
The ResourceBundle
ResourceBundle is very useful Java entity that helps in putting the static content away from the source file.Most of the application define a resource bundle file such as ApplicationResources.properties file whichcontains static messages such as Username or Password and include this with the application.
ResourceBundle comes handy when we want to add Internationalization (I18N) support to an application.We will define an ApplicationResources.properties file for our application. This property file should bepresent in WEB-INF/classes folders when the source is compiled. Thus we will create a source foldercalled resources and put the ApplicationResources.properties file in it.
To create a source folder, right click on your project in Project Explorer and select New -> Source Folder.
Specify folder name resources and press Finish. Create a file ApplicationResources.properties under resources folder.
Copy following content in ApplicationResources.properties. ername= Username label.password= Password label.login= Login
The JSPWe will create two JSP files to render the output to user. Login.jsp will be the starting point of our application which will contain a simple login form with username and password. On successful authentication, user will be redirected to Welcome.jsp which will display a simple welcom
e message. Create two JSP files Login.jsp and Welcome.jsp in WebContent folder of your project. Copy following content into it.
Login.jsp<%@ page contentType="text/html; charset=UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"%><html><head><title>Struts 2 - Login Application| </title></head><body><h2>Struts 2 - Login Application</h2><s:actionerror/><s:form action="login.action" method="post"><s:textfield name="username" key="ername" size="20"/><s:password name="password" key="label.password" size="20"/><s:submit method="execute" key="label.login" align="center"/>
</s:form></body></html>
Welcome.jsp
<%@ page contentType="text/html; charset=UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"%><html><head><title>Welcome</title></head> <body> <h2>Howdy, <s:property value="username" />...!</h2></body></html>
Note that we have used struts2 <s:> tag to render the textboxes and labels. Struts2 comes with a powerfulbuilt-in tag library to render UI elements more efficiently.
The struts.xml file
Struts2 reads the configuration and class definition from an xml file called struts.xml. This file is loadedfrom the classpath of the project. We will define struts.xml file in the resources folder. Create file struts.xmlin resources folder.
Copy following content into struts.xml.
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "/dtds/struts-2.0.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="false" /> <constant name="struts.custom.i18n.resources" value="ApplicationResources" /> <package name="default" extends="struts-default" namespace="/"> <action name="login" class="net.viralpatel.struts2.LoginAction"> <result name="success">Welcome.jsp</result> <result name="error">Login.jsp</result> </action> </package></struts>
Note that in above configuration file, we have defined Login action of our application. Two result paths are
mapped with LoginAction depending on the outcome of execute() method. If execute() method returnssuccess, user will be redirected to Welcome.jsp else to Login.jsp.
Also note that a constant is specified with name struts.custom.i18n.resources. This constant specify theresource bundle file that we created in above steps. We just have to specify name of resource bundle filewithout extension (ApplicationResources without .properties).
Our LoginAction contains the method execute() which is the default method getting called by Sturts2. If thename of method is different, e.g. authenticate(); then we should specify the method name in<action> tag.<action name="login" method="authenticate" class="net.viralpatel.struts2.LoginAction">
Almost Done
We are almost done with the application. You may want to run the application now and see the resultyourself. I assume you have already configured Tomcat in eclipse. All you need to do:
Open Server view from Windows -> Show View -> Server. Right click in this view and select New -> Serverand add your server details.
To run the project, right click on Project name from Project Explorer and select Run as -> Run on Server(Shortcut: Alt+Shift+X, R)
But there is one small problem. Our application runs perfectly fine at this point. But when user enters wrongcredential, she is redirected to Login page. But no error message is displayed. User does not know whatjust happened. A good application always show proper error messages to user. So we must display anerror message Invalid Username/Password. Please try again when user authentication is failed.
Final Touch
To add this functionality first we will add the error message in our ResourceBundle file.
Open ApplicationResources.properties and add an entry for error.login in it. The final
ApplicationResources.properties will look like:
ername= Usernamelabel.password= Passwordlabel.login= Loginerror.login= Invalid Username/Password. Please try again.
Also we need to add logic in LoginAction to add error message if user is not authenticated. But there is oneproblem. Our error message is specified in ApplicationResources.properties file. We must specify keyerror.login in LoginAction and the message should be displayed on JSP page.
For this we must implement com.opensymphony.xwork2.TextProvider interface which provides
methodgetText(). This method returns String value from resource bundle file. We just have to pass thekey value as argument to getText() method. The TextProvider interface defines several method that wemust implement in order to get hold on getText() method. But we don’t want to spoil our code by adding allthose methods which we do not intend to use. There is a good way of dealing with this problem.
Struts2 comes with a very useful class com.opensymphony.xwork2.ActionSupport. We just have to extendour LoginAction class with this class and directly use methods such as getText(), addActionErrors() etc.
Thus we will extend the LoginAction class with ActionSupport class and add the logic for error reporting intoit. The final code in LoginAction must look like:
package net.viralpatel.struts2; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport { private String username; private String password; public String execute() { if (ername.equals("admin") && this.password.equals("admin123")) { return "success"; } else { addActionError(getText("error.login")); return "error"; } } public String getUsername() { return username; } public void setUsername(String username) { ername = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}
And that’s it. Our first Hello World Struts2 Application is now ready.
That’s All Folks
Execute the application in Eclipse and run it in your favorite browser.
Login page
Welcome page
Login page with error
Download Source Code
Source Code without JAR files (9 KB)
Source Code with JAR files (3 MB)
Moving On
Now that we have created our first webapp using Struts2 framework, we know how the request flows inStruts2. We also know the use of struts.xml and properties file. In this application we implemented a
preliminary form of validation. In next part we will learn more about Validation Framework in Struts2 andimplement it in our example.
If you read this far, you should follow me on twitter here.
正在阅读:
Tutorial_Create Struts 2 Application in Eclipse05-29
超级新闻场节目分析07-24
张军《西方经济学学习精要与习题集》(第4章 生产技术)03-08
qq怎么改名字02-09
2018河南,全国二级建造师继续教育网上考试选修答案01-26
跟老婆道歉的话02-06
全科医学概论总结 - 图文10-02
小学数学低段教研组计划07-25
动词时态语态精品文档10-10
- 教学能力大赛决赛获奖-教学实施报告-(完整图文版)
- 互联网+数据中心行业分析报告
- 2017上海杨浦区高三一模数学试题及答案
- 招商部差旅接待管理制度(4-25)
- 学生游玩安全注意事项
- 学生信息管理系统(文档模板供参考)
- 叉车门架有限元分析及系统设计
- 2014帮助残疾人志愿者服务情况记录
- 叶绿体中色素的提取和分离实验
- 中国食物成分表2020年最新权威完整改进版
- 推动国土资源领域生态文明建设
- 给水管道冲洗和消毒记录
- 计算机软件专业自我评价
- 高中数学必修1-5知识点归纳
- 2018-2022年中国第五代移动通信技术(5G)产业深度分析及发展前景研究报告发展趋势(目录)
- 生产车间巡查制度
- 2018版中国光热发电行业深度研究报告目录
- (通用)2019年中考数学总复习 第一章 第四节 数的开方与二次根式课件
- 2017_2018学年高中语文第二单元第4课说数课件粤教版
- 上市新药Lumateperone(卢美哌隆)合成检索总结报告
- Application
- Tutorial
- Eclipse
- Create
- Struts
- 2013年高考作文写作指导及例文
- 最新线上教学与返校学习的衔接教学计划-三年级下册数学-程艳秋
- 商法的精神....从商人法到现代商法的转变析商法存在的意义
- 2344+建筑工程项目管理(2009.7)
- 小学生文明礼貌用语总汇
- 企业信信息管理师三级测试1
- 2010年天王社区民政半年工作总结
- 平凡中见证优秀——护士比赛演讲稿
- 英雄联盟适合上单的英雄解析
- 黄芩的药理研究进展
- 大学生应该脱口而出的英语口语
- 生日宴会(1000字)作文
- 夏邑县桑固乡赵寨刘氏家谱
- 江苏省南通市启东中学2016届高三上学期第一次月考试题 数学
- 1申论对策的八大套路
- 湘教版六年级语文下册期中知识点整理复习练习题含答案
- 中国企业品牌国际化战略分析
- 用人单位内部劳动保障规章制度
- 社会调查原理与方法期末预测试题
- 基于组态软件的PLC仿真实训教学系统研究与实现