`
厚积ss薄发
  • 浏览: 3679 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

第一个struts2例子

阅读更多
第一步:到官网下载struts2jar包 http://struts.apache.org/
第二步:把jar包导入项目中,我们这个例子只需要要一些基本包
struts2-core-2.3.14.jar,xwork-core-2.3.14.jar,ognl-3.0.6.jar,javassist-3.11.0.GA.jar
第三步:配置一些文件
1.web.xml文件
在文件中加入下面代码:
    <filter>
        <filter-name>struts2</filter-name>
        <filter- class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
2.struts.xml 该文件放在src目录下
代码如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<constant name="struts.i18n.encoding" value="GB18030"/>
<package name="default" namespace="/" extends="struts-default">
<action name="hello" class="com.su.struts.action.Hello" > <result>/hello_world.jsp</result>
  </action>
  </package>
</struts>
第四步:写Hello.java代码
package com.su.struts.action;
import java.util.Date;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.Action;
public class Hello {
private String name;
public String sayName(){
ServletActionContext.getRequest().setAttribute("date", new Date());  return Action.SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第五步:写页面
1.index.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
<%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
<%--<form action="hello!sayName.action" method="post">
名字<input type="text" name="name"/><br/>
<input type="submit" value="测试"/>
</form> --%>
<s:form action="hello!sayName.action" method="post">
<s:textfield name="name" label="名字"></s:textfield>
<s:submit value="测试" align="center"></s:submit>
</s:form>
</body>
</html>
2.hello_world.jsp页面
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
<h1><s:property value="name"/> Hello World! 时间:<s:property value="#request.date"/></h1><br>
<s:debug></s:debug>
</body>
</html>
第六步:发布运行
http://127.0.0.1:8080/struts_01/index.jsp
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics