項目架構
me.gacl.domain → 實體類
me.gacl.dao → 數據訪問接口
me.gacl.dao.impl → DAO 實現
me.gacl.service → 業務接口
me.gacl.service.impl→ Service 實現
me.gacl.web.controller → Servlet 控制器
me.gacl.web.UI → 頁面跳轉 Servlet
me.gacl.web.formbean→ 表單驗證 Bean
me.gacl.util → 工具類
me.gacl.exception → 自定義異常
核心模塊代碼
1. 實體類
public class User implements Serializable {
private String id; // UUID
private String userName;
private String userPwd;
private String email;
private Date birthday;
// getter/setter
}
2. DAO 層(XML 文件存儲)
public class UserDaoImpl implements IUserDao {
// 使用 Dom4j + XPath 操作 DB.xml
public User find(String userName, String userPwd) {
Document doc = XmlUtils.getDocument();
Element e = (Element) doc.selectSingleNode(
"//user[@userName='"+userName+"' and @userPwd='"+userPwd+"']");
// 映射到 User 對象...
}
public void add(User user) {
// 添加節點並寫回 XML
}
}
3. Service 層(業務邏輯 + 異常)
public class UserServiceImpl implements IUserService {
private IUserDao dao = new UserDaoImpl();
public void registerUser(User user) throws UserExistException {
if (dao.find(user.getUserName()) != null)
throw new UserExistException("用戶名已存在");
dao.add(user);
}
public User loginUser(String name, String pwd) {
return dao.find(name, pwd);
}
}
4. 表單驗證 Bean(核心亮點)
public class RegisterFormBean {
private String userName, userPwd, confirmPwd, email, birthday;
private Map<String, String> errors = new HashMap<>();
public boolean validate() {
boolean ok = true;
if (empty(userName)) { ok=false; errors.put("userName","用戶名不能為空"); }
else if (!userName.matches("[a-zA-Z]{4,12}")) { ok=false; errors.put("userName","4-12位字母"); }
if (empty(userPwd)) { ok=false; errors.put("userPwd","密碼不能為空"); }
else if (!userPwd.matches("\\d{6,12}")) { ok=false; errors.put("userPwd","6-12位數字"); }
if (!userPwd.equals(confirmPwd)) { ok=false; errors.put("confirmPwd","兩次密碼不一致"); }
if (!empty(email) && !email.matches("\\w+@\\w+(\\.\\w+)+"))
{ ok=false; errors.put("email","郵箱格式錯誤"); }
// 生日驗證...
return ok;
}
// getter/setter
}
5. WebUtils 工具類(自動封裝)
public class WebUtils {
public static <T> T requestBean(HttpServletRequest req, Class<T> clazz) {
T bean = clazz.newInstance();
Enumeration<String> en = req.getParameterNames();
while (en.hasMoreElements()) {
String name = en.nextElement();
BeanUtils.setProperty(bean, name, req.getParameter(name));
}
return bean;
}
public static String makeId() { return UUID.randomUUID().toString(); }
}
6. 控制器 Servlet
// 註冊控制器
public class RegisterServlet extends HttpServlet {
protected void doGet(req, resp) {
RegisterFormBean form = WebUtils.requestBean(req, RegisterFormBean.class);
if (!form.validate()) {
req.setAttribute("formbean", form); // 回顯數據與錯誤
forward("/WEB-INF/pages/register.jsp");
return;
}
User user = new User();
BeanUtils.copyProperties(user, form);
user.setId(WebUtils.makeId());
try {
new UserServiceImpl().registerUser(user);
showMsg("註冊成功", "/servlet/LoginUIServlet");
} catch (UserExistException e) {
form.getErrors().put("userName", e.getMessage());
req.setAttribute("formbean", form);
forward("/WEB-INF/pages/register.jsp");
}
}
}
// 登錄控制器
public class LoginServlet extends HttpServlet {
protected void doGet(req, resp) {
User user = new UserServiceImpl().loginUser(
req.getParameter("username"), req.getParameter("password"));
if (user == null) { showMsg("用戶名或密碼錯誤", "/servlet/LoginUIServlet"); return; }
req.getSession().setAttribute("user", user); // 存入 Session
showMsg("登錄成功", "/index.jsp");
}
}
// 註銷控制器
public class LogoutServlet extends HttpServlet {
protected void doGet(req, resp) {
req.getSession().removeAttribute("user");
showMsg("註銷成功", "/servlet/LoginUIServlet");
}
}
7. JSP 頁面(EL 表達式回顯)
<input type="text" name="userName" value="${formbean.userName}">
${formbean.errors.userName}
<input type="password" name="userPwd" value="${formbean.userPwd}">
${formbean.errors.userPwd}
MVC 分層開發總結
- Domain:純屬性 POJO,對應數據庫表
- DAO:接口定義 CRUD,實現類操作數據源
- Service:事務控制、業務規則、異常轉換
- Controller:接收請求、參數封裝、調用 Service、頁面導航
- FormBean:參數接收+驗證+錯誤收集,支援回顯
- Util:通用工具,減少樣板代碼