Set Default paging null - spring-mvc

I use spring boot 2
Seem like spring boot put a default value for pageable, if user put nothing... I would like to get null or nothing...
#GetMapping(value = "networks")
public ResponseEntity<Page<Networks>> getNetworks(#RequestParam(required = false) String search, Pageable page) {
}
So I tried to put #requestparam with required=false:
#GetMapping(value = "networks")
public ResponseEntity<Page<Networks>> getNetworks(#RequestParam(required = false) String search, #RequestParam(required = false) Pageable page) {
}
but if user type
http://localhost:8080/networks?search=&page=0&size=10&sort=id%2Casc 50
I get
"Failed to convert value of type 'java.lang.String' to required type
'org.springframework.data.domain.Pageable'; nested exception is
java.lang.IllegalStateException: Cannot convert value of type
'java.lang.String' to required type
'org.springframework.data.domain.Pageable': no matching editors or
conversion strategy found", "path" : "/
If user type
http://localhost:8080/networks
that work

Related

Missing URI template variable 'id' for method parameter of type String - Spring MVC

I have built a Spring MVC controller using the following code:
#RequestMapping(name = "/edit-soldier/{id}", method = RequestMethod.GET)
public ModelAndView editSoldierForm(#PathVariable String id) throws FileNotFoundException {
System.out.println("id:" + id);
(snip ...)
}
When I call the controller using the following URL : http://myurl/edit-soldier/Q65683623,
I get the following error:
There was an unexpected error (type=Internal Server Error, status=500).
Missing URI template variable 'id' for method parameter of type String
org.springframework.web.bind.MissingPathVariableException: Missing URI template variable 'id' for method parameter of type String
I have tried to replace name by value or path but it doesn't work either (I am getting a 404 error this time).
What am I doing wrong?
Change this
#RequestMapping(name = "/edit-soldier/{id}", method = RequestMethod.GET)
to
#RequestMapping(value = "/edit-soldier/{id}", method = RequestMethod.GET)
Note: Change name to value
or
#GetMapping("/edit-soldier/{id}")

Unexpected character encountered while parsing Value asp.net Core

