struts2 的3种驱动 第二种方式 对象驱动
第二种是:将对象写在action中:
在action中 我只写了一个user 对象 :
action 中的内容:
package com.luhua.test;
import com.luhua.pojo.User;
public class UserAction {
//用户
private User user ;
public void setUser(User user) {
this.user = user;
}
public String user(){
System.out.println(user.getUsername());
return "success" ;
}
public String execute(){
return "success" ;
}
}
user类中:只有一个username的属性,并提供了get和set方法
package com.luhua.pojo;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
public User(){}
private String username ;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
在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.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="welcome" method="execute">
<result name="success">index.jsp</result>
</action>
<action name="user" method="user">
<result name="success">success.jsp</result>
</action>
</package>
</struts>
jsp页面有两张,index.jsp 和 success.jsp 从index.jsp中输入用户名; 在action中打印出来
页面的输入的name必须是对象名.属性名
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
</head>
<body>
<form action="user" method="post">
username:<input type="text" name="user.username"/>
<input type="submit"/>
</form>
</body>
</html>
success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
</head>
<body>
user
</body>
</html>