Action访问servlet API

Action处理类:

package com.crazyit.app.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.convention.annotation.*;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;


@Namespace("/")
@Results({
    @Result(name="success",location="/WEB-INF/content/welcome.jsp")
})
public class loginAction extends ActionSupport{
    private String username;
    private String password;
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String execute() throws Exception {
        if("lidian".equals(username) && "123".equals(password)) {
            return SUCCESS;
        }else {
            return ERROR;
        }
    }
    @Action("login")
    public String login() throws Exception{
        if("lidian".equals(username) && "123".equals(password)) {
            /*设置application范围内属性*/
            ActionContext.getContext().getApplication().put("counter", 1);
            /*设置session范围内属性*/
            ActionContext.getContext().getSession().put("username", username);
            /*设置request范围内属性*/
            ActionContext.getContext().put("tip", "您已经登陆");
            
            return SUCCESS;
        }else {
            return ERROR;
        }
    }
    
}

jsp访问数据:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@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=UTF-8">
<title>welcome</title>
</head>
<body>
    <h1>欢迎,${sessionScope.username }</h1>
    <h2>当前访问量:${applicationScope.counter }</h2>
    <h3>提示消息:${requestScope.tip }</h3>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/lidian/p/8967298.html
今日推荐