?? loginaction.java
字號:
package bookstore;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.hibernate.Query;
import org.hibernate.Session;
import bookstore.database.HibernateUtil;
import bookstore.database.Userinfo;
public class LoginAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm srcForm,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionMessages errors = new ActionMessages();
ActionForward forward = mapping.findForward("frontPage");
LoginForm form = (LoginForm) srcForm;
try {
// 檢查用戶名、密碼是否合法
Session dbSession = HibernateUtil.currentSession();
HttpSession session = request.getSession();
String hqlStr = " from Userinfo as u where u.username=:username and u.pwd=:pwd";
Query query = dbSession.createQuery(hqlStr);
query.setString("username", form.getUserName());
query.setString("pwd", form.getPassword());
List result = query.list();
System.out.println(result.size());
if (result.size() == 0) {
// 不合法
errors.add("inputErrors", new ActionMessage("index.loginError"));
this.saveErrors(request, errors);
forward = mapping.findForward("failed");
} else {
// 合法后保存到Session中
Userinfo user = (Userinfo) result.get(0);
session.setAttribute("user", user);
if(user.getPower() == 1) {
// 當用戶權限為1時在session中做標記
// 此時只做一個名為admin的session為標記
// 當檢測到這個session存在時表明當前用戶為管理員
// 而不管admin這個session的內容是什么
session.setAttribute("admin", "true");
}
}
} catch (Exception e) {
errors.add("dbError", new ActionMessage("globle.dbError"));
this.saveErrors(request, errors);
forward = mapping.getInputForward();
}
return forward;
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -