struts2学习札记(3)<struts2注解配置和ActionContext>

struts2可以通过ActionContext访问Servlet API,ActionContext 获得的是map对象
用法

@SuppressWarnings("unchecked")
@Override
public String execute() throws Exception {
ActionContext ctx=ActionContext.getContext();
Integer total=(Integer)ctx.getApplication().get("total");
if(total==null){
total=1;
}
else{
total++;
}
ctx.getApplication().put("total", total);

//记录单个会员的访问的次数
if(name!=null&&password!=null){
if(name.equals("hello")&&password.equals("world")){
Integer memberTotal=(Integer)ctx.getSession().get("member");
if(memberTotal==null){
memberTotal=1;
}
else{
memberTotal++;
}
ctx.getSession().put("member", memberTotal);
}
this.setMessage("欢迎您登陆");
}
return SUCCESS;
}


struts2 zero configuration(注解配置)

package com.struts2;

import java.util.Map;

import org.apache.struts2.config.Namespace;
import org.apache.struts2.config.ParentPackage;
import org.apache.struts2.config.Result;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@ParentPackage("struts-default")
@Namespace("/test")
@Result(name="success", value="/index.jsp")

public class TestAction extends ActionSupport {

/**
* struts2注解配置
*/
private static final long serialVersionUID = 1L;
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@SuppressWarnings("unchecked")
@Override
public String execute() throws Exception {
Map<String,String> map=null;
map=ActionContext.getContext().getSession();
map.put("username", this.getUsername());
System.out.println ("姓名"+getUsername());
return SUCCESS;
}


}

在web.xml改为

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
<init-param>
<param-name>actionPackages</param-name>
<param-value>com.struts2</param-value>
</init-param>

</filter>


在jsp页面

<s:form method="post" action="test/test.action">
<s:textfield name="username" label="用户名"></s:textfield>
<s:submit value="提交"></s:submit>
</s:form>

说明:如果用注解配置,有个很大的优点,就是在企业开发,每个程序员不用写struts.xml文件,这便于管理,因为再公司开发项目只会用

一个应用服务器,如果用struts2开发只会用到一个struts.xml,程序员只要写action就行了
注解配置就是struts.xml什么也不要配置,注意一点用注解配置类名必须是*Action.java这种格式,不然会找不到action,还有再jsp
访问这个action,必须是小写如test.action.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值