0

My servlet is mapped with <url-pattern> /controller/*/* </url-pattern> my url is like this controller/12341/ABC123 will always like this but values can be changed.

I am trying to get value of first * and second * which presents serial & mac

I write following code but it return only last part ACB123

String mac= request.getPathInfo().replace("/", "");

How can I get both vaules?

mumair
  • 2,768
  • 30
  • 39
  • Use `split` method and get the last 2 indexes? – Husam Nov 10 '15 at 09:27
  • This problem has been solved countless times by many web frameworks... do you really want to "reinvent the wheel" and roll-your-own servlet based solution? – lance-java Nov 10 '15 at 09:28
  • @LanceJava Thank you, currently I am developing it in custom way. Means not using framework – mumair Nov 10 '15 at 09:31

1 Answers1

0

If I read the servlet spec correctly you cannot have multiple wildcards. Try

<url-pattern>/controller/*</url-pattern>

And then:

String[] parts = request.getPathInfo().split("/");
String serial = parts[1]; // before last index
String mac = parts[2]; // last index

Of course you will need some error handling for this.

On a related note: Pure servlet API is a pain to work with. If you have just this only servlet or are constrained somehow, this might be OK. However if you have more servlets and even need HTTP request parameter handling, parsing etc., using a framework like Spring WebMVC might be more appropriate.

Husam
  • 2,069
  • 3
  • 19
  • 29
Jan Thomä
  • 13,296
  • 6
  • 55
  • 83
  • when I `System.out.println("serial: " + serial + ", mac: " + mac);` then my server threw exception: `java.lang.NumberFormatException: For input string: "12341ABC123"`. Can you please help to figure out problem – mumair Nov 10 '15 at 10:23
  • It's rather unlikely that this exception comes from `System.out.println`. I would need to see the full code. – Jan Thomä Nov 10 '15 at 10:25
  • I have used your code and after that I write `System.out.println(...)` on execution it give exception mentioned previously – mumair Nov 10 '15 at 10:27