【问题标题】:jax-rs retrieve form parametersjax-rs 检索表单参数
【发布时间】:2011-05-13 03:43:56
【问题描述】:

我正在尝试使用 HttpServletRequest 从已发布的表单中检索传递给 jax-rs 的一些参数。但是,我的请求对象总是为我的参数返回空值。我不是以正确的方式去做吗?我已经发布了下面的代码,以及正在发送的示例请求。

这是我的服务:

@Path("/")
@Stateless
public class HomeController {

    @Context
    private HttpServletRequest request;
    @Context
    private HttpServletResponse response;
    @EJB
    private LoginServiceLocal loginService;

    @POST
    @Path("/authenticate")
    @Consumes("application/x-www-form-urlencoded")
    public void authenticate() throws Exception {
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        if (loginService.authenticate(email, password)) {
            response.sendRedirect("/app");
        } else {
            request.setAttribute("authenticationError", "Invalid email/password.");

        }
    }
}

示例请求:

POST http://localhost:8081/cheetah-web/authenticate HTTP/1.1
Host: localhost:8081
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.12) Gecko/20101026    Firefox/3.6.12
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://localhost:8081/cheetah-web/login
Cookie: JSESSIONID=a4e7aec0624206ad33754e35cce4
Content-Type: application/x-www-form-urlencoded
Content-Length: 39

email=unit%40test.com&password=testpass

【问题讨论】:

    标签: java rest jakarta-ee java-ee-6 jax-rs


    【解决方案1】:
    @POST
    @Path("/authenticate")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public void authenticate(@FormParam("email") String email, @FormParam("password") String password) throws Exception {
    
        if (loginService.authenticate(email, password)) {
            response.sendRedirect("/app");
        } else {
            request.setAttribute("authenticationError", "Invalid email/password.");
    
        }
    }
    

    【讨论】:

    • 如何像使用 UriInfo.getQueryParameters() 查询参数一样一次检索所有表单参数
    • 您将使用 MultivaluedMap 作为参数。例如, public void authenticate(MultivaluedMap form) { ... }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2019-11-22
    • 1970-01-01
    相关资源
    最近更新 更多