Struts2---第一站HelloWorld

本文介绍了使用Struts2框架搭建简单应用的过程,包括环境配置、国际化资源文件设置、表单验证及页面流转等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天开始学习struts2,为了激励自己成长,特将编码过程中遇到的大大小小的问题汇总出来。

第一个实例需求:用户填写用户姓名的index.jsp,负责处理请求的业务控制器HelloAction负责处理请求,如果请求无效返回index.jsp,如果验证成功,转向显示欢迎信息的welcome.jsp。

        实现步骤:

(1)新建Web Project--HelloWorld,将Struts2.1.8的几个必需的Jar包(commons-logging-1.0.4.jar、commons-io.1.3.2.jar、freemarker-2.3.15.jar、ognl-2.7.3.jar、struts2-core-2.1.8.1.jar、commons-fileupload-1.2.1.jar、xwork-2.0.4.jar)复制到WEB-INF/lib目录下。

(2)修改web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>struts2</filter-name>                                                                  -------------------为HelloWorld应用加入了Struts2.1框架功能
<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>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

(3)在src下创建国际化消息资源文件messageResource_zh_CN.properties:

title.text=HelloWorld
label.name=Name:
submit=submit
reset=reset
label.welcome=hello
Username.error=sorry

(原来是想写成中文的,但是一直出现中文乱码的情况,为了尽快见到效果,不得不把gbk改为了utf-8,并且把properties的内容也全换为英文)

(4)在src下创建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.i18n.encoding" value="utf-8"></constant>
<constant name="struts.locale" value="zh_CN"></constant>
<constant name="struts.custom.i18n.resources" value="messageResource"></constant>
<constant name="struts.devMode" value="false"></constant>
<constant name="struts.ui.theme" value="simple"></constant>
<package name="hello" extends="struts-default">
<action name="sayhello" class="com.helloworld.struts.action.HelloAction">
<result>/welcome.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>

(5)创建HelloAction

package com.helloworld.struts.action;


import com.opensymphony.xwork2.ActionSupport;


public class HelloAction extends ActionSupport{


/**

*/
private static final long serialVersionUID = 1L;
private String sername;
private String resultStr;
public String execute(){
resultStr="这是业务控制器HelloAction处理的结果内容!";
return SUCCESS;
}
public void validate(){
if(sername==null||sername.trim().length()<1){
addFieldError("sername",getText("Username.error"));
}
}
public String getSername(){
return sername;
}
public void setSername(String sername){
this.sername=sername;
}
public String getResultStr(){
return resultStr;
}
public void setResultStr(String resultStr){
this.resultStr=resultStr;
}


}

(6)创建index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"  %>
<%
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><s:text name="title.text"></s:text></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> 
  <h2><s:text name="title.text"></s:text></h2><br/>
   <s:form action="sayhello">
    <s:text name="label.name"></s:text>
    <s:textfield name="sername" size="22"></s:textfield>
    <s:submit key="submit" value="submit"></s:submit>
    <s:reset key="reset" value="reset"></s:reset>
    </s:form>
    <s:if test="hasFieldErrors()">
    <s:fielderror></s:fielderror>
    </s:if> 
  </body>
</html>

(7)创建welcome.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
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><s:text name="title.text"></s:text></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>
    ${sername },<s:text name="label.welcome"></s:text><br/>
    ${resultStr }
  </body>
</html>

(8)部署并运行,在浏览器地址栏中输入http://localhost:8080/HelloWorld就可以运行出结果。

运行结果:




重点:

中间出现的问题:

1,原先的properties文件是这样写的:

title.text=HelloWorld
label.name=Name:
label.submit=submit
label.reset=reset
label.welcome=hello
Username.error=sorry

index.jsp中也是<s:submit key="label.submit" ></s:submit>
     <s:reset key="label.reset" ></s:reset>

但是出现ognl.OgnlException: target is null for setProperty(null, "submit", [Ljava.lang.String;@6efc82)异常信息,我上网搜了好多答案,说是出了错误,将properties文件中label.submit改为label_submit或者改为submit就行了,估计是冲突之类的问题,但是我改为Label_submit后竟然根本不识别,又改为submit后就识别了.

而且两个按钮的value是空的,就将value="submit"和value="reset"加上了。

2,点击submit后,一直跳回index.jsp,并且提示sorry,可以看出是HelloAction中的validate方法中判断sername为空,可是我明明输入名字了,为什么呢?Struts2在点击submit提交了表单之后都会通过get/set方法将想对应的值传递给属性,输入框的名称为sername,HelloAction中的属性名也是sername,但是为什么没有匹配呢?原因很简单,我忘了写get/set方法了,加上这些方法,程序就运行成功了。


结尾:说一下我对这个程序运行流程的理解。

(1)在浏览器地址栏中输入http://localhost:8080/HelloWorld就可以运行出结果的原因是,这个请求首先被web.xml中配置的核心过滤器StrutsPrepareAndExecuteFilter拦截了,根据welcome-file属性设置的index.jsp直接导向index.jsp;

(2)用户在填写完index.jsp中的信息后点击submit按钮,将请求提交给sayhello.action。

(3)sayhello.action一样被StrutsPrepareAndExecuteFilter拦截,该过滤器首先清理当前线程的ActionContext和Dispatcher防止内存泄露,接下来询问ActionMapper来决定这个请求是否需要调用某个Action,由于sayhello是以.action结尾的,因此StrutsPrepareAndExecuteFilter把请求的处理交给ActionProxy(Action代理)。ActionProxy通过Configuration Manager询问Struts2.1的配置文件struts.xml,找到需要调用的com.helloworld.struts.action.HelloAction。

(4)ActionProxy创建HelloAction实例负责处理请求sayhello.action。

(5)在Action执行环境中首先调用Struts2.1自带的一系列内部拦截器或者用户定义的拦截器,然后调用validate()方法对表单字段进行有效性验证,验证过程如果出错调用addFieldError方法添加字段错误消息,并且跳转到struts.xml配置中指定的名为“input”的result使用户进行表单重填,如果验证通过则struts.xml中指定的result方法或者Action默认的execute()方法进行请求的业务处理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值