我是servlet概念的新手。我的要求就像将restful给定的URL转换为正文中的查询参数。
给定网址:
http://anydomain:8080/ServletBasics/HelloForm/India/Andhrapradesh
必填输出网址:
http://anydomain:8080/ServletBasics/HelloForm?Country=India&State=Andhrapradesh
使用给定的servlet代码完成了URL提取。任何人都可以帮助我将给定的URL转换为基于查询的URL。感谢
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
String vid = request.getRequestURI();
out.println("</body></html>");
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
修改后的代码:sdfd.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String url = request.getRequestURI();
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
if(url.equals("/servletTest/v1/code")) {
String[] words = url.split("/");
String newURI = url.replace(url, "/ws/simple/Apicode?"+"first_name="+words[2]+"&"+"last_name="+words[3]);
RequestDispatcher rd = request.getRequestDispatcher(newURI);
rd.forward(request, response);
out.println(newURI);
}
else
{
out.println("bad");
}
out.println("</html>");
out.println("</body>");
out.close();
}
的web.xml
<servlet>
<servlet-name>sdfd</servlet-name>
<servlet-class>sdfd</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sdfd</servlet-name>
<url-pattern>/v1/code</url-pattern>
</servlet-mapping>
我正在尝试转换
http://localhost:8080/servletTest/v1/code
到
http://localhost:8080/servletTest/ws/simple/Apicode?first_name=v1&last_name=code
但我得到的错误。
HTTP Status 404 - /servletTest/ws/simple/Apicode
type Status report
message /servletTest/ws/simple/Apicode
description The requested resource is not available.
Apache Tomcat/7.0.42
请帮助我哪里出错了? 感谢
答案 0 :(得分:1)
使用URLRewrite
您可以在以下网址中找到该文档:http://urlrewritefilter.googlecode.com/svn/trunk/src/doc/manual/4.0/index.html
例如:
<rule>
<from>^/HelloForm/([a-z]+)/([a-z]+)$</from>
<to>/HelloForm?Country=$1&State=$2</to>
</rule>
要配置UrlRewrite,请阅读手册http://urlrewritefilter.googlecode.com/svn/trunk/src/doc/manual/4.0/index.html