An introductory tutorial on Web programming under the Java Struts Framework _java

Source: Internet
Author: User
Tags class definition html form tomcat server

When clicking on a hyperlink or submitting an HTML form in the STRUTS2 Web application, the input collected is sent to a Java class called the Operation Controller. When the action is executed, the result selects a resource to render the response. A resource is usually a JSP, but it can also be a PDF file, an Excel spreadsheet, or a Java applet window.

Suppose you have a development environment in place. Now let's continue to build the first "Hello World" struts2 project. The goal of this project is to create a Web application that collects the user's name and displays the "Hello World" username. We will create four components of any STRUTS2 project:

I'm going to use the Eclipse IDE, so all the required components will create a dynamic Web project. So let's start by creating a Dynamic Web project.

To create a Dynamic Web project:
start Eclipse and then File > New > Dynamic Web Project to enter the project name as HelloWorldStruts2 and set the remaining options on the screen:

Select all the default options in the next screen and the final check Generate web.xml deployment descriptor option. This will create a dynamic Web project in Eclipse. Now go to Windows > show View > Project Explorer, and you will see something like the item window as follows:

Now copy the following file from the Struts 2 Lib folder c:struts-2.2.3lib to the Engineering Web-inflib folder, and to do this, you can simply drag and drop all of the following files to the Web-inf Lib folder.

    • Commons-fileupload-x.y.z.jar
    • Commons-io-x.y.z.jar
    • Commons-lang-x.y.jar
    • Commons-logging-x.y.z.jar
    • Commons-logging-api-x.y.jar
    • Freemarker-x.y.z.jar
    • Javassist-.xy.z.ga
    • Ognl-x.y.z.jar
    • Struts2-core-x.y.z.jar
    • Xwork-core.x.y.z.jar

To create an action class:
the action class is the key to the STRUTS2 application, the business logic of most of the action classes we implement. So let's create a Java file Helloworldaction.java Java resources > src com.yiibai.struts2 the content package named below.

The action class responds to user actions when the user clicks on a URL. One or more of the methods in the action class is executed and returns a string result. The result based value, the rendering of a particular JSP page.

Package com.yiibai.struts2;

public class helloworldaction{
 private String name;

 Public String Execute () throws Exception {return
  "success";
 }
 
 Public String GetName () {return
  name;
 }

 public void SetName (String name) {
  this.name = name;
 }
}

This is a very simple class, one named "name" attribute. We have the getter and setter methods for the standard "name" attribute and return the execution method of the string "success".

The STRUTS2 framework creates an object Helloworldaction class and invokes the execution method in response to the user's actions. Put the business logic inside the Execute method, and finally return the string constant. Simply put, for each URL, you must perform an action class, or you can use the name of the class directly as the operation name, or you can use the Struts.xml file to map to some other names as shown below.

Create a View
we need a JSP to submit the final message, this page will be called the Struts2 frame when a predefined action occurs, this mapping will be defined in the Struts.xml file. So let's create the JSP file helloworld.jsp in the Eclipse project under the WebContent folder. To do this, right-click the WebContent folder in Project Explorer, and select New >jsp File.

<%@ page contenttype= "text/html; Charset=utf-8 "%>
<%@ taglib prefix=" s "uri="/struts-tags "%>
 
 

The taglib instruction tells the servlet container that this page will use the Struts 2 label, which will be preceded by S. The S:property label displays the value returned by the GetName () method of the Action class property, Name> Helloworldaction class.

To create a home page:
We also need the index.jsp created in the WebContent folder. The file will act as the initial action URL where the user can click to tell the Struts 2 framework to invoke the Helloworldaction class definition method to render the helloworld.jsp view.

<%@ 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>
 
 

The Hello action definition in the above view file will be mapped to the Helloworldaction class and its execution method uses the Struts.xml file. When the user clicks on the "Submit" button, which causes the STRUTS2 framework to run the execution method defined therein, the Helloworldaction class responds to the corresponding view selection and rendering based on the method of the return value.

