Struts2 類型轉換

實現的目標,將頁面中的字符轉爲對象,如Larry;123456 轉爲 User對象,username爲Larry,password爲123456。html

如何實現:java

Struts的類型轉換,對於8個原生數據類型以及Date,String等常見類型,
Struts2可使用內建的類型轉換器實現自動轉換;但對於自定義的對象
來講,就須要咱們本身指定類型轉換的方式了。apache

 

 1、原始的類型轉換方式 (局部類型轉換)app

工程用到的文件以下圖所示框架

 

 

一、建立測試頁面test.jspjsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>使用分號隔開用戶名和密碼</h1>
	<form action="userAction">
	 user info: <input type="text" name="user"> <br>
	 
	 <input type="submit" value="submit">
	</form>
</body>
</html>

  

二、建立userActionide

public class UserAction extends ActionSupport {

	
	private User user;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	

	@Override
	public String execute() throws Exception {
		System.out.println("username:" + user.getUsername());
		System.out.println("password:" + user.getPassword());
		return SUCCESS;
		
	}
}

  輸出用戶名和密碼測試

 

三、在struts.xml中添加配置ui

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
	"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
   <!-- 是否開啓動態方法調用 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<package name="default" namespace="/" extends="struts-default">
		 <action name="login" class="com.example.struts2.LoginAction" method="login">
			<result name="success">/success.jsp</result>
			<result name="error">/error.jsp</result>
			<result name="result">/result.jsp</result>
		</action> 
		<action name="helloworld" class="com.example.struts2.HelloWorldAction">
			<result name="success">/success.jsp</result>
			<result name="result">/result.jsp</result>
		</action> 
		<action name="userAction" class="com.example.struts2.UserAction">
			<result name="success">/output.jsp</result>
		</action>
	</package>
</struts>  

output.jsp文件以下:this

<%@ page language="java" contentType="text/html;charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:property value="user" />

</body>

</html>

  

  

 

四、建立轉換器

public class UserConverter extends DefaultTypeConverter {
	
	

	@Override
	public Object convertValue(Map<String, Object> context, Object value, Class toType) {
		
		if(User.class == toType){ //從頁面向後臺對象轉換
			String[] str = (String[])value;
			String firstValue = str[0];
			StringTokenizer st = new StringTokenizer(firstValue,";");
			String username = st.nextToken();
			String password = st.nextToken();
			
			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			
			return user;
			
			
		}
		
		return null;
		
	}
	
}

  而且增長配置文件UserAction-conversion.properties

內容爲:user=com.example.converter.UserConverter

位於UserAction中的user變量使用com.example.converter.UserConverter轉換器

 

五、測試

打開test.jsp

 

 而後點擊提交

控制檯輸出以下

 提交後頁面結果

 

 

2、Struts自帶的類型轉換 (局部類型轉換)

可使用Struts2框架自帶的類型轉換器StrutsTypeConverter簡化類型轉換代碼的編,
StrutsTypeConverter繼承於DefaultTypeConverter父類,而且提供了兩個抽象方法
convertFromString與convertToString,分別表示從頁面的字符串轉換爲後臺對象以及
從後臺對象轉換爲頁面的字符串,咱們只需實現這兩個抽象方法便可實現類型轉換。

一、單個類型轉換

建立類型轉換器

public class UserConverter2 extends StrutsTypeConverter {


	@Override
	public Object convertFromString(Map arg0, String[] arg1, Class arg2) {
		User user = new User();
		String value = arg1[0];
	
		StringTokenizer st = new StringTokenizer(value,";");
		user.setUsername(st.nextToken());
		user.setPassword(st.nextToken());
		return user;
	}


	@Override
	public String convertToString(Map arg0, Object arg1) {
		
		User user = (User)arg1;
		
		String username = user.getUsername();
		String password = user.getPassword();
		
		String userInfo = "username :" + username + ",password :" + password;
		
		
		return userInfo;
	}
	
	

	
	
}

  修改配置文件

 

 輸出結果和上面是一致的。

 

二、批量類型轉換(局部類型轉換)

 1)增長input.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>使用分號隔開用戶名和密碼</h1>
	<form action="userAction2">
	 user info 1: <input type="text" name="user"> <br>
	 user info 2: <input type="text" name="user"> <br>
	 user info 3: <input type="text" name="user"> <br>
	 user info 4: <input type="text" name="user"> <br>
	 
	 <input type="submit" value="submit">
	</form>
</body>
</html>

  

2)UserAction2 

public class UserAction2 extends ActionSupport {

	
	private List<User> user;


	public List<User> getUser() {
		return user;
	}


	public void setUser(List<User> user) {
		this.user = user;
	}



	@Override
	public String execute() throws Exception {
		for(User u: user){
			System.out.println("username:" + u.getUsername());
			System.out.println("password:" + u.getPassword());
		}
		
		return SUCCESS;
		
	}
}

  

3)struts.xml增長配置

	<action name="userAction2" class="com.example.struts2.UserAction2">
			<result name="success">/output.jsp</result>
		</action>

  

四、增長轉換器

public class UserConverter3 extends StrutsTypeConverter {


	@Override
	public Object convertFromString(Map arg0, String[] arg1, Class arg2) {
		List<User> list = new ArrayList<>();
		
		for(String value : arg1){
			User user = new User();
			StringTokenizer st = new StringTokenizer(value,";");
			user.setUsername(st.nextToken());
			user.setPassword(st.nextToken());
			list.add(user);
		}
		
		return list;
	}


	@Override
	public String convertToString(Map arg0, Object arg1) {
		
		List<User> list = (List<User>)arg1;
		StringBuffer buffer = new StringBuffer();
		for(User user : list){
			String username = user.getUsername();
			String password = user.getPassword();
			buffer.append("username:").append(username).append(",password:" ).append(password).append(" ");
			
		}
		
		
		
		
		return buffer.toString();
	}
	
	

	
	
}

  增長屬性文件

 

 

5)測試結果

 

 點擊提交後返回

 

 

3、全局類型轉換

在src目錄下建立xwork-conversion.properties,該文件的內容是待轉換的類=轉換器的名字,即

com.example.bean.User=com.exmaple.converter.UserConverter2

 

 一、建立全局配置屬性文件

 

 

二、修改input.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>使用分號隔開用戶名和密碼</h1>
	<form action="userAction">
	 user info 1: <input type="text" name="user"> <br>
	 <input type="submit" value="submit">
	</form>
</body>
</html>

  

 

 

三、提交後顯示

相關文章
相關標籤/搜索