url encoding in java?

隐身守侯 提交于 2019-12-23 05:33:27

问题


I want to know that what is url encoding. I have 2 jsp pages and one servlet. When I run the application the url displayed is :

http://localhost:8080/myproject/index.jsp

where

index.jsp :

<form action="Myservlet" method="post">
    <input type="text" name="mytext" id="mytext"/>
    <input type="submit" value="submit"/>
</form>

after the submit button is clicked the URL displayed is :

http://localhost:8080/myproject/Myservlet

What is the meaning of URL encoding? How can I encode url?

From index.jsp goes to Myservlet then to result.jsp

Myservet#doPost // Do I need to do URL encoding here? If yes how ?

  fetching data from db.......
  ....................
  String nextJSP = "/result.jsp";
  RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
  dispatcher.forward(request,response);

result.jsp

displays data here


回答1:


There are two types of encoding: HTML form encoding and URL re-writing.

In form encoding, the URL string is converted into a valid ASCII format that's Internet-ready. From the URLEncoder.encode(String, String) docs:

Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme. This method uses the supplied encoding scheme to obtain the bytes for unsafe characters.

The second kind is URL rewriting. The URL string is encoded with a session id in case the client browser doesn't support (or has disabled) cookies or session tracking. From the HttpServletResponse.encodeURL(String) docs:

Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. For example, if the browser supports cookies, or session tracking is turned off, URL encoding is unnecessary.




回答2:


I think you have misundersting here. Neither HTML Form Encoding nor URL Re-writing is for what you want to achieve.

If you want to achieve like .

For example: instead of typing http://localhost:8080/search.jsp?xxx the user would see http:/localhost:8080/search?xxx

You can create a servlet mapping like this:

<servlet-mapping>
   <servlet-name>MappingServlet</servlet-name>
   <url-pattern>path/*</url-pattern>
 </servlet-mapping>

The url-pattern must be edited to suit your needs. You need of course to create the servlet in order to map the url to the actual jsp. This technique is used by most of the MVC frameworks.

Read More on How to develop JSP/Servlets Web App using MVC pattern?




回答3:


Use java.net.URLEncoder.encode(s, "UTF-8") where s is the string to encode.

This is required whenever we send text as path segments, query string arguments, etc...

Example: see the documentation



来源:https://stackoverflow.com/questions/10276473/url-encoding-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!