I am using Spring mapping. And have the following mapping code. The problem is there are like 20 possible misspelling for these and others that need to be accounted for. Rather than add a RequestMapping for each url which would be like 30 or 40, is there a way to simply redirect these. I know the way I am doing is not clean and would appreciate advice on how to keep my request mappings to a minium. Thanks.
#RequestMapping("/protect")
public String protect(Model model) {
QuickResponse qr = createQR();
model.addAttribute("qr", qr);
return "qr_general";
}
I am unsure as to what can be misspelled, but I am thinking you are referring to the path that is being mapped to.
The #RequestMapping annotation's default value member takes String[], so you should be able to put all of your mappings in one location:
#RequestMapping({"/protect", "/protekt", "/proteckt", "/protext"})
public String protect(Model model) {
QuickResponse qr = createQR();
model.addAttribute("qr", qr);
return "qr_general";
}
Related
I am pretty new in Spring MVC and I have the following doubt about how correctly achieve the following task.
I am working on a web application that implement a user registration process. This registration process is divided into some consecutive steps.
For example in the first step the user have to insert a identification code (it is a code that identify uniquely a user on some statal administration systems) and in the second step it have to compile a form for his personal data (name, surname, birth date, and so on).
So, actually I have the following controller class that handle these steps:
#Controller
public class RegistrazioneController {
#Autowired
private LoadPlacesService loadPlacesService;
#RequestMapping(value = "/iscrizioneStep1")
public String iscrizioneStep1(Model model) {
return "iscrizioneStep1";
}
#RequestMapping(value = "/iscrizioneStep2", method=RequestMethod.POST)
public String iscrizioneStep2(Model model, HttpServletRequest request, #RequestParam("cf") String codicFiscale) {
System.out.println("INTO iscrizioneStep2()");
//String codicFiscale = request.getParameter("cf");
System.out.println("CODICE FISCALE: " + codicFiscale);
model.addAttribute("codicFiscale", codicFiscale);
return "iscrizioneStep2";
}
#RequestMapping(value = "/iscrizioneStep3", method=RequestMethod.POST)
public String iscrizioneStep3(#ModelAttribute("SpringWeb")Step2FormCommand step2Form, ModelMap model, HttpServletRequest request) {
System.out.println("INTO iscrizioneStep3()");
System.out.println("NOME: " + step2FormCommand.getName());
return "iscrizioneStep3";
}
Into the iscrizioneStep2() it is retrieved the first code (#RequestParam("cf") String codicFiscale).
Into the iscrizioneStep3() it is retrieved a command object containing the data inserted into the form of the view in which this form was submitted, this one:
#ModelAttribute("SpringWeb")Step2FormCommand step2FormCommand
It works fine.
Now my problem is that I have another object named Step3View that have to be initialized with the aggregation of the #RequestParam("cf") String codicFiscale object retrieved into the iscrizioneStep2() method and the #ModelAttribute("SpringWeb")Step2FormCommand step2FormCommand retrieved into the iscrizioneStep3() method.
This Step3View class simply contain the String codicFiscale and all the fields of the Step2FormCommand class.
Now my doubts are: what is the best way to handle this situation? Where have I to declare this Step3View object? at controller level? (so I can use it in all my controller methods?). Have I to annotate this class with #Component (or something like this) to inject it in my controller?
What is the best solution for this situation?
I think in order to get an answer you need to understand the question and ask the right question. I think your question is "how do I pass a parameter from one page to another page in SpringMVC?". You specifically want to know how to pass the "cf" param, but readers here will tend to pass over questions that are too specific because it takes too much time to figure out what you want.
In answer to that, see Spring MVC - passing variables from one page to anther as a possible help.
Also, there are many good answers about this question for JSP in general, which can be worked into the SpringMVC architecture. See How to pass value from one jsp to another jsp page? as a possible help.
I am using the below URL to send a request,but i am getting a 404 error.
with a warning on server:No mapping found for HTTP request with URI
The URI is
http://localhost:8080/webstore/products/tablet/price;low=200;high=400?manufacturer="Google"
The method in controller used is
#RequestMapping(value="/products/{category}/{ByCriteria}",method=RequestMethod.GET)
public String getSpecificProductByFilter(#PathVariable("category")String ProductCategory,#MatrixVariable(pathVar= "ByCriteria") Map<String,List<Long>> filterParams,#RequestParam String manufacturer,Model model){
model.addAttribute("products",productService.getfilterproducts(ProductCategory,filterParams, manufacturer));
return "products";
}
The category signifies "tablet"in the URI
Criteria signifies"low" and "high"
manufacturer is"google"
For those who dont know, this is from book "Spring MVC begginers guide" by Amuthan G. This question is really old but I will give there my solution just in case somebody going to need that, just like me today.
First of all your #RequestMapping is wrong. It should looks like this:
#RequestMapping(value="/{category}/{ByCriteria}", method=RequestMethod.GET)
And reason for that is you already have #RequestMapping("/products") on this whole controller class (above your class declaration). And because you want to map
webstore/products/tablet and NOT webstore/products/products/tablet you have to leave that "products" mapping from this method.
Second thing is your URI. I know that in the books there is this one and its not really big deal, but if you dont want to have problems, leave quotation marks next to word Google. Its because you dont want to have value "Google" but just Google without these quation marks and if you let them there, you will have problems with comparing values. So your URI should looks like this.
http://localhost:8080/webstore/products/tablet/price;low=200;high=400?manufacturer=Google
For complete solution you have to do following steps:
In your repository and service interfaces and classes write method:
List<Product> getProductsByManufacturer(String manufacturer);
and implement it in same way like you wrote method GetProductsByCategory.
In your repository and service interfaces and classes write method:
Set<Product> getProductsByPrice(Map<String, List<String>> priceParams);
and implement it in same way like you wrote method getProductsByFilter.
Finnaly write method in Controller class:
#RequestMapping("/{category}/{ByPrice}")
public String filterProducts(#PathVariable("category") String productCategory,
#MatrixVariable(pathVar = "ByPrice") Map<String, List<String>> filterParams,
#RequestParam String manufacturer, Model model) {
List<Product> byCategory = productService.getProductsByCategory(productCategory);
List<Product> byManufacturer = productService.getProductsByManufacturer(manufacturer);
Set<Product> byPrice = productService.getProductsByPrice(filterParams);
byCategory.retainAll(byManufacturer);
byCategory.retainAll(byPrice);
model.addAttribute("products", byCategory);
return "products";
}
In my project this method look like this, but you can certainly do it in shorter way. After you complete these steps, your project should working. If not, feel free to ask me there. If you dont know how to write methods in steps 1 and 2 I will comment there code for you, but its almost same like that another methods as I said. I hope that this is going to help somebody.
I'm investigating Web Api in ASP.NET vNext using the daily builds. In a web api 2x project, I use HttpParameterBinding and ParameterBindingAttribute in some situations (see http://bit.ly/1sxAxdk); however, I can't seem to find either in vNext. Do/will these classes exist? If not, what are my alternatives?
Edit (1-22-15):
I want to be able to serialize a complex JS object to a JSON string, put the JSON string in a hidden form field (say name="data"), submit the form, and then bind my parameter to that JSON object on the server. This will never be done by a human, but rather by a machine. I also want this very same mechanism to work if the JSON is sent directly in the request body instead of form data. I also need this to work for several different types of objects.
I've been able to accomplish this scenario in Web Api 2.2 in a few different ways, including a custom ModelBinder; however, I remember reading an MSFT blog post that suggested to use a ModelBinder for query string binding, formatters for request body, and HttpParameterBinding for more general scenarios. Is it okay to read the request body in a ModelBinder ASP.NET 5, or is there a better mechanism for that? If so, then case closed and I will port my ModelBinder with a few minor changes.
I'm not sure that IInputFormatter will work for me in this case either.
Here are two rough approaches
Approach 1:
A quick and dirty approach would be to start with a Dto model
public class Dto
{
public Serializable Result { get; set; }
public Serializable FromForm
{
get { return Result; }
set { Result = value; }
}
[FromBody]
public Serializable FromBody
{
get { return Result; }
set { Result = value; }
}
}
public class Serializable
{
}
And an action method
public IActionResult DoSomething(Dto dto)
{
// Do something with Dto.Result
}
Then write a custom model binder for Serializable, that just works with Request.Form this way you never actually read the body yourself, and Form only reads it if it of type Form.
The down side of this is that ApiExplorer will not provide correct details (but I think since this is none-standard you are going to be in trouble here anyways).
Approach 2
You can alternatively just use the code from BodyModelBinder and create a custom binder for Serializable type above, that first tries to get it from the Form, and if it fails tries to get it from the Body. The Dto class in that case is not necessary.
Here is some pseudo code
if (inputType is yourtype)
{
if (request.Form["yourkey"] != null)
{
Use Json.Net to deserialize your object type
}
else
{
fall back to BodyModelBinder code
}
}
With this approach you can make it generic, and ApiExplorer will say the way to bind the type is unknown/custom (we haven't decided on the term yet :) )
Note:
Instead of registering the model binder you can use the [ModelBinder(typeof(customBinder))] attribute to apply it sparingly.
Here is a link to the BodyModelBinder code.
There is a new [FromHeader] attribute that allows you to bind directly to http header values if that is what you need.
https://github.com/aspnet/Mvc/issues/1671
https://github.com/aspnet/Mvc/search?utf8=%E2%9C%93&q=fromheader
I am developing a Spring Rest application. One of my methods is that:
#RequestMapping(method = RequestMethod.GET)
public #ResponseBody
Collection<Configuration> getConfigurationInJSON() {
Collection<Configuration> confList = new ArrayList<Configuration>();
...
I fill my confList and send it for GET request, it works. However when I want to keep that confList in a HashMap and send it after got it's entrySet as like that:
#RequestMapping(method = RequestMethod.GET)
public
#ResponseBody
Collection<Configuration> getAllConfigurationsInJSON() {
return configurationMap.values();
}
It gives me 406 error, so it means there is a wrong. What are the differences between that collections and why the second one is not same with first example?
For the sake of simplicity, can you just copy the values() collection?
new ArrayList<Configuration>(configurationMap.values());
Only thing that comes to my mind is that Spring expects mutable collection, but don't really understand why. Hard to say without debugging, try enabling org.springframework.web full logging.
The obvious difference is that configurationMap.values() is a Set.
You need to check if the JSON marshaller expects a List to be returned and is not able to marshal Set instances, as the marshaller will check the actual type of the returned value instead of the declared return type of the method, which is Collection.
By the way, isn't there any clue in the logs about this ?
A 3rd party is sending me part of the data to fill in my domain object via a query string. I need to partially fill in my domain object, and then have the user fill in the rest via a form. I don't have any control over the query string parameters coming in, so I can't change those, but I'd really like to be able to use Spring MVC's data binding abilities, rather than doing it by hand.
How can I do this?
To add some complication to this, some of the parameters will require extensive processing because they map to other objects (such as mapping to a user from just a name) that may not even exist yet and will need to be created. This aspect, I assume, can be handled using property editors. If I run into trouble with this, I will ask another question.
Once I have a partially filled domain object, passing it on to the edit view, etc. is no problem, but I don't know how to properly deal with the initial domain object population.
The only thing I have been able to come up with so far is to have an extra class that has it's properties named to match the inbound query parameters and a function to convert from this intermediary class to my domain class.
This seems like a lot of overhead though just to map between variable names.
Can you not just have the getter named differently from the setter, or have 2 getters and 2 setters if necessary?
private int spn;
// Standard getter/setter
public int getSpn() {
return spn;
}
public void setSpn(int spn) {
this.spn = spn;
}
// More descriptively named getter/setter
public int getShortParameterName() {
return spn;
}
public void setShortParameterName(int spn) {
this.spn = spn;
}
Maybe that is not standard bean convention, but surely would work?