Struts2 值在验证失败回到原来页面的时候会丢失的解决方案

关键词

struts2 验证失败后 返回原来的页面 如何将原来的值保留?
Struts2 值在验证失败回到原来页面的时候会丢失的解决方案?


如登录界面保留原来的用户名和密码



login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<%
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%>">
    <title>My JSP 'login.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<style>
	.errorMessage{
		color:red;
	}
	</style>
  </head>
  
  <body>
		<form action="login" method="post">
			username:
			<input type="text" name="user.username"  value="${user.username}"  label="username" />
			<span class=errorMessage>
				<s:property value="errors['user.username'][0]" />
			</span>
			<br>
			password:
			<input type="password" name="user.password" value="${user.password}" label="password" />
			<span class=errorMessage>
				<s:property value="errors['user.password'][0]" />
			</span>
			<br>
			<input type="submit"  align="left" />
		</form>
	<br/>
	<s:debug />


	</body>
</html>
LoginAction.java
package com.action;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.domain.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
	private User user ;
	public String login(){
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get( ServletActionContext.HTTP_REQUEST);
		if(user==null)
			return INPUT;
		String ret = SUCCESS;
		if(!user.getUsername().trim().equals("admin")){
			this.addFieldError("user.username", "Username Invalid");
			ret = INPUT;
		}
		if(!user.getPassword().trim().equals("1")){
			this.addFieldError("user.password", "Password Invalid");
			ret = INPUT;
		}
		return ret;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	@Override
	public String execute() throws Exception {
		System.out.println("login action @ method *execute()");
		return super.execute();
	}
}

struts.xml
加入拦截器 
defaultStack
<action name="login" method="login"  class="com.action.LoginAction">
	<interceptor-ref name="defaultStack"/>
	<result name="success" type="redirect">/success.jsp</result>
	<result name="login">/login.jsp</result>
	<result name="input">/login.jsp</result>
</action>



结果如下图

其他解决方法:


©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页