Struts2_用DomainModel接收參數,struts2domainmodel
用領域模型接收參數
User類
1 package com.bjsxt.struts2.user.model; 2 3 public class User { 4 5 private String name; 6 7 private int age; 8 9 public String getName() {10 return name;11 }12 13 public void setName(String name) {14 this.name = name;15 }16 17 public int getAge() {18 return age;19 }20 21 public void setAge(int age) {22 this.age = age;23 }24 25 }View Code
UserAction
1 package com.bjsxt.struts2.user.action; 2 3 import com.bjsxt.struts2.user.model.User; 4 import com.opensymphony.xwork2.ActionSupport; 5 6 public class UserAction extends ActionSupport{ 7 8 private static final long serialVersionUID = -2514433281517403937L; 9 10 User user;11 //private UserDTO userDTO;12 13 public String add(){14 System.out.println("name = " + user.getName());15 System.out.println("age = " + user.getAge());16 return SUCCESS;17 }18 19 public User getUser() {20 return user;21 }22 23 public void setUser(User user) {24 this.user = user;25 }26 27 }View Code
struts.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"><struts> <constant name="struts.configuration.xml.reload" value="true"/> <constant name="struts.enable.DynamicMethodInvocation" value="true"/> <package name="user" namespace="/user" extends="struts-default"> <action name="user" class="com.bjsxt.struts2.user.action.UserAction"> <result>/user_add_success.jsp</result> </action> </package> </struts>
index.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <% 4 String path = request.getContextPath(); 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 6 %> 7 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 8 <html> 9 <head>10 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">11 <title>首頁</title>12 <base href="<%=basePath%>"/>13 </head>14 <body>15 <h1>Hello World~~~</h1>16 <a href="user/user!add?user.name=xiaoer&user.age=33">添加使用者</a>17 </body>18 </html>
View Code
結果:
有時候,頁面輸入的值並非就是單純的與資料庫對應的model,也許會加上其他的東西:驗證碼,確認密碼,識別欄位...
這時候可以在 model 前又加上一層 dto(Data Transfer Object),或者叫VO。
我們可以先用dto接收,接收完在方法中處理了相關業務之後,再把dto中與model相關的值複製到model中,dto相當一個中間對象,兩者之間的關係如。
連結: http://pan.baidu.com/s/1dFf4HXJ 密碼: a73w