Parameters from URL using Java and spring boot - java

I am using Java and spring boot and I need to get information by a URL and store it in my class in Java. My URL is like this one
localhost:8080/send?adress=example
I want to store the value of the URL parameter to a variable in Java.

I would suggest reading tutorials on spring boot and web services such as this one:
https://spring.io/guides/gs/rest-service/
The RequestParam annotation is used to bind method parameters to web request parameters. e.g.
#RequestMapping(value="/send", method=RequestMethod.GET)
public String method(#RequestParam(value="address") String address) {
...
}

You don't need to send a parameter with the URL, it should be sent through request parameters.
Once you have added a parameter with the request, in spring-boot by #RequestParam we can get parameter values. e.g
#RequestMapping(value="/order/search", method=RequestMethod.GET)
public String method(#RequestParam(value="orderNumber") String orderNumber) {
get Order by orderNumber...
}

Related

How to decode multiple request parameters in Spring MVC

I am trying to decode request parameters in a Spring MVC controller. The client has encoded these parameters and I want to bind them to an object. I expect that the parameters will automatically be decoded by Spring MVC when they are bound to the object.
I am trying to decode multiple request parameters in my code using Spring MVC. The client sends a request with multiple parameters, such as page, size, and search. I am using the #GetMapping annotation to handle the request and the #Valid annotation to validate the UserListRequest object. However, when the request is received, the search attribute is not being decoded properly and it is still in its encoded form.
#GetMapping
public List<User> getUsers(#PathVariable #NotNull String tenantKey,
#Valid UserListRequest request) {
// some code
}
The class UserListRequest
public class UserListRequest {
private Set<UserRole> role;
private String search;
// other attributes
}
The clients sends a request like this
GET http://localhost:8080/api/user?page=0&size=20&search=some_text%2B
Spring puts all the parameters to the object UserListRequest, but the attribute search is not decoded. It has some_text%2B and not some_text+.
I have tried using the #ModelAttribute annotation but it did not work as expected. The search attribute is still in its encoded form.
I would like to know how I can properly decode the search attribute and bind it to the UserListRequest object in my Spring MVC controller.

using spring mvc redirect a url pattern to a specific controller

i would like to redirect a request something like this
localhost:8080 /firstSpringProject/{uniqueusername}
to a specific controller named 'profile':
#RequestMapping(value="/profile")
public String profiles(Model model){
based on the uniqueusername i would like to render a profile page
return "profile";
}
I am using spring mvc; how can I resolve this situation is there any other way to do this?
Spring documentation says on redirect view:
Note that URI template variables from the present request are
automatically made available when expanding a redirect URL and do not
need to be added explicitly neither through Model nor
RedirectAttributes. For example:
#RequestMapping(value = "/files/{path}", method = RequestMethod.POST)
public String upload(...) {
// ...
return "redirect:files/{path}";
}
Keep in mind that version lower than 3.1.4 are affected by a memory leak due to caching redirect views.
If you are using Spring 3.1.3 or lower and you are doing this
return "redirect : profile?username="+username;
you will see OutOfMemoryError sometime.
I think you may use spring path variable here. You have to create a controller method that will take username as per your URL requirement and will redirect to profile method with username parameter.
#RequestMapping(value="/{username}")
public String getUserName(Model model,#PathVariable("username") String username){
//process username here and then redirect to ur profile method
return "redirect : profile?username="+username;
}
#RequestMapping(value="/profile")
public String profiles(Model model,String username){
//have a username and render a profile page
return "profile";
}
Thank you

Multipart Rest based Java spring web service

Im new to java based web service development.
I need to create a web service which accepts multipart data(ex: zip file).
Please help me out how to mention that in the function.
below is my current web service code which is accepting data in the form of json.
#RequestMapping(value="/workitems/updateData", method=RequestMethod.POST)
#ResponseBody
public Object updateData(#RequestHeader String deviceToken, #RequestBody FormFields[]
formFields,HttpServletResponse response) throws Exception {
//some code
}
please guide me to how to accept the multipart data in the web service method.
thanks in advance.
#RequestMapping(
value ="/workitems/updateData",method=RequestMethod.POST ,headers="Accept=application/xml, application/json")
public #ResponseBody
Object updateData(HttpServletResponse response,#RequestHeader String deviceToken,
#RequestParam ("file") MultipartFile file) throws Exception {
}
You can support it as above.
You can use normal Upload technique which you use in Servlet - commons-fileupload.jar way.
The same code placed in a method inside your controller will work fine. Make sure you pass HttpServletRequest object to your method.

what's different between servlet url path and parameter?

What's the difference between localhost/user/user123, localhost/user?user=user123 and localhost/?user=user123?
How to get the parameter user123 from a URL localhost/user/user123 in servlet?
Thanks in advance
You can parse from the getPathInfo() of HttpServletRequest Object.
sample code
String urlPath = request.getPathInfo();
System.out.println("" + urlPath.substring(urlPath.lastIndexOf("/"), urlPath.length()- 1));
localhost/user/user123 looks like a RESTful way to identify a resource.
The two others aren't, I think.
These all are accessible from Servlet API. Check HttpServletRequest, you can access all information from there.
The actual values may differ how your webapp was deployed, but usually
localhost is the Context Path
the String after that is the Servlet PAth
the parameters after the ? is the Query String - you have to parse it, if you want to use
Generally you pass parameters like
/localhost/Servlet?parameter1=one
or for a JSP
/localhost/mypage.jsp?parameter1=one
In a servlet you can access the parameters by using the request object. So generally like this:
String parameter1 = request.getParameter("parameter1");
Here is some detail on getParameter for HttpServletRequest
Hope this helps.
localhost/user/user123 - this url will be handled by pattern /user/user123
localhost/user?user=user123 - this url will be handled by pattern /user, with user parameter set to user123 (for GET request)
localhost/?user=user123 - this url will be handled by pattern / with user parameter set to user123 (again, for GET)
I don't know how to retrieve user123 from url localhost/user/user123 with pure servlets, but it's pretty easy with web MVC frameworks. Spring example:
#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
}
}

Find whether URL mapping exists in Spring MVC 3.1 using code in a controller

I am using Spring 3.1 MVC and in one of the request I get parameter which is URL.
e.g. http:/myapp/controllername?url=someurl
I need to find out in my controller method whether some URL is configured in my application.
I tried using RequestMappingHandlerMapping instance to get
Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
But I have a string which is URL, I will need to create a RequestMappingInfo object out of this to look up in this map, which doesn't have any constructor based on just URL.
How to find whether an URL mapping exists in spring mvc 3.1 using code in a controller?
You can use requestMappingInfo.getPatternsCondition() to check the mapping path; and it has toString method for you to compare with your url string.
Set<RequestMappingInfo> rmSet = handlerMapping.getHandlerMethods().keySet();
for (RequestMappingInfo rm : rmSet) {
if("[YourURLPath]".equals(rm.getPatternsCondition().toString())) {
// URL mapping matched
}
}
Example: For url http://mydomain/test/abc the above condition should be as
if("[/test/abc]".equals(rm.getPatternsCondition().toString()))
I believe you have already autowired handlerMapping object in your controller, as below
#Autowired
private RequestMappingHandlerMapping handlerMapping;

Categories

Resources