User.java
package com.org; public class User { private String username; private String password; 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; } }
UserAction.java
package com.org; import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport { private User user; public void setUser(User user) { this.user = user; } public User getUser() { return user; } @Override public String execute()throws Exception{ System.out.println("username: "+getUser().getUsername()); System.out.println("password: "+getUser().getPassword()); return SUCCESS; } }
编写类型转换器 UserConvert.java
package com.org; import java.util.Map; import java.util.StringTokenizer; import ognl.DefaultTypeConverter; public class UserConvert extends DefaultTypeConverter { @Override public Object convertValue(Map context, Object value, Class toType) { // TODO Auto-generated method stub //从前台转后台 if(User.class == toType){ String str[] = (String[])value; String v = str[0]; //取出字符串 StringTokenizer st = new StringTokenizer(v,";"); String username = st.nextToken(); String password = st.nextToken(); User user = new User(); user.setUsername(username); user.setPassword(password); return user; }else if(String.class == toType){ //从后台转到前台 User user = (User)value; String username = user.getUsername(); String password = user.getPassword(); return "Username: "+username+",Password: "+password; } return null; } }
UserAction-conversion.properties配置文件
user=com.org.UserConvert
info.jsp
<body> 请输入用户名和密码中间以分号隔开:<br> <form action="userAction" method="post"> <!-- name属性值一定要对应Action中的属性 --> <input type="text" name="user"><br> <input type="submit" value="提交"/> </form> </body>
success.jsp
用struts2标签取出数据
<body> SUCCESS!!!<s:property value="user"/> </body>
struts.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="false" /> <package name="default" extends="struts-default"> <action name="userAction" class="com.org.UserAction"> <result name="success">/success.jsp</result> </action> </package> </struts>
目录结构
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/14384.html