I have written the following code :
#Controller
#RequestMapping("/test")
public class Home {
#RequestMapping(value = "index")
public String index() {
return "index";
}
#RequestMapping(value = "welcome")
public String welcome(#RequestParam("txtname") String name, ModelMap model) {
model.addAttribute("msg", name);
return "index";
}
}
Now I have two doubts. I want something like /test to load index() directly. Now I have to type /test/index. How do I configure that.
Secondly index() and welcome() is almost same. Just that the request parameter is added to the output. I wrote index() because /welcome won't work if there is no parameter. I want txtname to be made optional or something as such so that welcome can be dropped.
I want something like /test to load index() directly. Now I have to type /test/index.
Just skip the extra mapping:
#RequestMapping
public String index() {
return "index";
}
I want txtname to be made optional or something as such so that welcome can be dropped.
Try this:
#RequestParam(value = "txtname", required = false)
Besides your welcome() method can be simplified:
#RequestMapping(value = "welcome")
public String welcome(#RequestParam("txtname") String name) {
return new ModelAndView("index", "msg", name);
}
Related
I'm adding a Path variableto receive value sent by URL. And this is my controller.
#Controller
#RequestMapping("/user")
public class UserController {
#RequestMapping(value = "/list/{field}", method = RequestMethod.GET)
public void userList(Model model, #PathVariable("field") String field) {
List<Users> userList = userDAO.searchAll();
System.out.println("Condition "+field);
model.addAttribute("userList", userList);
}
}
But I'm getting a 404 error.
And this is my folder structure for jsp.
Please help me to find out what is wrong here.
Thanks.
Edit : And also is there any chance that I can send empty path variable ex: http://localhost:8080/mvcquick/user/list and return to the same method?
system is looking for mvcquick/WEB-INF/jsp/user/list/n.jsp.
I dont see this file.
Please try this:
#Controller
#RequestMapping("/user")
public class UserController {
#RequestMapping(value = "/list/{field}", method = RequestMethod.GET)
public String userList(Model model, #PathVariable("field") String field) {
List<Users> userList = userDAO.searchAll();
System.out.println("Condition "+field);
model.addAttribute("userList", userList);
return "user/list"; // added line. Alos return type to String
}
Please try with below option.
#PathVariable(name="field",required=true)
Notice the error says n.jsp is not found. It means you're not returning the view name from the controller - I assume it's list.jsp. To change this, give a return value of String pointing to your list.jsp file. So try using
#RequestMapping(value = "/list/{field}", method = RequestMethod.GET)
public String userList(Model model, #PathVariable("field") String field) {
List<Users> userList = userDAO.searchAll();
System.out.println("Condition "+field);
model.addAttribute("userList", userList);
return "jsp/user/list.jsp"; // Path root must be from WEB-INF
}
I think it is looking for n.jsp inside your ".jsp" files. Please make sure that while sending id or attributes you are sending properly.
See this link for sending data(SO)
I am pretty new in Spring MVC and I have the following doubt.
In a controller, I have a method annotated in this way:
#Controller
#RequestMapping(value = "/users")
public class UserController {
#RequestMapping(params = "register")
public String createForm(Model model) {
model.addAttribute("user", new Customer());
return "user/register";
}
}
So this method handle HTTP Request toward the URL /users?register where register is a parameter (because the entire class handle request toward /users resource).
Is it the same thing if, instead using the params = "register" I use the following syntaxt:
#Controller
public class UserController {
#RequestMapping("/users/{register}")
public String createForm(Model model) {
model.addAttribute("user", new Customer());
return "user/register";
}
}
I have deleted the mapping at class level and I use #RequestMapping("/users/{register}").
Is it the same meaning of the first example?
NO, they are completely different constructs:
Code 1
#Controller
#RequestMapping(value = "/users")
public class UserController {
#RequestMapping(params = "register")
public String createForm(Model model) {
model.addAttribute("user", new Customer());
return "user/register";
}
}
In this case, createForm method will be called when a HTTP request is made at URL /users?register. Quoting from Spring Javadoc, it means this method will be called whatever the value of the register HTTP parameter; it just has to be present.
"myParam" style expressions are also supported, with such parameters having to be present in the request (allowed to have any value).
Code 2
#Controller
public class UserController {
#RequestMapping("/users/{register}")
public String createForm(Model model) {
model.addAttribute("user", new Customer());
return "user/register";
}
}
In this case, #RequestMapping is declaring register as a PathVariable. The method createForm will be called if a HTTP request is made at URL /users/something, whatever the something. And you can actually retrieve this something like this:
#RequestMapping("/users/{register}")
public String createForm(#PathVariable("register") String register, Model model) {
// here "register" will have value "something".
model.addAttribute("user", new Customer());
return "user/register";
}
I have approximately following controllers:
#RequestMapping(value = "foo", method = RequestMethod.GET)
public String foo(RedirectAttributes redirectAttributes, Model model) {
//logic
return bar(model);
}
#RequestMapping(value = "bar", method = RequestMethod.GET)
public String bar (Model model) {
model.addAttribute("value","magicValue")
return "myJsp";
}
my aim that after /foo invocation url was changed with bar
method bar shouldn't be broken.
Is it possible?
In method foo you can do:
return new ModelAndView("redirect:bar", modelName, model);
But this will add additional request to a server. It will also put the model values in the URL which is not always desirable
#RequestMapping(value = "/post/{postThreadId}", method = RequestMethod.GET)
#ResponseBody
public String paramTest(PostParams params) {
return params.toString();
}
Spring MVC Path Variable ("postThreadID") can be mapped to Command object field?
PostParams have setPostThreadId(int ...)
But, it looks not working.
I don't think this is possible.
Set it manually:
public String paramTest(PostParams params, #PathVariable int postThreadId) {
params.setPostThreadId(postThreadId);
....
}
I'm trying out Spring MVC 3.0 for the first time and like to make it RESTfull.
This is my controller:
#Controller
#RequestMapping(value = "/product")
#SessionAttributes("product")
public class ProductController {
#Autowired
private ProductService productService;
public void setProductValidator(ProductValidator productValidator, ProductService productService) {
this.productService = productService;
}
#RequestMapping(method = RequestMethod.GET)
public Product create() {
//model.addAttribute(new Product());
return new Product();
}
#RequestMapping(method = RequestMethod.POST)
public String create(#Valid Product product, BindingResult result) {
if (result.hasErrors()) {
return "product/create";
}
productService.add(product);
return "redirect:/product/show/" + product.getId();
}
#RequestMapping(value = "/show/{id}", method = RequestMethod.GET)
public Product show(#PathVariable int id) {
Product product = productService.getProductWithID(id);
if (product == null) {
//throw new ResourceNotFoundException(id);
}
return product;
}
#RequestMapping(method = RequestMethod.GET)
public List<Product> list()
{
return productService.getProducts();
}
}
I have 2 questions about this.
I'm a believer in Convention over Configuration and therefor my views are in jsp/product/ folder and are called create.jsp , list.jsp and show.jsp this works relatively well until I add the #PathVariable attribute. When I hit root/product/show/1 I get the following error:
../jsp/product/show/1.jsp" not found how do I tell this method to use the show.jsp view ?
If I don't add the RequestMapping on class level my show method will be mapped to root/show instead of root/owner/show how do I solve this ? I'd like to avoid using the class level RequestMapping.
add your 'product' to Model and return a String /product/show instead of Product. In your show.jsp, you can access the product object form pageContext
Check out the section in the manual about "Supported handler method arguments and return types".
Basically, when your #RequestMapping method returns just an object, then Spring uses this as a single model attribute, and, I'm guessing, attempts to use the request URL as the basis for the view name.
The easiest way to return the view and data you want from the same method is probably to just have the method return a ModelAndView, so you can explicitly specify the viewName and the model data.