Display All Request Parameters

Parsing a URL

The URL class provides several methods that let you query URL objects. You can get the protocol, authority, host name, port number, path, query, filename, and reference from a URL using these accessor methods:

getProtocol Returns the protocol identifier component of the URL. getAuthority Returns the authority component of the URL. getHost Returns the host name component of the URL. getPort Returns the port number component of the URL. The getPort method returns an integer that is the port number. If the port is not set, getPort returns -1. getPath Returns the path component of this URL. getQuery Returns the query component of this URL. getFile Returns the filename component of the URL. The getFile method returns the same as getPath , plus the concatenation of the value of getQuery , if any. getRef Returns the reference component of the URL.

Remember that not all URL addresses contain these components. The URL class provides these methods because HTTP URLs do contain these components and are perhaps the most commonly used URLs. The URL class is somewhat HTTP-centric.

You can use these getXXX methods to get information about the URL regardless of the constructor that you used to create the URL object.

The URL class, along with these accessor methods, frees you from ever having to parse URLs again! Given any string specification of a URL, just create a new URL object and call any of the accessor methods for the information you need. This small example program creates a URL from a string specification and then uses the URL object’s accessor methods to parse the URL:

import java.net.*; import java.io.*; public class ParseURL < public static void main(String[] args) throws Exception < URL aURL = new URL("http://example.com:80/docs/books/tutorial" + "/index.html?name=networking#DOWNLOADING"); System.out.println("protocol = " + aURL.getProtocol()); System.out.println("authority = " + aURL.getAuthority()); System.out.println("host = " + aURL.getHost()); System.out.println("port = " + aURL.getPort()); System.out.println("path = " + aURL.getPath()); System.out.println("query = " + aURL.getQuery()); System.out.println("filename = " + aURL.getFile()); System.out.println("ref = " + aURL.getRef()); >>

Here is the output displayed by the program:

protocol = http authority = example.com:80 host = example.com port = 80 path = /docs/books/tutorial/index.html query = name=networking filename = /docs/books/tutorial/index.html?name=networking ref = DOWNLOADING

Источник

Читайте также:  Python интерпретатор что это

Get all Request Parameters in Java

In this tutorial, we’ll show you how to get all request parameters in java. Ideally, the server should know the parameter names that was sent by the client browser. I have created a simple Spring Controller that gets a request from the client and redirect the user to another page that displays all his request parameters and its values.

Create A Servlet Controller

In our Controller, we take a parameter HttpServletRequest which contains the client request including its parameters.

@Controller @RequestMapping("/sample") public class SampleController < @RequestMapping(value = "/get", method= RequestMethod.GET) public ModelAndView getParameters(HttpServletRequest request)< Enumeration enumeration = request.getParameterNames(); MapmodelMap = new HashMap<>(); while(enumeration.hasMoreElements()) < String parameterName = enumeration.nextElement(); modelMap.put(parameterName, request.getParameter(parameterName)); >ModelAndView modelAndView = new ModelAndView("sample"); modelAndView.addObject("parameters", modelMap); return modelAndView; > >

To get all request parameters in java, we get all the request parameter names and store it in an Enumeration object. Our Enumeration object now contains all the parameter names of the request. We then iterate the enumeration and get the value of the request given the parameter name.

We store the the name and its value in a Map and add it to a ModelAndView and redirect to sample.jsp. Below is the sample.jsp file:

      

List of Request Parameter Names and its Values