Configuration file
We need a map to match URLs, helloworldaction classes (models), and helloworld.jsp (views). The mapping tells the Struts 2 framework class will respond to the user's action (URL), the method of the class will be executed, and the view render is based on the string result, which returns.

So let's create a name called Struts.xml. Because the STRUTS2 requires Struts.xml in the class folder. Therefore, create the Struts.xml file under the Webcontent/web-inf/classes folder. Eclipse does not create a "classes" folder, so you need to do it yourself. To do this, right-click on the Web-inf folder of the Project Explorer and select New > folder. The struts.xml should look like this:

<?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=" Hello " 
   class=" Com.yiibai.struts2.HelloWorldAction " 
   method=" "Execute" >
   <result name= "Success" >/helloworld.jsp </result>
  </action>
 </package>
</struts>

A few words of the above configuration file. Here we set the true constant Struts.devmode, because we are in the program development environment and we need to see some useful log messages. Then, we define a HelloWorld package named. Creating a package is useful when you want to group actions together. In our example, we named our action "Hello", which is the corresponding url/hello.action and backup Helloworldaction.class. Executing the Helloworldaction.class method is a method that the runtime url/hello.action calls. If the result of executing the method returns "Success", then we take the user to helloworld.jsp.

The next step is to create a web.xml file, which is a Struts2 entry point for any request. The entry point for the STRUTS2 application will be the filter defined in a deployment descriptor (Web.xml). Therefore, we will define the entry Oforg.apache.struts2.dispatcher.FilterDispatcher class in Web.xml. Web.xml files in the Web-inf folder that you need to create under WebContent. Create a project when you have established an eclipse's Web.xml file. So let's just change the following:

<?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_3 _0.xsd "
 id=" webapp_id "version=" 3.0 ">
 
 <display-name>struts 2</display-name>
 < welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <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>