this is i am trying to do but getting this error
Unexpected character encountered while parsing value
var searchModel = Newtonsoft.Json.JsonConvert.DeserializeObject<EmployeeSearchModel>(filter);
Model
public class EmployeeSearchModel
{
public string EmployeeNameSearch { get; set; } = null;
public string SearchFilter { get; set; } = null;
}
Error Detail
I suspect filter is not a valid JSON.
In fact, the exact error can be reproduced by the following code:
Newtonsoft.Json.JsonConvert.DeserializeObject("a");
//Error: Unexpected character encountered while parsing value: a. Path '', line 0, position 0.
coming string in filter variable
I believe the translation of what you said should be "The incoming filter variable is a string".
When receiving this error it can also mean your controller's action method has not been setup to take in a specific class to deserialize to.
For example this will fail with your error message:
public IActionResult Post([FromBody] string filter)
{
var searchModel = Newtonsoft.Json.JsonConvert.DeserializeObject<EmployeeSearchModel>(filter);
But the following will succeed because we have identified a specific object to deserialize and do not have to call Newtonsoft because .Net Core has deserialized it for us:
public IActionResult Post([FromBody] EmployeeSearchModel searchModel)
{
If (searchModel.EmployeeNameSearch == "OmegaMan")
...
So make sure your JSON incoming body is the same as the class.

Spring Model Argument is not enriched by controller mapping

In a Spring Controller method, I want to enrich the Model elements from what is posted from the jsp file.
Here is the start of the code function.
the model is void everytime the function is entered. Any Hint about that?
#RequestMapping(value = Uris.IMPORTADDRBOOK)
public String mainImportController(HttpServletRequest request, HttpServletResponse response, Model model,
#RequestParam(value = "chosenSP", required = false) String bookToImportName,
#RequestParam(value = "catMode", required = false) String catMode,
#RequestParam(value = "transition", required = false) ImportControllerTransitions transition) {
logger.debug(String.format("controller import. Etat entrée : %s, transition demandée : %s, chosen SP : %s, catmode : %s",
model.asMap().get("importState"), transition, bookToImportName, catMode));
logger.debug(String.format("Modele Entree Import Controller:"));
for (String attribute : model.asMap().keySet())
logger.debug(String.format("%s : %s", attribute, model.asMap().get(attribute)));
if (!model.containsAttribute("importState"))
model.addAttribute("importState", ImportControllerState.INITIAL);
switch ((ImportControllerState) model.asMap().get("importState")) {
case INITIAL:
if (transition == ImportControllerTransitions.CONNECTORCHOICE) {
model.addAttribute("importState", ImportControllerState.CONNECTOR);
if (bookToImportName != null)
model.addAttribute("chosenSP", DynAddrBookTypes.valueOf(bookToImportName));
}
break;
default:
break;
}
logger.debug(String.format("Modele sortie Import Controller:"));
for (String attribute : model.asMap().keySet())
logger.debug(String.format("%s : %s", attribute, model.asMap().get(attribute)));
return Uris.IMPORTADDRBOOK;
}
The JSP can read correctly the model attribute but when I come back into the controller, model is empty again...
Thanks in advance,
Following up on Bart's comments above and answer from Donal Boyle in this related SO question, #SessionAttributes is the right way to keep the values of the model objects despite the fact the Spring MVC server side is stateless.
The code in my question works just fine provided the class declaration include the #SessionAttributes annotation as below :
#Controller
#SessionAttributes({ "importState", "chosenSP", "catMode" })
public class ImportContactController {

What's wrong with "i"? Asp.Net MVC 3

I am reading an MVC book and following the examples from it to create a music store project.
In one of the example, it creates a controller, calls an action method with a parameter in the URL. I found something interesting. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcMusicStore.Controllers
{
public class StoreController : Controller
{
//
// GET: /Store/
public string Index()
{
return "Hello from Store.Index()";
}
// GET: /Store/Browse?genre=?Disco
public string Browse(string genre)
{
string message =
HttpUtility.HtmlEncode("Store.Browse, Genre = " + genre);
return message;
}
//
// GET: /Store/Details/5
public string Details(int id)
{
string s = "Store.Details, ID = " + id;
return s;
}
}
}
In the last method "Details(int id)", if I call it using a URL like
http://localhost:4961/store/details/6
It's alright. But if I change the name of the parameter from "id" to "i", the compiler doesn't complain but when I ran it I would get an error message that I am unable to interpret.
Part of the error message is like this:
The parameters dictionary contains a null entry for parameter 'i' of non-nullable type 'System.Int32' for method 'System.String Details(Int32)' in 'MvcMusicStore.Controllers.StoreController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
So what is wrong if I just use "i" for integer?
It's because in your route definition you used {id}. Because Int32 is a value type it means that you have to pass a value for this parameter when invoking the action.
For example you could call it like this and still keep your default route definition with {id}
http://localhost:4961/store/details?i=6
You literally have to use the name of the variable (seriously). I ran into this a while back and was.... let's say, surprised. The entry in the url must match the method parameter.
The problem is that when you change
public string Details(int id)
to
public string Details(int i)
then you introduce a breaking change. The code which called Details by passing parameter id is now passing a parameter which does not match. As a result, Details is called and i does not match anything. When calling and omitting a parameter, the parameter must be marked as optional with this syntax:
public string Details(int i = 0)
But since it is not, you get the error. Either change it back to id, or change the caller to use i (as #Darin points out, the binding is coming from your default route definition).
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
You would need to change these to be
"{controller}/{action}/{i}", // URL with parameters
new { controller = "Home", action = "Index", i = UrlParameter.Optional }, // Parameter defaults

ASP.NET session object generates InvalidCastException when trying to do a "valid" cast

in a method I store a struct into HttpSession:
HttpContext.Current.Session["search_headers"] = ra;
where ra is my custom struct of type "replySearchAjax".
In a webmethod, that belongs to same namespace, I am trying to do:
[WebMethod(EnableSession = true)]
public replySearchAjax RestorePhenSearchTable()
{
if (HttpContext.Current.Session["search_headers"] != null)
{
replySearchAjax aa = (replySearchAjax) HttpContext.Current.Session["search_headers"];
return aa;
}
but the line with typecast returns
{"Message":"Specified cast is not valid."
"ExceptionType":"System.InvalidCastException"}
Examination of session variable at breakpoint at the line that produces exception shows that inside it are valid replySearchAjax fields.
How I would make it work? Thanks in advance!

Resources