4.6. 修改 LoginAction.java 文件
在LoginAction.java类中定义属性public IUsersBusiness usersBusiness;并定义了一个setUsersBusiness(IUsersBuseiness usersBusiness)方法,可以让我们注入IUsersBusiness的实例,在Action中使用 IUsersBusiness对象来验证用户信息:(IUsersBusiness为接口类型)
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.zlk.struts.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import com.zlk.business.IUsersBusiness;
import com.zlk.struts.form.LoginForm;
/**
* MyEclipse Struts
* Creation date: 03-05-2010
*
* XDoclet definition:
* @struts.action path="/login" name="loginForm" parameter="methods" scope="request" validate="true"
*/
public class LoginAction extends DispatchAction {
/*
* Generated Methods
*/
private IUsersBusiness usersBusiness;
public void setUsersBusiness(IUsersBusiness usersBusiness) {
this.usersBusiness = usersBusiness;
}
/**
* 登陆的方法
*/
public ActionForward login(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
LoginForm loginForm = (LoginForm) form;// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = null;
try {
out = response.getWriter();
if(usersBusiness.getUser(loginForm)!=null){
out.print(""+loginForm.getUsername()+"恭喜你登陆成功!");
}else{
out.println("对不起,登陆失败");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 注册的方法
*/
public ActionForward register(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
LoginForm loginForm = (LoginForm) form;// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = null;
try {
out = response.getWriter();
if(!usersBusiness.isExitUserName(loginForm)){
if(usersBusiness.addUser(loginForm)){
out.print(""+loginForm.getUsername()+"恭喜你注册成功!");
out.print("
");
out.print("用户名:"+loginForm.getUsername());
out.print("
");
out.print("密 码:"+loginForm.getPassword());
out.print("
");
out.print("<<<返回");
out.print(" ");
out.print("登陆>>>");
}else{
out.print("对不起注册失败!");
out.print("
");
out.print("<<<返回");
}
}else{
out.print("用户"+loginForm.getUsername()+"名已存在!");
out.print("
");
out.print("<<<返回");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}