作者:王斌 2005-04-06
通過第一個例子,我們對Spring Framework有了一點感性上的認識,現在我們通過一個具體的login例子,完整的闡述Spring Framework的實際應用!本文中的IDE為Eclipse!
1.我們使用的Web服務器是tomcat,所以在D:\tomcat\webapps\webaPPS下新建一個目錄spring,並在下面新建兩個文件,用於Eclipse導入本工程.
.classpath
.project
2.在spring下新建一個目錄WEB-INF,在下面新建文件web.xml,Config.XML以便tomcat初始化spring
web.XML
Config.XML
3.在web-inf下新建三個目錄src,classes,lib,如圖
4.在Eclipse中導入spring
ok,spring導入完成!!!
5.在spring目錄下建立三個JSP文件
index.JSP
<%@ page contentType="text/Html; charset=gb2312" %><%@ page language="Java" %>
main.JSP
<%@ page contentType="text/Html; charset=gb2312" %>
Login Success!!!
loginfail.JSP
<%@ page contentType="text/Html; charset=gb2312" %>
Login failed!!!
6.在WEB-INF rc下新建包action,在action包下新建二個Java文件,注意,要在項目中導入e: pring\dist下的所有jar包,否則Eclipse提示找不到類文件!
LoginInfo.Java
package action;
public class LoginInfo { private String username; private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = passWord; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
LoginAction.Java
package action;import Java.util.*;import org.springframework.validation.*;import org.springframework.web.servlet.*;import org.springframework.web.servlet.mvc.*;
public class LoginAction extends SimpleFormController { private String fail_vIEw;
private String success_vIEw;
protected ModelAndView onSubmit( Object cmd, BindException ex) throws Exception { LoginInfo loginInfo = (LoginInfo) cmd; if (login(loginInfo) == 0) { HashMap result_map = new HashMap(); result_map.put("logininfo", loginInfo); return new ModelAndView(this.getSuccess_view(), result_map); } else { return new ModelAndView(this.getFail_vIEw()); } }
private int login(LoginInfo loginInfo) { if ("qQQ".equalsIgnoreCase(loginInfo.getUsername()) && "1".equals(loginInfo.getPassWord())) {//假設用戶名是"qQQ",密碼"1" return 0; } return 1; }
public String getFail_view() { return fail_vIEw; }
public String getSuccess_view() { return success_vIEw; }
public void setFail_view(String string) { fail_vIEw = string; }
public void setSuccess_view(String string) { success_vIEw = string; }}
7.在WEB-INF\lib下拷入e: pring\dist下的所有jar包,注意一點,還要從sun的網站上下載JStl.jar,要不然會出現
"java.lang.NoClassDefFoundError: Javax/servlet/JSP/JStl/fmt/LocalizationContext"的提示!全圖如下(包括第一個例子):
ok!現在可以啟動tomcat,IE上輸入http://localhost/spring/index.JSP
驗證失敗!
驗證成功!