Struts2中Action接收请求参数的方式
1、以Servlet的方式获取
1.1、新建登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/login.do">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" name="登录">
</form>
</body>
</html>
1.2、配置action
<package name="p1" extends="struts-default" namespace="/user">
<action name="hello" class="com.fu.controller.HelloAction" method="sayHello">
<result name="success" type="dispatcher">/success.jsp</result>
</action>
<action name="login" class="com.fu.controller.LoginAction" method="login">
</action>
</package>
<!--修改struts的后缀名-->
<constant name="struts.action.extension" value="do"></constant>
<!--是否是开发模式-->
<constant name="struts.devMode" value="true"></constant>
1.3、创建LoginAction类
public class LoginAction extends ActionSupport {
public String login() {
HttpServletRequest request = ServletActionContext.getRequest();
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username+"-"+password);
return null;
}
}
1.4、启动项目
在浏览器中输入:http://localhost:8080/Struts2/login.jsp
在控制器中查看输出结果与登录页面输入的用户名、密码是否一致;
2、Action模型驱动封装参数
调整后台方法:
public class LoginAction extends ActionSupport implements ModelDriven<User> {
private User user = new User();
public String login() {
String username = user.getUsername();
String password = user.getPassword();
System.out.println(username+"-"+password);
return null;
}
@Override
public User getModel() {
return user;
}
}