login.jsp
<body>
<script language="javascript">
function validate(f){
if(!(/^\w{5,15}$/.test(f.userid.value))){
alert("用户ID必须是5~15位!") ;
f.userid.focus() ;
return false ;
}
if(!(/^\w{5,15}$/.test(f.userpass.value))){
alert("密码必须是5~15位!") ;
f.userpass.focus() ;
return false ;
}
}
</script>
<%
request.setCharacterEncoding("GBK") ;
%>
<%
List<String> info = (List<String>) request.getAttribute("info") ;
if(info != null){ // 有信息返回
Iterator<String> iter = info.iterator() ;
while(iter.hasNext()){
%>
<h4><%=iter.next()%></h4>
<%
}
}
%>
<form action="LoginServlet" method="post" onSubmit="return validate(this)">
用户ID:<input type="text" name="userid"><br>
密 码:<input type="password" name="userpass"><br>
<input type="submit" value="登陆">
<input type="reset" value="重置">
</form>
</body>
web.xml
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>
org.lxh.mvcdemo.servlet.LoginServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
servlet
package org.lxh.mvcdemo.servlet;
import java.io.* ;
import java.util.* ;
import javax.servlet.* ;
import javax.servlet.http.* ;
import org.lxh.mvcdemo.factory.* ;
import org.lxh.mvcdemo.vo.* ;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
System.out.println("111111");
String path = "login.jsp" ;
String userid = req.getParameter("userid") ;
String userpass = req.getParameter("userpass") ;
List<String> info = new ArrayList<String>() ; // 收集错误
if(userid==null || "".equals(userid)){
info.add("用户id不能为空!") ;
}
if(userpass==null || "".equals(userpass)){
info.add("密码不能为空!") ;
}
if(info.size()==0){ // 里面没有记录任何的错误
User user = new User() ;
user.setUserid(userid) ;
user.setPassword(userpass) ;
System.out.println("222222");
try{
if(DAOFactory.getIUserDAOInstance().findLogin(user)){
info.add("用户登陆成功,欢迎" + user.getName() + "光临!") ;
} else {
info.add("用户登陆失败,错误的用户名和密码!") ;
}
}catch(Exception e){
e.printStackTrace() ;
}
}
req.setAttribute("info",info) ;
req.getRequestDispatcher(path).forward(req,resp) ;
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
this.doGet(req,resp) ;
}
}
工厂类
package org.lxh.mvcdemo.factory;
import org.lxh.mvcdemo.dao.* ;
import org.lxh.mvcdemo.dao.proxy.* ;
public class DAOFactory {
public static IUserDAO getIUserDAOInstance(){
return new UserDAOProxy() ;
}
}
代理类
package org.lxh.mvcdemo.dao.proxy;
import org.lxh.mvcdemo.vo.User ;
import org.lxh.mvcdemo.dbc.* ;
import org.lxh.mvcdemo.dao.* ;
import org.lxh.mvcdemo.dao.impl.* ;
import java.sql.* ;
public class UserDAOProxy implements IUserDAO {
private DatabaseConnection dbc = null ;