1. 程式人生 > >struts攔截器(實現登入)

struts攔截器(實現登入)

攔截器的使用:

package com.beiruan.xitongguanli.interceptor;

import java.util.Map;

import com.beiruan.xitongguanli.entity.User;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class QuanXianInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Map<String, Object> session = invocation.getInvocationContext().getSession();
		User user = (User) session.get("loginUser");
		if(user == null){
			return Action.LOGIN;
		}else{
			return invocation.invoke();
		}
	}

}

<interceptors>
			<!-- 宣告這個類是攔截器 -->
			<interceptor name="myTimerInterceptor" class="com.beiruan.xitongguanli.interceptor.MyTimerInterceptor"/>
			<interceptor name="QuanXianInterceptor" class="com.beiruan.xitongguanli.interceptor.QuanXianInterceptor"/>
			<!-- 攔截器棧 -->
			<interceptor-stack name="myDefaultInterceptor">
				<interceptor-ref name="myTimerInterceptor"/>
				<interceptor-ref name="QuanXianInterceptor"/>
				<interceptor-ref name="defaultStack"/>
			</interceptor-stack>
		</interceptors>
		<!-- 修改預設攔截器 -->
		<default-interceptor-ref name="myDefaultInterceptor"/>
			

<action name="login" class="com.beiruan.xitongguanli.action.UserAction"
			method="login">
			<result name="login">/login.jsp</result>
			<result name="success">/success.jsp</result>
			<result name="error">/error.jsp</result>
			<interceptor-ref name="defaultStack"/>
			<!-- 使攔截器作用於這個action -->
		</action>

package com.beiruan.xitongguanli.action;

import java.util.List;

import com.beiruan.util.Constants;
import com.beiruan.xitongguanli.entity.User;
import com.beiruan.xitongguanli.service.UserService;
import com.beiruan.xitongguanli.service.impl.UserServiceImpl;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {
	private String username;
	private String password;
	public void setUsername(String username) {
		this.username = username;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	private int userId;
	public void setUserId(int userId) {
		this.userId = userId;
	}

	private UserService userService = new UserServiceImpl();
	private List<User> userList;
	public List<User> getUserList() {
		return userList;
	}
	
	
	public String login() throws Exception {
		User user = userService.login(username, password);
		if(user != null){
			ActionContext.getContext().getSession().put(Constants.LOGIN_USER, user);
			userList = userService.getAllUserList();
			return SUCCESS;
		}else{
			return ERROR;
		}
	}
	
	public String delete() throws Exception {
		userService.deleteUserByUserId(userId);
		return SUCCESS;
		
	}
}