struts2怎样从jsp页面传值到action中
2016-12-24 · 知道合伙人数码行家
知道合伙人数码行家
向TA提问 私信TA
jsp页面跟通常的html传值一样 通常有两种方式
1.form表单传值
2.url方式传值
通常后台接受前端传值 都是用的 request.getParameter("username")
但是在struts框架下 可以用set方法让action自动接收 也更方便
所以 action接收值也有两种方式
1.request.getParameter("username")
2.set
下面记录多种组合方式,大家可以根据相应的情况选择使用:
方式一 jsp中form传值username,password, action中set方法接收
[java] view plain copy
<%@taglib prefix="s" uri="/struts-tags" %>
[java] view plain copy
<form action="getIp/login" method="post" name="form1">
用户名:
<s:textfield name="username" />
<br />
密 码:
<s:password name="password" />
<br />
<s:submit value="提交" />
</form>
login.jsp
[java] view plain copy
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>login page</title>
</head>
<body>
<form action="getIp/login" method="post" name="form1">
用户名:
<s:textfield name="username" />
<br />
密 码:
<s:password name="password" />
<br />
<s:submit value="提交" />
</form>
</body>
</html>
loginAction.java
[java] view plain copy
package action;
import com.opensymphony.xwork2.ActionSupport;
public class loginAction extends ActionSupport {
/**
* 登录
*/
private static final long serialVersionUID = -6797327769546503535L;
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;
}
public String execute() {
System.out.println("username:" + username);
System.out.println("password:" + password);
return SUCCESS;
}
}
spring文件
action.xml
[java] view plain copy
<?xml version="1.0" encoding="utf-8"?>
<!-- <bean id="testAction" class="action.TestAction">
</bean> -->
<bean id="login" class="action.loginAction">
</bean>
</beans>
struts文件
action.xml
[java] view plain copy
<struts>
<package name="getIp" extends="json-default" namespace="/getIp">
<!-- <action name="testJson" class="testAction">
<result type="json"></result>
</action>
<action name="testJsp" class="testAction">
<result name="success">/index.jsp</result>
</action> -->
<action name="login" class="login">
<result type="json"></result>
</action>
</package>
</struts>