struts2的登录和退出

freshly debugged source:http://blog.csdn.net/weiyanghuadi/article/details/9081879

SessionAware用的是依赖注入。而ActionContext.getContext().getSession()不是。不过,它们的作用是相同的,都是返回一个Map,这跟servlet API中的HttpSession不一样。

下面的例子使用ActionContext.getContext().getSession()

如果你想使用SessionAware,那就要让Action实现SessionAware接口,并建立setters和getters。

login.jsp


		
		


package vaannila;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext;
import java.util.*;

public class loginAction1 extends ActionSupport {

	private String userId;
	private String password;

	@Override
	public String execute() throws Exception {

		if ("admin".equals(userId) && "admin".equals(password)) {
			Map session = ActionContext.getContext().getSession();
			session.put("logged-in", "true");
			return SUCCESS;
		} else {
			return ERROR;
		}
		// return SUCCESS;
	}

	public String logout() throws Exception {

		Map session = ActionContext.getContext().getSession();
		session.remove("logged-in");
		return SUCCESS;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}
}


		
			
			/success2.jsp
			/login.jsp
		
		
			/checkLogin.jsp
		
	

success2.jsp


	Welcome, you have logined.
	
Session Time: <%=new Date(session.getLastAccessedTime())%>

Logout

package vaannila;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext;
import java.util.*;

public class logoutAction extends ActionSupport {
	@Override
	public String execute() throws Exception {
		System.out.println("the action name in struts and href in jsp is a little bit of different!");
		Map session = ActionContext.getContext().getSession();
		session.remove("logged-in");
		return SUCCESS;
	}
}

checkLogin.jsp


	
		
	

The following warning:

WARNING: No configuration found for the specified action: 'denglu' in namespace: ''. Form action defaulting to 'action' attribute's literal value.

and the typo


cost me half an hour!

原文:http://pampanasatyanarayana.wordpress.com/2012/05/12/login-and-logout-in-struts2/ 

the more original is vaannila

源代码:http://pan.baidu.com/share/link?shareid=3471752733&uk=3878681452

你可能感兴趣的:(Struts2)