This question already has answers here:
How to test a spring mvc controller
(3 answers)
Closed 2 years ago.
New at testing and after doing much research not sure where to start based on examples I've seen.
The below controller is used in a spring boot client app that makes only GET requests to the REST API that returns a response as a list. Here the response is set as an attribute on the model and then returned as a String to be rendered in the view... if I got that 100% correct.
Question : can someone share an example on how I need to write a test for this controller? Do I need to just assert that the controller attribute is not null?
#Controller
#RequestMapping
public class WebController {
#GetMapping("/ListA")
public String viewListAController(Model model) {
return "ListA";
}
}
Well, the Model method parameter is never used and should most likely be removed since it isn't doing anything.
Then your unit test would most likely just be making sure that the viewListAController method returns the string 'ListA'.
And...
That's it...
Related
This question already has answers here:
How to do Multiple URL Mapping (aliases) in Spring Boot
(2 answers)
Closed 2 years ago.
I have 2 URIs
/books
/getallbooks
I want to call the same Controller method upon these URIs
Is it possible through Spring ? (Mapping same controller method with multiple URIs)
Or,
I create 2 different methods and map these URIs with them, and then call a common method
You can use more than one URI as follows :
#Controller
public class IndexController {
#RequestMapping({"","/","index","index.html"})
public String index() {
return "index";
}
Here I have passed a list of URIs to RequestMapping annotation.
I have a Spring controller and two methods that one prepare order data for user to edit, the other merage the latest order information change come back from the form (POST).
Now I want to make some procedure working like OptiMistic Locking without add version column in database. Because client take sometime to edit the order before session expires, I have to make the post method to be sure the order is still on the same status when client first open the order edit page
So I add a orderStatus attribute to carry the original status before order edit page is loaded and compare with the latest status from DB when save the order edit, like this:
#RequestMapping("/order")
#Controller
public class OrderController{
private String orderStatus;
#RequestMapping(value = "/{orderId}/edit", method = RequestMethod.GET)
public String prepareOrderEditForm(....){
....
// remember the original status
orderStatus = Order.getLatestStatus(orderId);
}
#RequestMapping(value = "/processEdit", method = RequestMethod.POST)
public String prepareOrderEditForm(....){
....
String currentOrderStatus = Order.getLatestStatus(orderId);
// compare most recent status with the original status
if(currentOrderStatus.equals(orderStatus) == false){
....//something is wrong, someone may be already edit the order
return "failed";
}else{
orderService.merge(order);
orderStatus = order.getNewStatus();
}
return "updated";
}
}
I understand this design is not as robust as Optimistic locking by database it may ignore the time when DML executed, also the orderStatus here should use getter/setter as java bean. So please exclude above concern but put the scope only within this controller
My question is, as Spring MVC is working in single thread like JSP Servlet, is there any problem while multiple user log on to the spring web application and edit the same order so orderStatus in this controller class somehow intertwined by multiple user(concurrency issue)?
Neither JSP nor Spring MVC are single threaded.
You should always try not to change instance/static variables in your controller methods.
Edit:
I should have mentioned that session thread safety will only work when you set Spring MVC abstract controller's synchronizeOnSession to true (by default it is false).
In your case you can:
1) set synchronizeOnSession to true in your spring application context where you define your controller.
2) Extend from Spring's AbstractController and override handleRequestInternal method.
3) in handleRequestInternal call request.getSession().setAttribute("orderStatus")
This question already has answers here:
Wildcard path for servlet?
(2 answers)
Closed 7 years ago.
I'm sorry, I come from a PHP web world.
I'm used to using a router in frameworks like Laravel to send to controllers and get parameters. I know how to get get and post parameters using servlets by routing things with the web.xml servlet-mapping and using * wildcards, but am unfamiliar with how to get those url wildcards with the HttpServletRequest variable passed through doGet or doPost.
Is there anything where I can grab the wildcards of those urls, such as, if the url was a username or a particular page I didn't want to hard code into the web.xml? I'm sure there is.
Id like to know things like what I can get in PHP's $_SERVER variables for reading data about the incoming request. Stuff like cookies are also needed. Can someone give me a quick pointer with Java Servlets?
EDIT:
Or maybe I should just stick the variables to where variables belong and not make "pages" out of fake variables. I'm also open to that idea as well.
My main problem is that I don't know how to get url wildcards in doGet or doPost after it's routed from web.xml, so I'd either like to know how or be told that's a stupid thing to do and not do it at all.
Check out Spring MVC. With Spring Controllers you get to do URL paths like
#RequestMapping("/fixed/{id}/{user}")
public String getSomeData(#PathVariable("id") String id, #PathVariable("user") String user) {
...
}
or even
#RequestMapping("/{id}/**")
public void doSomething(#PathVariable("id") int id, HttpServletRequest request) {
String remainingUrl = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
...
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Return only string message from Spring MVC 3 Controller
My spring controller has a endpoint where I want to only:
1. set the http response code
2. return a string back, don't need to render a .jsp view page or anything.
So will want to set the http status code to 200 OK or 500 etc.
And simply return a string like "OK".
How can I do this, or am I forced to render a .jsp view page?
Use the #ResponseBody annotation:
#RequestMapping(value="/sayHello", method=GET)
#ResponseBody
public String whatever() {
return "Hello";
}
See the #ResponseBody ref docs for further details.
You may be able to use the #ResponseStatus annotation to set the code rather than using the HttpServletResponse directly.
No, you are not forced to use view. If you use more recent version of Spring, you may use #ResponseBody annotation. See documentation for reference.
Example:
#Controller
#RequestMapping(value = "/someUrl", method = RequestMethod.GET, produces="text/plain")
#ResponseBody
public String returnSimpleMessage() {
return "OK";
}
You could also use HttpServletResponse as a parameter to set desired HTTP status.
This question already has answers here:
Can I find the URL for a spring mvc controller in the view layer?
(6 answers)
Closed 5 months ago.
I am using Spring MVC 3.0
I have a guestbook.jsp page where I want to create a link that points to GuestBookController's login method.
This is a simple task that most web frameworks handle this (e.g grails does it with g:link tag) but I couldn't find any documentation on this in the official SpringMVC docs.
So I am scratching my head - Is this functionality in some tag library? Does the framework expose it? Do I have to extend the framework to get this to work?
Note, I am not taking about hardcoding the url (which is an obvious but weak solution) but rather generating it based on controller and action name.
UPDATE:
Spring MVC doesn't provide this functionality. There is a JIRA ticket though. You can vote here https://jira.springsource.org/browse/SPR-5779
The short answer is no, you can't do this with Spring MVC currently.
It's a shame because you can do this in other frameworks including Grails (which uses Spring MVC under the hood).
See the discussion here which includes a link to a Spring feature request to add this (vote for it!)
Spring MVC uses the standard JSTL tags in JSPs so:
<c:url value="/guestBook.html" var="guestBookLink" />
Guest Book
In your controller:
#RequestMapping(value = "/guestBook")
public String handleGuestBook() { ... }
The Spring HATEOS library provides an API to generate links to MVC controller methods in various ways.
For example:
URI url = linkTo(methodOn(GuestBookController.class).login()).toUri();
Annotate your login method with #RequestMapping, like so:
#Controller
public class GuestBookController {
...
#RequestMapping(value="/mycontextroot/login", method = RequestMethod.GET)
public String login() {
...
}
...
}
Then, in your JSP, create a link something like this:
<c:url var="loginlink" value="/mycontextroot/login.html">
</c:url>
Login
This assumes that your dispatcher servlet is looking for *.html URLs.