modelMap = (Map) request.getAttribute("parameters"); for(String key: modelMap.keySet())< out.print(key); out.print(" : "); out.print(modelMap.get(key)); out.print("
"); > %>

Testing our WebApp

To test it, we type the url in the browser:

http://localhost:8080/sample/get?name=javapointers&language=java&version=8

When we hit Enter, the resulting page is below:

Источник

Get all Request Parameters in Servlet

With this tutorial we shall show you how to get all requests parameters in a Java Servlet. This the most basic step you have to consider when developing a Servelt application because HTTP is based mostly on parameters exchange. Basically in order to get all Request Parameters in Servlet, one should take the following steps:

  • Create a handleRequest method so you can use it both in doGet and doPost methods.
  • Use HttpServletRequest.getParameterNames to get an Enumeration of parameter names.
  • Use HttpServletRequest.getParameterValues(paramName) to get the parameters values.
Читайте также:  Import java integer parseint

In order to help you master programming with Java Servlets, we have compiled a kick-ass guide with all the major servlet API uses and showcases! Besides studying them online you may download the eBook in PDF format!

Thank you!

Let’s see the simple code snippets that follow:

package com.javacodegeeks.snippets.enterprise; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class GetAllRequestParametersInServlet extends HttpServlet < private static final long serialVersionUID = -2128122335811219481L; public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException < handleRequest(req, res); >public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException < handleRequest(req, res); >public void handleRequest(HttpServletRequest req, HttpServletResponse res) throws IOException < PrintWriter out = res.getWriter(); res.setContentType("text/plain"); EnumerationparameterNames = req.getParameterNames(); while (parameterNames.hasMoreElements()) < String paramName = parameterNames.nextElement(); out.write(paramName); out.write("n"); String[] paramValues = req.getParameterValues(paramName); for (int i = 0; i < paramValues.length; i++) < String paramValue = paramValues[i]; out.write("t" + paramValue); out.write("n"); >> out.close(); > >
  JCG Snippets Web Project JCG Snippets Application com.javacodegeeks.snippets.enterprise.GetAllRequestParametersInServlet  JCG Snippets Application /jcgservlet  
http://myhost:8080/jcgsnippets/jcgservlet?param1=paramvalue1¶m2=paramvalue2a¶m2=paramvalue2b
param2 paramvalue2a paramvalue2b param1 paramvalue1

This was an example on how to get all Request Parameters in Servlet.

Источник

Java get all url parameters

  • Language
  • HTML & CSS
  • Form
  • Java interaction
  • Mobile
  • Varia
  • Language
  • String / Number
  • AWT
  • Swing
  • Environment
  • IO
  • JS interaction
  • JDBC
  • Thread
  • Networking
  • JSP / Servlet
  • XML / RSS / JSON
  • Localization
  • Security
  • JNI / JNA
  • Date / Time
  • Open Source
  • Varia
  • Powerscript
  • Win API & Registry
  • Datawindow
  • PFC
  • Common problems
  • Database
  • WSH & VBScript
  • Windows, Batch, PDF, Internet
  • BigIndex
  • Download
  • TS2068, Sinclair QL Archives
  • Real’s HowTo FAQ
  • Donate!
  • Funny 1
  • Funny 2
  • Funny 3
  • Funny 4
  • One line
  • Ascii Art
  • Deprecated (old stuff)

    Get URL parameters using JDK HTTP server Tag(s): Networking

    About cookies on this site

    We use cookies to collect and analyze information on site performance and usage, to provide social media features and to enhance and customize content and advertisements.

    The server is very simple. If you want to access parameters passed in the URL (using the GET method) then you need to provide a method to extract them.

    import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; public class SimpleHttpServer2 < public static void main(String[] args) throws Exception < HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0); server.createContext("/info", new InfoHandler()); server.createContext("/get", new GetHandler()); server.setExecutor(null); // creates a default executor server.start(); System.out.println("The server is running"); >// http://localhost:8000/info static class InfoHandler implements HttpHandler < public void handle(HttpExchange httpExchange) throws IOException < String response = "Use /get?hello=word&foo=bar to see how to handle url parameters"; SimpleHttpServer2.writeResponse(httpExchange, response.toString()); >> static class GetHandler implements HttpHandler < public void handle(HttpExchange httpExchange) throws IOException < StringBuilder response = new StringBuilder(); Map parms = SimpleHttpServer2.queryToMap(httpExchange.getRequestURI().getQuery()); response.append(""); response.append("hello : " + parms.get("hello") + "
    "); response.append("foo : " + parms.get("foo") + "
    "); response.append(""); SimpleHttpServer2.writeResponse(httpExchange, response.toString()); > > public static void writeResponse(HttpExchange httpExchange, String response) throws IOException < httpExchange.sendResponseHeaders(200, response.length()); OutputStream os = httpExchange.getResponseBody(); os.write(response.getBytes()); os.close(); > /** * returns the url parameters in a map * @param query * @return map */ public static Map queryToMap(String query) < Mapresult = new HashMap(); for (String param : query.split("&")) < String pair[] = param.split("="); if (pair.length>1) < result.put(pair[0], pair[1]); >else < result.put(pair[0], ""); >> return result; > >

    Источник

Оцените статью