從一個簡單的小實例分析JSP+Servelt與JSP+Struts2框架的區別


最近在學struts2,struts2相比以前的JSP+Servlet,在處理流程上的更簡單,我們就一個小實例來具體分析一下。

實例內容如下:

實現一個簡單的注冊頁面包括:用戶名、密碼、重復密碼、年齡、出生日期、畢業日期

要求如下:
用戶名的長度在4-6之間
密碼的長度在4-6之間
重復密碼與密碼相等
年齡在10-50之間
出生日期在畢業日期之前

輸入錯誤返回原頁面,並在原頁面的文本框后面顯示具體的錯誤信息。正確輸入則跳入下個頁面將信息顯示出來。

1、JSP+Servlet

1)我們編寫注冊頁面register.jsp

注冊頁面,不使用struts標簽庫的話,基本上大同小異,唯一的區別在form中action選項上,這里面的servlet自然要跳到RegisterServlet上進行相應的信息處理。我們先各自處理,然后再來比較吧。

 

[html]  view plain  copy
 
  1. <body>  
  2. <h1>用戶注冊</h1>  
  3. <form action="RegisterServlet" method="post">  
  4. username:<input type="text" name="username"><br>  
  5. password:<input type="password" name="password"><br>  
  6. repassword:<input type="password" name="repassword"><br>  
  7. age:<input type="text" name="age"><br>  
  8. birthday:<input type="text" name="birthday"><br>  
  9. graduate:<input type="text" name="graduate"><br>  
  10. <input type="submit" value="submit">  
  11. </form>  
  12. </body>  

2)因為這些屬性都是屬於注冊用戶的,我們再構建一個User類

 

 

[java]  view plain  copy
 
  1. private String username;  
  2.     private String password;  
  3.     private String repassword;  
  4.     private int age;  
  5.     private Date birthday;  
  6.     private Date graduate;  
  7.     public String getUsername() {  
  8.         return username;  
  9.     }  
  10.     public void setUsername(String username) {  
  11.         this.username = username;  
  12.     }  
  13.     public String getPassword() {  
  14.         return password;  
  15.     }  
  16.     public void setPassword(String password) {  
  17.         this.password = password;  
  18.     }  
  19.     public String getRepassword() {  
  20.         return repassword;  
  21.     }  
  22.     public void setRepassword(String repassword) {  
  23.         this.repassword = repassword;  
  24.     }  
  25.     public int getAge() {  
  26.         return age;  
  27.     }  
  28.     public void setAge(int age) {  
  29.         this.age = age;  
  30.     }  
  31.     public Date getBirthday() {  
  32.         return birthday;  
  33.     }  
  34.     public void setBirthday(Date birthday) {  
  35.         this.birthday = birthday;  
  36.     }  
  37.     public Date getGraduate() {  
  38.         return graduate;  
  39.     }  
  40.     public void setGraduate(Date graduate) {  
  41.         this.graduate = graduate;  
  42.     }  

 

3)輸入效驗可以分為客戶端效驗和服務器端的效驗,客戶端的效驗是將驗證代碼用javascript寫到頁面中,這里面我們統一用服務器端效驗。編寫RegisterServlet

 

