在Java的Struts框架下进行web编程的入门教程
当点击一个超链接或提交一个html表单在struts2 的 web应用程序,输入所收集被发送到一个java类称为操作控制器。当动作执行后,结果选择了一个资源来呈现响应。资源通常是一个jsp,但它也可以是一个pdf文件,excel电子表格,或一个java applet 窗口。
假设已经建立开发环境。现在让我们继续为第一个 “hello world” 的 struts2 项目构建。这个项目的目的是建立一个web应用程序,它收集用户的姓名,并显示“hello world” 用户名。我们将创建任何struts2项目的四个组成部分:
我打算使用eclipse ide,所以所有必需的组件将创建一个动态web项目下。所以,让我们开始创建动态web项目。
创建动态web项目:
启动eclipse,然后再 file > new > dynamic web project 输入工程名称为 helloworldstruts2 并设置屏幕中给出其余的选项:
选择在接下来的画面中的所有默认选项和最后检查 generate web.xml deployment descriptor 选项. 这将创建一个动态web项目在eclipse。现在去 windows > show view > project explorer, 会看到项目窗口的东西如下:
现在复制下列文件从struts 2 lib 文件夹 c:struts-2.2.3lib 到工程 web-inflib 文件夹,要做到这一点,你可以简单地将以下的所有文件拖放复制到web-inf lib文件夹。
- 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
创建动作类:
action类是 struts2 应用程序的关键,我们实现的大部分动作类中的业务逻辑。因此,让我们创建一个java文件helloworldaction.java java resources > src 在下面给出的内容包名 com.yiibai.struts2 。
action类响应用户操作,当用户点击一个url。 action类中的方法中的一个或多个被执行并返回一个字符串结果。基于结果的值,一个特定的jsp页面的呈现方式。
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; } }
这是一个非常简单的类,一个名为“name”属性。我们有标准的“name”属性的getter和setter方法,并返回字符串“success”的执行方法。
struts2框架将创建一个对象helloworldaction类并调用执行方法在响应用户的动作。把业务逻辑里面的execute方法,最后返回的字符串常量。简单地说为每个网址,必须执行一个动作类,要么就可以直接使用这个类的名称作为操作名,也可以使用struts.xml文件如下所示映射到一些其他的名字。
创建视图
我们需要一个jsp提交最后的消息,这个页面会被称为struts2框架一个预定义的动作时,会发生这种映射将被定义在struts.xml文件。因此,让我们一起创造在eclipse项目在webcontent文件夹下面的jsp文件helloworld.jsp。要做到这一点,右键单击webcontent文件夹在项目资源管理器,选择new >jsp file。 .
<%@ page contenttype="text/html; charset=utf-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>hello world</title> </head> <body> hello world, <s:property value="name"/> </body> </html>
taglib指令告诉servlet容器,这个页面将使用struts 2的标签,这些标签将之前由s。 s:property标签显示动作类属性"name> helloworldaction类的getname()方法返回的值。
创建主页:
我们还需要在webcontent文件夹中创建的index.jsp。该文件将作为初始动作url,用户可以在其中点击告诉struts 2框架调用 helloworldaction类定义的方法呈现 helloworld.jsp 视图。
<%@ 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>hello world</title> </head> <body> <h1>hello world from struts2</h1> <form action="hello"> <label for="name">please enter your name</label><br/> <input type="text" name="name"/> <input type="submit" value="say hello"/> </form> </body> </html>
hello 动作定义在上面的视图文件将被映射到helloworldaction类和其执行方法使用struts.xml文件。当用户点击“提交”按钮,将导致struts2框架运行的执行方法定义的在其中,helloworldaction类根据返回值的方法,将相应的视图选择和渲染作为响应。
配置文件
我们需要一个映射,以配合网址,helloworldaction类(模型),和的helloworld.jsp的(视图)。映射讲述了struts 2框架类将响应用户的操作(url),这个类的方法将被执行,查看渲染基于字符串结果,该方法返回。
因此,让我们创建一个名为struts.xml中。由于struts2 要求struts.xml中存在类“文件夹中。因此,创建struts.xml文件的webcontent/ web-inf/classes文件夹下。 eclipse不创建“classes”文件夹,所以需要自己做。要做到这一点,在项目资源管理器的web-inf文件夹上点击右键并选择new > folder。struts.xml中应该像这样:
<?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>
上面的配置文件的几句话。在这里,我们设置为 true常量struts.devmode,因为我们正在程序开发环境,我们需要看到一些有用的日志消息。然后,我们定义了一个名为helloworld 包。创建一个包是有用的,当想一起进行分组动作。在我们的例子中,我们将我们的行动命名为“hello”,这是相应的url /hello.action 和备份helloworldaction.class。执行helloworldaction.class方法是运行时url /hello.action 调用的方法。如果执行方法的结果返回“success”,然后我们把用户到 helloworld.jsp。
下一步是创建一个web.xml文件,这是一个struts2的任何请求的入口点。struts2应用程序的入口点,将是一个部署描述符(web.xml)中定义的过滤器。因此,我们将定义在web.xml中条目oforg.apache.struts2.dispatcher.filterdispatcher类。 web.xml文件中需要创建的web-inf文件夹下的webcontent下。已经建立的eclipse的web.xml文件时为创建项目。所以,让我们只需要修改如下:
<?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>
我们已经指定index.jsp的欢迎文件。然后,我们已经配置struts2的过滤器上运行的所有url(即任何url匹配模式/ *)
启用详细日志:
可以启用完整的日志记录功能,而struts 2的web-inf/classes下文件夹创建logging.properties文件。保持在属性文件中的以下两行:
org.apache.catalina.core.containerbase.[catalina].level = info org.apache.catalina.core.containerbase.[catalina].handlers = java.util.logging.consolehandler
默认logging.properties指定consolehandler的路由记录到stdout,也是一个文件处理器。处理程序的日志级别阈值可以设置使用 severe, warning, info, config, fine, finer, finest 或 all.
就是这样。我们已经准备好使用struts 2框架来运行我们的hello world应用程序。
执行应用程序
右键点击项目名称,并单击 export > war file文件创建一个war文件。然后部署在tomcat 的 webapps目录下这个war。最后,启动tomcat 服务器和尝试访问url http://localhost:8080/helloworldstruts2/index.jsp。这会给出以下画面:
输入一个值“struts2”,并提交页面。应该看到页面如下:
注意,可以定义索引struts.xml文件中的动作,在这种情况下,可以调用索引页http://localhost:8080/helloworldstruts2/index.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>
一个实例演示struts:学生学籍查询(模糊查询)
需求分析:查询学生学籍,要涉及到数据库的操作,要涉及到页面的表单操作。
输入学生名字,点击模糊查询。会返回查询结果。
这里目的只是显示struts的知识点。页面操作等详细细节不做过多要求。
在以上的基础上,在temp包下新建queryform.java和queryaction.java 在src下新建两个包,一个是bean文件的,一个操作数据库的,分别是com.bean和com.dao。com.bean下新建studentbean.java文件com.dao下新建studentdao.java文件
webroot新建queryform.jsp文件和result.jsp文件index.jsp可以做导航页面(新建工程时既有)。
各个文件的内容如下:
studentbean.java文件:
package com.bean; //封装一个学生的资料 public class studentbean { private string stuid; private string stuname; private string stusex; private string 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文件: 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=学生学籍信息", "sa", "sa"); } catch (exception e) { } } public arraylist querystubyname(string sname) { arraylist stus = new arraylist(); string sql = "select 学号,姓名,性别,出生年月," + "家庭住址 from 学籍表 where 姓名 like '%" + sname + "%'"; //system.out.println("studentdao.java中querystubyname函数sname="+sname); try { this.initconnection(); resultset rs = conn.createstatement().executequery(sql); while (rs.next()) { studentbean stu = new studentbean(); stu.setstuid(rs.getstring("学号")); stu.setstuname(rs.getstring("姓名")); stu.setstusex(rs.getstring("性别")); stu.setstubir(rs.getstring("出生年月")); stu.setstuadd(rs.getstring("家庭住址")); 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文件:
<%@ 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"> <html> <head> <base href="<%=basepath%>"> <title>my jsp 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> this is my jsp page. <br> <a href="queryform.jsp">学生学籍查询</a> </body> </html>
queryform.jsp文件:
<%@ 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"> <html> <head> <base href="<%=basepath%>"> <title>my jsp 'queryform.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> 查询表单 <br> <form action="/project02/query.do" method="post"> 请您输入学生姓名:<input name="sname"> <input type="submit" value="模糊查询"> </form> </body> </html>
result.jsp文件:
<%@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"> <html> <head> <base href="<%=basepath%>"> <title>my jsp 'queryform.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body>
返回结果页面
<br> <%arraylist stus =(arraylist)request.getattribute("stus"); %> <table> <tr> <td> 学号 </td> <td> 姓名 </td> <td> 性别 </td> <td> 出生年月 </td> <td> 家庭住址 </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> </html>
queryform.jsp文件:
package project02; import org.apache.struts.action.actionform; //这是actionform为了容纳表单的值 //规范: //1-必须继承org.apache.struts.action.actionform //2-必须编写和表单元素重名的元素属性 //3-必须在struts配置文件中注册 @suppresswarnings("serial") public class queryform extends actionform{ public queryform(){ system.out.println("queryform.java构造函数运行"); } private string sname; public string getsname() { system.out.println("queryform.java中getsname函数运行"); return sname; } public void setsname(string sname) { this.sname = sname; system.out.println("queryform.java中setsname函数运行"); } } queryaction.java文件: 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负责接收actionform的数据,然后进行处理 //规则: //1-必须继承org.apache.struts.action.action //2-重写excute方法业务逻辑 //3-将这个类在配置文件中注册 public class queryaction extends action{ public queryaction(){ system.out.println("queryaction.java构造函数运行"); } @override public actionforward execute(actionmapping mapping, actionform form, httpservletrequest request, httpservletresponse 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("queryaction.java中execute函数运行"); // 跳转 actionforward af=new actionforward("/result.jsp"); //设置了配置文件可以用以下方式跳转 // actionforward af = mapping.findforward("result"); //以上方式出现异常警告:警告: unable to find 'result' forward. return af; } }
编写了以上的文件还未能实现struts的功能,要对各个文件之间的关系在struts-config.xml文件进行配置。
配置如下:
<?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 /> <!-- 在此注册actionform --> <form-beans> <!-- name:名称 type:类的路径 --> <form-bean name="queryform" type="project02.queryform"></form-bean> </form-beans> <global-exceptions /> <!-- 设置url的逻辑名称 全局性的,所以的action都可以识别到--> <global-forwards> <forward name="result" path="/result.jsp"></forward> </global-forwards> <!-- 这里注册action --> <action-mappings> <!-- name:actionform的名称 type:类的路径 path:客户端提交给服务器临时指定的路径 --> <action name="queryform" path="/query" type="project02.queryaction"></action> </action-mappings> <message-resources parameter="project02.applicationresources" /> </struts-config>
最后,对工程文件进行发布,启动tomcat,用浏览器测试。
现在,来梳理清楚。根据需求建立功能。根据要求建立form和action文件。最后对struts-config.xml文件进行配置。
测试操作步骤:
1-进入index.jsp导航页面,点击学生学籍查询进入了queryform.jsp页面
2-进入了queryform.jsp页面,在文本框输入学生名中的一个或两个字进行模糊查询。点击模糊查询。
<form action="/project02/query.do" method="post">
请您输入学生姓名:<input name="sname">
<input type="submit" value="模糊查询">
</form>
action:指定了action要执行的路径 method:提交的方式--post不显示信息,get显示信息
3-进入了/project02/query.do 到了queryaction.java执行。这里为什么是到queryaction.java文件下执行的呢?
<!-- 在此注册actionform --> <form-beans> <!-- name:名称 type:类的路径 --> <form-bean name="queryform" type="project02.queryform"></form-bean> </form-beans> <!-- 这里注册action --> <action-mappings> <!-- name:actionform的名称 type:类的路径 path:客户端提交给服务器临时指定的路径 --> <action name="queryform" path="/query" type="project02.queryaction"></action> </action-mappings>
因为配置文件已经完成了配置。注册action中的path=”/query”就是query.do只是没有了.do后缀。这里已经指定了type类的路径为:project02.queryaction 所以执行queryaction.java文件。
4-接下来的就是java文件了,大都能看懂。