Java jax-rs 检索表单参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4234084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jax-rs retrieve form parameters
提问by Brian DiCasa
I'm trying to retrieve some parameters that are passed to jax-rs from a posted form with the HttpServletRequest. However, my request object is always returning null values for my parameters. Am I not going about this the right way? I've posted the code below, along with an example request that is getting sent.
我正在尝试从带有 HttpServletRequest 的已发布表单中检索传递给 jax-rs 的一些参数。但是,我的请求对象总是为我的参数返回空值。我不是以正确的方式解决这个问题吗?我已经发布了下面的代码,以及正在发送的示例请求。
Here is my service:
这是我的服务:
@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.");
}
}
}
Example request:
示例请求:
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
采纳答案by Brian DiCasa
@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.");
}
}