[java]  view plain  copy
 
  1. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  2.         // TODO Auto-generated method stub  
  3.         //從頁面傳過來的數據都是字符形式的,我們要進行相應的轉換  
  4.         String username=request.getParameter("username");  
  5.         String password=request.getParameter("password");  
  6.         String repassword=request.getParameter("repassword");  
  7.         int age=Integer.valueOf(request.getParameter("age"));  
  8.         String birthday=request.getParameter("birthday");  
  9.         String graduate=request.getParameter("graduate");  
  10.         Date graduate1=null;  
  11.         Date birthday1=null;  
  12.         Map<String, String> errors = new HashMap<String, String>();  
  13.             if (username == null)  
  14.             {  
  15.                 errors.put("username", "用戶名不能為空");  
  16.             } else  
  17.             {  
  18.                 if (username.length()<4||username.length()>6)  
  19.                 {  
  20.                     errors.put("username", "用戶名必須是4到6位");  
  21.                 }  
  22.             }  
  23.             if (password == null)  
  24.             {  
  25.                 errors.put("password", "密碼不能為空");  
  26.             } else  
  27.             {  
  28.                 if (password.length()<4||password.length()>6)  
  29.                 {  
  30.                       
  31.                     errors.put("password", "密碼必須是4-6位數字");  
  32.                 }  
  33.             }  
  34.             if (repassword ==null)  
  35.             {  
  36.                 errors.put("repassword", "確認密碼不能為空");  
  37.             } else  
  38.             {  
  39.                 if (!(password.equals(repassword)))  
  40.                 {  
  41.                     errors.put("repassword", "確認密碼必須與密碼輸入一致");  
  42.                 }  
  43.             }  
  44.             if(age>50||age<10)  
  45.             {  
  46.                 errors.put("age", "年齡無效");  
  47.             }  
  48.             if(birthday!=null)  
  49.             {  
  50.                 DateFormat df=new SimpleDateFormat("yyyy-MM-dd");  
  51.                   
  52.                 try{  
  53.                     birthday1=df.parse(birthday);  
  54.                 }catch(Exception e)  
  55.                 {  
  56.                     errors.put("birthday", "日期格式不正確");  
  57.                 }  
  58.             }else{  
  59.                 errors.put("birthday", "生日不能為空");  
  60.             }  
  61.             if(graduate!=null)  
  62.             {  
  63.                 DateFormat df=new SimpleDateFormat("yyyy-MM-dd");  
  64.                   
  65.                 try{  
  66.                     graduate1=df.parse(graduate);  
  67.                 }catch(Exception e)  
  68.                 {  
  69.                     errors.put("graduate", "日期格式不正確");  
  70.                 }  
  71.             }else{  
  72.                 errors.put("graduate", "畢業日期不能為空");  
  73.             }  
  74.             if(null!=graduate1&&null!=birthday1)  
  75.             {  
  76.               Calendar c1=Calendar.getInstance();  
  77.               c1.setTime(birthday1);  
  78.               Calendar c2=Calendar.getInstance();  
  79.               c2.setTime(graduate1);  
  80.               if(!c1.before(c2))  
  81.               {  
  82.                   errors.put("graduate", "畢業日期出生日期不匹配");  
  83.               }  
  84.             }  
  85.         <span style="color:#FF0000;">if(errors.size()==0)  
  86.         {  
  87.             User user=new User();  
  88.             user.setUsername(username);  
  89.             user.setAge(age);  
  90.             user.setPassword(password);  
  91.             user.setRepassword(repassword);  
  92.             user.setBirthday(birthday1);  
  93.             user.setGraduate(graduate1);  
  94.             request.setAttribute("user", user);  
  95.             request.getRequestDispatcher("result.jsp").forward(request, response);  
  96.         }else  
  97.         {  
  98.             request.setAttribute("errors", errors);  
  99.             request.setAttribute("username", username);  
  100.             request.setAttribute("password",password);  
  101.             request.setAttribute("birthday", birthday);  
  102.             request.setAttribute("graduate",graduate);  
  103.             request.setAttribute("age",age);  
  104.             request.getRequestDispatcher("register.jsp").forward(request, response);      
  105.               
  106.         }</span>  
  107.           
  108.     }  


4)然后我們編寫一下result.jsp結果頁面和修改一下register.jsp頁面(出現錯誤后跳轉,顯示相應的錯誤信息)

 

result.jsp頁面

 

[html]  view plain  copy
 
  1. <body>  
  2. username:${user.username}<br>  
  3. password:${user.password}<br>  
  4. age:${user.age}<br>  
  5. birthday:${user.birthday}<br>  
  6. graduate:${user.graduate}<br>  
  7. </body>  

register.jsp修改后內容

 

 

[html]  view plain  copy
 
  1. <body>  
  2. <h1>用戶注冊</h1>  
  3. <form action="RegisterServlet" method="post">  
  4. username:<input type="text" name="username" value="${username}">${errors.username}<br>  
  5. password:<input type="password" name="password">${errors.password}<br>  
  6. repassword:<input type="password" name="repassword">${errors.repassword}<br>  
  7. age:<input type="text" name="age" value="${age}">${errors.age}<br>  
  8. birthday:<input type="text" name="birthday" value="${birthday}">${errors.birthday}<br>  
  9. graduate:<input type="text" name="graduate" value="${graduate}">${errors.graduate}<br>  
  10. <input type="submit" value="submit">  
  11. </form>  

5)最后我們查看一下web.xml文件中,zai生成RegisterServlet時是否有相關的配置

 

 

[html]  view plain  copy
 
  1. <servlet>  
  2.     <description></description>  
  3.     <display-name>ReigsterServlet</display-name>  
  4.     <servlet-name>ReigsterServlet</servlet-name>  
  5.     <servlet-class>ReigsterServlet</servlet-class>  
  6.   </servlet>  
  7.   <servlet-mapping>  
  8.     <servlet-name>ReigsterServlet</servlet-name>  
  9.     <url-pattern>/RegisterServlet</url-pattern>  
  10.   </servlet-mapping>  


Ok,到這上面描述的Jsp+Servlet的基本功能都已實現,RegisterServlet作為整個代碼的核心,寫的是很長的。其實我們可以優化一下,將判斷的內容放在formbean類中,然后在servlet中判調用。但是代碼量是不減的,只能是讓邏輯業務更清晰。

 

2、用Struts框架來實現以上功能。

1)首先struts的基本配置省略,可以參考http://blog.csdn.net/fumier/article/details/44626461

2)編寫register.jsp頁面,這里面使用了struts標簽庫,需要在開頭第二行加入( <%@ taglib prefix="s" uri="/struts-tags"%>)

 

