servlet url路径和参数之间有什么不同?

时间:2013-02-20 13:16:59

标签: java url tomcat servlets path

localhost/user/user123localhost/user?user=user123localhost/?user=user123之间有什么区别?

如何从servlet中的URL user123获取参数localhost/user/user123

提前致谢

5 个答案:

答案 0 :(得分:3)

您可以从HttpServletRequest对象的getPathInfo()进行解析。

示例代码

String urlPath = request.getPathInfo();

System.out.println("" + urlPath.substring(urlPath.lastIndexOf("/"), urlPath.length()- 1));

答案 1 :(得分:0)

localhost / user / user123看起来像是一种识别资源的RESTful方式。

我认为其他两个不是。

答案 2 :(得分:0)

这些都可以从 Servlet API 访问。检查HttpServletRequest,您可以从那里访问所有信息。

实际值可能与您的webapp部署方式不同,但通常是

  • localhost是上下文路径
  • 之后的字符串是Servlet PAth
  • ?之后的参数是查询字符串 - 如果要使用
  • ,则必须解析它

答案 3 :(得分:0)

  • localhost/user/user123 - 此网址将由模式/user/user123
  • 处理
  • localhost/user?user=user123 - 此网址将由模式/user处理,user参数设置为user123(对于GET请求)
  • localhost/?user=user123 - 此网址将由模式/处理,user参数设置为user123(同样适用于GET)

我不知道如何使用纯servlet从url user123检索localhost/user/user123,但使用web MVC框架非常容易。春天的例子:

@Controller
@RequestMapping("/user")
public class Controller {
    @RequestMapping(value = "/{user}")
    public String getUser((@PathVariable String user) {
        //here variable "user" is available and set to "user123" in your case
    }
}

答案 4 :(得分:0)

通常你会传递像

这样的参数
/localhost/Servlet?parameter1=one

或JSP

/localhost/mypage.jsp?parameter1=one

在servlet中,您可以使用请求对象访问参数。所以一般都是这样的:

String parameter1 = request.getParameter("parameter1");

以下是关于HttpServletRequest

的getParameter的一些细节

希望这有帮助。

相关问题