We have specified the index.jsp welcome file. We have then configured all URLs running on the Struts2 filter (that is, any URL matching mode/*)

To enable verbose logging:
You can enable full logging, while the Web-inf/classes folder under Struts 2 creates logging.properties files. Keep the following two lines in the property file:


Org.apache.catalina.core.ContainerBase. [Catalina].level = INFO
org.apache.catalina.core.containerbase.[ Catalina].handlers = 
        Java.util.logging.ConsoleHandler

The default logging.properties specifies Consolehandler routing records to stdout, also a file processor. The log level thresholds for handlers can be set using SEVERE, WARNING, INFO, CONFIG, FINE, finer, FINEST or all.

That's it. We are ready to use the Struts 2 framework to run our Hello World application.

Executing the application
Right-click the project name and click the Export > War file File to create a war document. Then deploy this war in Tomcat's WebApps directory. Finally, start the Tomcat server and try to access the URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will give you the following picture:

Enter a value of "Struts2" and submit the page. You should see the page as follows:

Note that you can define the actions in the index Struts.xml file, in which case the index page http://localhost:8080/HelloWorldStruts2/index.action can be invoked. The following checks how to define an exponent as an action:

<?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=" index ">
   < Result >/index.jsp</result>
  </action>

  <action name= "Hello" 
   class= " Com.yiibai.struts2.HelloWorldAction " 
   method=" "Execute" >
   <result name= "Success" >/ helloworld.jsp</result>
  </action>

 </package>
</struts>

One example demonstrates struts: Student status Query (fuzzy query)

Requirements Analysis: Query student status, to involve the operation of the database, to involve the form of the page operation.
Enter the student name and click on the Blur query. Returns the results of the query.
The purpose here is only to show the knowledge points of struts. Page operations, such as detailed details do not make too many requirements.
on the basis of the above, under the temp package new Queryform.java and Queryaction.java under src new two packages, one is the bean file, an operational database, respectively, Com.bean and Com.dao. Com.bean the new Studentdao.java file under Com.dao under new Studentbean.java file
Webroot new queryform.jsp files and result.jsp files index.jsp can do a navigation page (both when new projects are created). The contents of the
 
file are as follows:
Studentbean.java file:

Package Com.bean; Encapsulates a student's data public class Studentbean {private string stuid; private string stuname; private string stusex; private Stri
Ng Stubir;
 
Private String Stuadd;
 
Public String Getstuid () {return stuid;}
 
public void Setstuid (String stuid) {this.stuid = Stuid;}
 
Public String Getstuname () {return stuname;}
 
public void Setstuname (String stuname) {this.stuname = Stuname;}
 
Public String Getstusex () {return stusex;}
 
public void Setstusex (String stusex) {this.stusex = Stusex;}
 
Public String Getstubir () {return stubir;}
 
public void Setstubir (String stubir) {This.stubir = Stubir;}
 
Public String Getstuadd () {return stuadd;}
 
public void Setstuadd (String stuadd) {this.stuadd = Stuadd;}
 
Studentdao.java file: Package Com.dao;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
 
Import java.util.ArrayList;
 
Import Com.bean.StudentBean; public class Studentdao {private connectiOn conn = null; public void Initconnection () {try {class.forname ("Com.microsoft.sqlserver.jdbc.SQLServerDriver"); conn =
DriverManager. getconnection ("jdbc:sqlserver://localhost:1433;" + "Databasename= Student status information", "sa", "sa");
 
The catch (Exception e) {}} public ArrayList Querystubyname (String sname) {ArrayList stus = new ArrayList ();
String sql = "Select school number, name, sex, date of birth," + "home address from list where name like '% ' + sname + '% '";
System.out.println ("Studentdao.java querystubyname function Sname=" +sname);
try {this.initconnection ();
 
ResultSet rs = conn.createstatement (). executequery (SQL); while (Rs.next ()) {Studentbean Stu = new Studentbean (); Stu.setstuid (rs.getstring ("School Number"); Stu.setstuname (Rs.getstring (
"Name"));
Stu.setstusex (rs.getstring ("gender"));
Stu.setstubir (rs.getstring ("Birth date"));
Stu.setstuadd (Rs.getstring ("Home Address"));
Stus.add (Stu);
 
} catch (SQLException e) {e.printstacktrace ();} finally {this.closeconnection ();}
return stus; public void CloseConnection () {try {if Conn!= null) {conn.close (); conn = null;}}
catch (Exception e) {e.printstacktrace ();}}
 }

index.jsp file:

 <%@ page language= "java" import= "java.util.*" pageencoding= "GB18030"%> <%
String path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  
 

 
queryform.jsp file:

<%@ page language= "java" import= "java.util.*" pageencoding= "GB18030"%> <% String Path = Request.getcontextpath
();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

 
result.jsp file:

 <% @page import= "Com.bean.StudentBean"%> <% @page import= "Com.dao.StudentDao "%> <%@ page language=" java "import=" java.util.* "pageencoding=" GB18030 "%> <% String Path =
Request.getcontextpath ();
String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  
 

Return results page

<br>
<%arraylist stus = (ArrayList) request.getattribute ("Stus");%>
<table>
<tr >
<td>
School No.
</td>
<td>
name
</td>
<td>
sex 
</td>
<td>
date of birth
</td>
<td>
Home address
</td>
</tr >
 
<% for
(int i=0;i<stus.size (); i++) {
Studentbean stu= (Studentbean) stus.get (i);
%>
<tr>
<td>
<%=stu.getstuid ()%> 
</td>
<td>
<%=stu.getstuname ()%> 
</td>
<td>
<%=stu.getstusex ()%> 
</td>
<td>
<%=stu.getstubir ()%> 
</td>
<td>
<%=stu.getstuadd ()% > 
</td>
</tr>
<%}%>
</table>
</body>
 
 


queryform.jsp file:

Package project02;
 
Import Org.apache.struts.action.ActionForm;
This is actionform in order to accommodate the form's value//specification://1-must inherit org.apache.struts.action.ActionForm//2-must write element attributes with the same name as the form element//3-must be registered in the Struts configuration file @SuppressWarnings ("Serial") public class Queryform extends actionform{public queryform () {System.out.println ("
Queryform.java constructor function ");
 
Private String sname;
 
Public String Getsname () {System.out.println ("Run Getsname function in Queryform.java"); return sname;}
public void Setsname (String sname) {this.sname = sname;
SYSTEM.OUT.PRINTLN ("Operation of setsname function in Queryform.java");
 
} Queryaction.java File: Package project02;
 
Import java.util.ArrayList;
Import Javax.servlet.http.HttpServletRequest;
 
Import Javax.servlet.http.HttpServletResponse;
Import org.apache.struts.action.Action;
Import Org.apache.struts.action.ActionForm;
Import Org.apache.struts.action.ActionForward;
 
Import org.apache.struts.action.ActionMapping;
 
Import Com.dao.StudentDao; Queryaction is responsible for receiving actionform data and processing//rules://1-must inherit org.apache.struts. Action. Action//2-overrides Excute method business logic//3-registers the class in the configuration file with the public class Queryaction extends action{public queryaction () {System.out.pri
Ntln ("Queryaction.java constructor runs"); @Override public Actionforward Execute (actionmapping mapping, actionform form, httpservletrequest request, HTTPSERVL
Etresponse response) throws Exception {Queryform queryform= (queryform) Form;
String Sname=queryform.getsname ();
Sname=new String (sname.getbytes ("iso-8859-1"), "gb2312");
Studentdao studentdao=new Studentdao ();
ArrayList Stus=studentdao.querystubyname (sname);
Request.setattribute ("Stus", Stus);
SYSTEM.OUT.PRINTLN ("Execute function runs in Queryaction.java");
Jump Actionforward af=new Actionforward ("/result.jsp");
The configuration file can be set to jump//Actionforward AF = Mapping.findforward ("result") in the following ways;
The above method has an exception warning: Warning: Unable to found ' result ' forward.
Return AF;
 }
}

&NBSP
The above file has not been able to implement struts, and the relationship between the individual files is configured in the Struts-config.xml file. The
configuration is as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE struts-config Public "-//apache Software foundation//dtd struts Configuration 1.2//en" "http:// Struts.apache.org/dtds/struts-config_1_2.dtd "> <struts-config> <data-sources/> <!--register here Actionfo RM--> <form-beans> <!--name: Name Type: The path of the class--> <form-bean name= "Queryform" type=. Queryform "></form-bean> </form-beans> <global-exceptions/> <!--set the logical name of the URL globally, so the action can be To identify the--> <global-forwards> <forward name= "result" path= "/result.jsp" ></forward> </ Global-forwards> <!--here Register action--> <action-mappings> <!--name:actionform name type: Classpath path: Client Commit The path specified temporarily to the server--> <action name= "Queryform" path= "/query" type= "project02". Queryaction "></action> </action-mappings> <message-resources parameter=" project02.
 Applicationresources "/> </struts-config>

&NBSP
Finally, publish the project file, start Tomcat, and test with the browser.
 
 
Now, to sort it out. Build functionality based on requirements. Create form and action files as required. Finally, the Struts-config.xml file is configured.
 
Test procedure:
1-Enter the index.jsp navigation page, click the Student status query to enter the queryform.jsp page
2- Enter the Queryform.jsp page, in the text box to enter a student name in one or two words for fuzzy query. Click on the Blur query.
<form action= "/project02/query.do" method= "POST"
     Please enter student name: <input name= " Sname ""
<input type= "Submit" value= "Fuzzy query"
</form>
Action: Specifies the path to be executed by the action Method: The way it is submitted--post not display information, get display information
3-entered/project02/query.do  to Queryaction.java execution. Why was it executed under the Queryaction.java file?

 <!--register here actionform--> 
 <form-beans>
 <!--name: Name Type: The path of the class-->
 <form-bean name= " Queryform "Type=" project02. Queryform "></form-bean>
 </form-beans>
 
 <!--here Register action-->
 <action-mappings >
 <!--name:actionform name type: Classpath path: Client submits to server temporarily specified path-->
 <action name= "Queryform"/ Query "Type=" project02. Queryaction "></action>
 </action-mappings>

Because the configuration file is already configured. Registration action in the path= "/query" is query.do just don't have. do suffix. The path to the type class has been specified here: project02. Queryaction so execute Queryaction.java file.
4-The next is the Java file, most can read.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.