[html]  view plain  copy
 
  1. <s:form action="register.action" theme="simple"><br>  
  2. username:<s:textfield name="username" label="username"></s:textfield><br>  
  3. password:<s:password name="password" label="password"></s:password><br>  
  4. repassword:<s:password name="repassword" lable="repassword"></s:password><br>  
  5. age:<s:textfield name="age" label="age"></s:textfield><br>  
  6. birthday:<s:textfield name="birthday" label="birthday"></s:textfield><br>  
  7. graduate:<s:textfield name="graduate" label="age"></s:textfield><br>  
  8. <s:submit value="submit"></s:submit>  
  9. </s:form>  

3)接下來我們編寫RegisterAction類

 

 

[java]  view plain  copy
 
  1. public class RegisterAction extends ActionSupport {  
  2. private String username;  
  3. private String password;  
  4. private String repassword;  
  5. private int age;  
  6. private Date birthday;  
  7. private Date graduate;  
  8.   
  9. public String getUsername() {  
  10.     return username;  
  11. }  
  12.   
  13. public void setUsername(String username) {  
  14.     this.username = username;  
  15. }  
  16.   
  17. public String getPassword() {  
  18.     return password;  
  19. }  
  20.   
  21. public void setPassword(String password) {  
  22.     this.password = password;  
  23. }  
  24.   
  25. public String getRepassword() {  
  26.     return repassword;  
  27. }  
  28.   
  29. public void setRepassword(String repassword) {  
  30.     this.repassword = repassword;  
  31. }  
  32.   
  33. public int getAge() {  
  34.     return age;  
  35. }  
  36.   
  37. public void setAge(int age) {  
  38.     this.age = age;  
  39. }  
  40.   
  41. public Date getBirthday() {  
  42.     return birthday;  
  43. }  
  44.   
  45. public void setBirthday(Date birthday) {  
  46.     this.birthday = birthday;  
  47. }  
  48.   
  49. public Date getGraduate() {  
  50.     return graduate;  
  51. }  
  52.   
  53. public void setGraduate(Date graduate) {  
  54.     this.graduate = graduate;  
  55. }  
  56.   
  57. @Override  
  58. public String execute() throws Exception {  
  59.     // TODO Auto-generated method stub  
  60.     System.out.println("execute()");  
  61.     return SUCCESS;  
  62. }  
  63. @Override  
  64.     public void validate() {  
  65.         // TODO Auto-generated method stub  
  66.     System.out.println("validate()");  
  67.     if(null==username||username.length()<4||username.length()>6)  
  68.     {  
  69.         this.addFieldError("username","用戶名無效");  
  70.     }  
  71.     if(null==password||password.length()<4||password.length()>6)  
  72.     {  
  73.         this.addFieldError("password","密碼無效");  
  74.     }else if(null==repassword||repassword.length()!=password.length())  
  75.     {  
  76.         this.addFieldError("repassword","密碼長度不一致");  
  77.     }else if(!repassword.equals(password))  
  78.     {  
  79.         this.addFieldError("repassword","密碼不一致");  
  80.     }  
  81.     if(age<10||age>50)  
  82.     {  
  83.         this.addFieldError("age","年齡無效");  
  84.     }  
  85.     if(null==birthday)  
  86.     {  
  87.         this.addFieldError("birthday","出生日期為空");  
  88.     }  
  89.     if(null==graduate)  
  90.     {  
  91.         this.addFieldError("graduate","畢業日期為空");  
  92.     }  
  93.     if(null!=graduate&&null!=birthday)  
  94.     {  
  95.       Calendar c1=Calendar.getInstance();  
  96.       c1.setTime(birthday);  
  97.       Calendar c2=Calendar.getInstance();  
  98.       c2.setTime(graduate);  
  99.       if(!c1.before(c2))  
  100.       {  
  101.           this.addFieldError("graduate","畢業日期出生日期不匹配");  
  102.       }  
  103.     }  
  104.     }  
  105. }  

4)配置struts.xml文件

 

 

[html]  view plain  copy
 
  1. <action name="register" class="cn.sict.register.RegisterAction">  
  2.     <result name="success">/result.jsp</result>//正確就跳轉到result.jsp  
  3.     <result name="input">/register.jsp</result>//錯誤就跳轉到register.jsp  
  4. </action>  

5)result.jsp與1中的相同,至此,就完成了所有的功能。

 


接下來,我們來看一下,使用struts框架,我們省略了哪些工作。

1)首先沒有set/get方法了。

2)沒有了servlet中從頁面獲得字符,然后再轉換為需要的類型,然后簡單的配置相應的result參數,就可以跳轉到相應的頁面。

3)繼承了ActionSupport類重寫validate()方法,使邏輯清晰。

Struts對上述的操作進行了包裝,提高了程序的課重用性,我們只需要修改少量的參數和配置文件,就可以達到想要的效果。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM