Search code examples
jspjax-rsform-parameter

Conflict between @FormParam and ${param}


I can use Expression Language to print a POST form value from current request in my view:

<p>Foo Name: ${fn:escapeXml(param.fooName)}</p>

But param.fooName EL variable is no longer populated when I capture form data into a Java variable using the @FormParam annotation in my controller:

@FormParam("fooName") String fooName

Full flow goes like this:

  1. Browser submits form to http://localhost:7101/myapp/rs/foo/new:

    @POST
    @Path("/new")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.TEXT_HTML)
    public Response saveNew(
        @FormParam("fooName") String fooName // <---
    ) {
        Map<String, Object> map = new HashMap<String, Object>();
        // Do stuff here
        return Response.ok(new Viewable("/foo/new", map)).build();
    }
    
  2. View is rendered from new.jsp:

    <%@ page contentType="text/html" pageEncoding="UTF-8" %>
    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    <p>Foo Name: ${fn:escapeXml(param.fooName)}</p>
    

If I remove the @FormParam("fooName") String fooName line then ${fn:escapeXml(param.fooName)} contains form data again.

Is there a way to access form data in both locations (Java controller and JSP view)?


Solution

  • Bug or feature, @FormParam seems to have side effects. However, form data is available at javax.servlet.http.HttpServletRequest so:

    @POST
    @Path("/new")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.TEXT_HTML)
    public Response saveNew() {
        // null when it doesn't exist (no exception thrown)
        String fooName = request.getParameter("fooName");
    
        Map<String, Object> map = new HashMap<String, Object>();
        // Do stuff here
        return Response.ok(new Viewable("/foo/new", map)).build();
    }
    
    <%@ page contentType="text/html" pageEncoding="UTF-8" %>
    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    <p>Foo Name: ${fn:escapeXml(param.fooName)}</p>