Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

java - Fill a form with saved cookies

I have an action class that saves my cookies like this:

public String execute() {

    // Save to cookie
      Cookie name = new Cookie("name", userInfo.getName() );
      name.setMaxAge(60*60*24*365); // Make the cookie last a year!
      servletResponse.addCookie(name);
}

If I submit my form, I can see the cookies on the browser that has been created and saved. When the user submits, they get redirected to a new page, a page with all the stored information that they just created.

I want the user to be able to go back to the submit page and see all the information in the forms that they just submitted. Is it possible to do this with Struts2, by using the saved Cookies and get the form to fill in with the old data?

This is my form:

<s:textfield
        label="Name"
        name="name"
        key="name" 
        tooltip="Enter your Name here"/>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To send cookie you can use a cookie-provider interceptor. It allows you to populate cookies in the action via implementing CookieProvider. To apply this interceptor to the action configuration you can override the interceptors config

<action ... >
  <interceptor-ref name="defaultStack"/>
  <interceptor-ref name="cookieProvider"/>
  ...
</action> 

The CookieProvider has a method to implement,

public class MyAction extends ActionSupport implements CookieProvider {

    @Override
    public Set<Cookie> getCookies(){
      Set<Cookie> cookies = new HashSet<>();
      Cookie name = new Cookie("name", userInfo.getName() );
      name.setMaxAge(60*60*24*365); // Make the cookie last a year!
      name.setPath("/"); //Make it at root.
      cookies.add(name);
      return cookies;
    }

}

In the form

<s:set var="name">${cookie["name"].value}</s:set>
<s:textfield
        label="Name"
        name="name"
        value="%{#name}"
        tooltip="Enter your Name here"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...