最近在學struts2,struts2相比以前的JSP+Servlet,在處理流程上的更簡單,我們就一個小實例來具體分析一下。
實例內容如下:
實現一個簡單的注冊頁面包括:用戶名、密碼、重復密碼、年齡、出生日期、畢業日期
要求如下:
用戶名的長度在4-6之間
密碼的長度在4-6之間
重復密碼與密碼相等
年齡在10-50之間
出生日期在畢業日期之前
輸入錯誤返回原頁面,並在原頁面的文本框后面顯示具體的錯誤信息。正確輸入則跳入下個頁面將信息顯示出來。
1、JSP+Servlet
1)我們編寫注冊頁面register.jsp
注冊頁面,不使用struts標簽庫的話,基本上大同小異,唯一的區別在form中action選項上,這里面的servlet自然要跳到RegisterServlet上進行相應的信息處理。我們先各自處理,然后再來比較吧。
- <body>
- <h1>用戶注冊</h1>
- <form action="RegisterServlet" method="post">
- username:<input type="text" name="username"><br>
- password:<input type="password" name="password"><br>
- repassword:<input type="password" name="repassword"><br>
- age:<input type="text" name="age"><br>
- birthday:<input type="text" name="birthday"><br>
- graduate:<input type="text" name="graduate"><br>
- <input type="submit" value="submit">
- </form>
- </body>
2)因為這些屬性都是屬於注冊用戶的,我們再構建一個User類
- private String username;
- private String password;
- private String repassword;
- private int age;
- private Date birthday;
- private Date graduate;
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getRepassword() {
- return repassword;
- }
- public void setRepassword(String repassword) {
- this.repassword = repassword;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public Date getBirthday() {
- return birthday;
- }
- public void setBirthday(Date birthday) {
- this.birthday = birthday;
- }
- public Date getGraduate() {
- return graduate;
- }
- public void setGraduate(Date graduate) {
- this.graduate = graduate;
- }
3)輸入效驗可以分為客戶端效驗和服務器端的效驗,客戶端的效驗是將驗證代碼用javascript寫到頁面中,這里面我們統一用服務器端效驗。編寫RegisterServlet
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
- //從頁面傳過來的數據都是字符形式的,我們要進行相應的轉換
- String username=request.getParameter("username");
- String password=request.getParameter("password");
- String repassword=request.getParameter("repassword");
- int age=Integer.valueOf(request.getParameter("age"));
- String birthday=request.getParameter("birthday");
- String graduate=request.getParameter("graduate");
- Date graduate1=null;
- Date birthday1=null;
- Map<String, String> errors = new HashMap<String, String>();
- if (username == null)
- {
- errors.put("username", "用戶名不能為空");
- } else
- {
- if (username.length()<4||username.length()>6)
- {
- errors.put("username", "用戶名必須是4到6位");
- }
- }
- if (password == null)
- {
- errors.put("password", "密碼不能為空");
- } else
- {
- if (password.length()<4||password.length()>6)
- {
- errors.put("password", "密碼必須是4-6位數字");
- }
- }
- if (repassword ==null)
- {
- errors.put("repassword", "確認密碼不能為空");
- } else
- {
- if (!(password.equals(repassword)))
- {
- errors.put("repassword", "確認密碼必須與密碼輸入一致");
- }
- }
- if(age>50||age<10)
- {
- errors.put("age", "年齡無效");
- }
- if(birthday!=null)
- {
- DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
- try{
- birthday1=df.parse(birthday);
- }catch(Exception e)
- {
- errors.put("birthday", "日期格式不正確");
- }
- }else{
- errors.put("birthday", "生日不能為空");
- }
- if(graduate!=null)
- {
- DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
- try{
- graduate1=df.parse(graduate);
- }catch(Exception e)
- {
- errors.put("graduate", "日期格式不正確");
- }
- }else{
- errors.put("graduate", "畢業日期不能為空");
- }
- if(null!=graduate1&&null!=birthday1)
- {
- Calendar c1=Calendar.getInstance();
- c1.setTime(birthday1);
- Calendar c2=Calendar.getInstance();
- c2.setTime(graduate1);
- if(!c1.before(c2))
- {
- errors.put("graduate", "畢業日期出生日期不匹配");
- }
- }
- <span style="color:#FF0000;">if(errors.size()==0)
- {
- User user=new User();
- user.setUsername(username);
- user.setAge(age);
- user.setPassword(password);
- user.setRepassword(repassword);
- user.setBirthday(birthday1);
- user.setGraduate(graduate1);
- request.setAttribute("user", user);
- request.getRequestDispatcher("result.jsp").forward(request, response);
- }else
- {
- request.setAttribute("errors", errors);
- request.setAttribute("username", username);
- request.setAttribute("password",password);
- request.setAttribute("birthday", birthday);
- request.setAttribute("graduate",graduate);
- request.setAttribute("age",age);
- request.getRequestDispatcher("register.jsp").forward(request, response);
- }</span>
- }
4)然后我們編寫一下result.jsp結果頁面和修改一下register.jsp頁面(出現錯誤后跳轉,顯示相應的錯誤信息)
result.jsp頁面
- <body>
- username:${user.username}<br>
- password:${user.password}<br>
- age:${user.age}<br>
- birthday:${user.birthday}<br>
- graduate:${user.graduate}<br>
- </body>
register.jsp修改后內容
- <body>
- <h1>用戶注冊</h1>
- <form action="RegisterServlet" method="post">
- username:<input type="text" name="username" value="${username}">${errors.username}<br>
- password:<input type="password" name="password">${errors.password}<br>
- repassword:<input type="password" name="repassword">${errors.repassword}<br>
- age:<input type="text" name="age" value="${age}">${errors.age}<br>
- birthday:<input type="text" name="birthday" value="${birthday}">${errors.birthday}<br>
- graduate:<input type="text" name="graduate" value="${graduate}">${errors.graduate}<br>
- <input type="submit" value="submit">
- </form>
5)最后我們查看一下web.xml文件中,zai生成RegisterServlet時是否有相關的配置
- <servlet>
- <description></description>
- <display-name>ReigsterServlet</display-name>
- <servlet-name>ReigsterServlet</servlet-name>
- <servlet-class>ReigsterServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>ReigsterServlet</servlet-name>
- <url-pattern>/RegisterServlet</url-pattern>
- </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"%>)
- <s:form action="register.action" theme="simple"><br>
- username:<s:textfield name="username" label="username"></s:textfield><br>
- password:<s:password name="password" label="password"></s:password><br>
- repassword:<s:password name="repassword" lable="repassword"></s:password><br>
- age:<s:textfield name="age" label="age"></s:textfield><br>
- birthday:<s:textfield name="birthday" label="birthday"></s:textfield><br>
- graduate:<s:textfield name="graduate" label="age"></s:textfield><br>
- <s:submit value="submit"></s:submit>
- </s:form>
3)接下來我們編寫RegisterAction類
- public class RegisterAction extends ActionSupport {
- private String username;
- private String password;
- private String repassword;
- private int age;
- private Date birthday;
- private Date graduate;
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getRepassword() {
- return repassword;
- }
- public void setRepassword(String repassword) {
- this.repassword = repassword;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public Date getBirthday() {
- return birthday;
- }
- public void setBirthday(Date birthday) {
- this.birthday = birthday;
- }
- public Date getGraduate() {
- return graduate;
- }
- public void setGraduate(Date graduate) {
- this.graduate = graduate;
- }
- @Override
- public String execute() throws Exception {
- // TODO Auto-generated method stub
- System.out.println("execute()");
- return SUCCESS;
- }
- @Override
- public void validate() {
- // TODO Auto-generated method stub
- System.out.println("validate()");
- if(null==username||username.length()<4||username.length()>6)
- {
- this.addFieldError("username","用戶名無效");
- }
- if(null==password||password.length()<4||password.length()>6)
- {
- this.addFieldError("password","密碼無效");
- }else if(null==repassword||repassword.length()!=password.length())
- {
- this.addFieldError("repassword","密碼長度不一致");
- }else if(!repassword.equals(password))
- {
- this.addFieldError("repassword","密碼不一致");
- }
- if(age<10||age>50)
- {
- this.addFieldError("age","年齡無效");
- }
- if(null==birthday)
- {
- this.addFieldError("birthday","出生日期為空");
- }
- if(null==graduate)
- {
- this.addFieldError("graduate","畢業日期為空");
- }
- if(null!=graduate&&null!=birthday)
- {
- Calendar c1=Calendar.getInstance();
- c1.setTime(birthday);
- Calendar c2=Calendar.getInstance();
- c2.setTime(graduate);
- if(!c1.before(c2))
- {
- this.addFieldError("graduate","畢業日期出生日期不匹配");
- }
- }
- }
- }
4)配置struts.xml文件
- <action name="register" class="cn.sict.register.RegisterAction">
- <result name="success">/result.jsp</result>//正確就跳轉到result.jsp
- <result name="input">/register.jsp</result>//錯誤就跳轉到register.jsp
- </action>
5)result.jsp與1中的相同,至此,就完成了所有的功能。
接下來,我們來看一下,使用struts框架,我們省略了哪些工作。
1)首先沒有set/get方法了。
2)沒有了servlet中從頁面獲得字符,然后再轉換為需要的類型,然后簡單的配置相應的result參數,就可以跳轉到相應的頁面。
3)繼承了ActionSupport類重寫validate()方法,使邏輯清晰。
Struts對上述的操作進行了包裝,提高了程序的課重用性,我們只需要修改少量的參數和配置文件,就可以達到想要的效果。