Spring - store object in session without MVC - spring

I have a clean javascript + html + css frontend project, which sends a POST request to a backend endpoint.
Backend is a SpringBoot application.
I need to store a shopping cart into server's session and not into browser's session. Previously the project was a Spring MVC + Thymeleaf app, but I am rewriting it to JS + Spring.
In previous app version is was handled by #ModelAttribute and #SessionAttribute annotations, but simple "copy-paste" of all classes and configs does not solve the issue.
Example Controller:
#Controller
#SessionAttributes("basket")
public class LabelDesignController implements IPageModel {
#ModelAttribute("basket")
public Basket populateBasketForm() {
logger.info("[Model Attribute] populating [Basket] form.");
return new Basket();
}
#PostMapping(value = "/myEndPoint", produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public Object myEndPoint(#ModelAttribute("basket") Basket b, Item newItem) {
// some logic here
}
}
Item is a POJO class.
EDIT:
forgot to mention, the frontend are static HTML pages with vanilla JavaScript (even no jQuery). they are running on Nginx server. The backend is running on mvn spring-boot:run command.

Related

Two end points work without configuration - showing same view

I am using Spring Boot (2.5.6)'s Controller like this:
#Controller
public class WebController {
#GetMapping("/index")
public String indexPage () {
return "index";
}
}
And when I hit these two URLs:
http://localhost:8080/index
http://localhost:8080
Same Thymeleaf view index.html is served. To my understanding on hitting http://localhost:8080 I should get - Whitelabel Error Page.
In the past I have used something like this #RequestMapping(value = { "/", "/index" }, method = RequestMethod.GET) extensively. What I am missing/overlooking here?
Spring Boot, through auto-configuration, will add a WelcomePageHandlerMapping. The WelcomePageHandlerMapping will mimic the behavior of the welcome-page support in Servlet containers like Tomcat.
By default it will try to locate an index.html in either the static or template directory and, if needed, use the available templating framework to render this page.

Spring Model Attribute Binding Issue with Square Brackets

Spring MVC Version: 4.3.25
Spring Boot: 1.5.22 (Stuck to this due an old webshpere server version :( compatible only with JEE6)
Jackson Data-Bind: 2.10.3
My UI form submits POST request with parameters sent (inspected through browser tools).
Content-Type on Http Request is "application/x-www-form-urlencoded; charset=UTF-8"
changedValues[contacts[0]] 12312312313
changedValues[contacts[1]] 345354535
changedValues[contacts[2]] 35534534
name Sam
My Spring MVC controller goes like this.
Controller Code
#PostMapping("/saveMyPage")
public String saveMyPage(Model model,HttpServletRequest request, HttpServletResponse response,
HttpSession session,#ModelAttribute("myBean") MyBean oBean,BindingResult result){
Map <String,Object> uiChanged = oBean.changedValues;
... Other Code
}
Bean Code
public class MyBean implements Serializable{
private List<String> contacts;
private Map<String,Object> changedValues;
... Getters & Setters
}
On debugging, my Spring MVC controller I am hoping to get the list of only the changed contacts via the "changedValues" Hash Map. This is where the square brackets seem to break -
The key that Spring Binding maps now looks like
contacts[0 12312312313
contacts[1 345354535
contacts[2 35534534
name Sam
This breaks my code as the second square brackets were not understood by Spring Data Binding.
Still exploring if I can make Spring understand this binding of mine.

Lazy load Spring web page from Spring controller

I currently have a web page that displays some text and a set of images. In my Spring controller, I have two Java functions that retrieve this data however, the images take considerably longer to load and nothing appears on the web page until the images have been loaded. Is there a way to lazy load a web page from the Spring controller? Here is my controller
#Controller
public class Controller {
#RequestMapping(value = "/location/{city}", method = RequestMethod.GET)
public String getData(#PathVariable("city") String city, Model model) throws Exception {
model.addAttribute("cityName", city);
Dashboard.getTextData(city, true);
Dashboard.getImages(city);
return "location";
}
}
I think we can go with Asynchronous methods, Asynchronous(CompletableFuture interface) methods provide multi-thread from which we can load an image, while the main thread will do its other work other than the loading the image.
for asynchronous methods in spring, you can refer this asynchronous methods

Spring Boot REST controller not returning HTML string

I have a Spring Boot app that has one controller that serves mostly RESTful endpoints, but it has 1 endpoint that actually needs to return HTML.
#RestController
#RequestMapping("v1/data/accounts")
public class AccountResource {
// Half a dozen endpoints that are all pure data, RESTful APIs
#GetMapping("/confirmRegistration")
public void confirmRegistration(#RequestParam(value = "vt") String token) {
// Some logic goes here
System.out.println("This should work!");
return ResponseEntity.ok('<HTML><body>Hey you did a good job!.</body></HTML>')
}
}
When this runs, no errors/exceptions get thrown at all, and in fact I see the "This should work!" log message in my app logs. However from both a browser and a curl command, the HTTP response is empty. Any idea what I need to change in the ResponEntity builder to get the server returning a hand-crafted HTML string?
Add this to your #RequestMapping or #GetMapping
produces = MediaType.TEXT_HTML_VALUE
Spring defaults to application\json. If you need any other type, you need to specify it.

Spring JSF application flow

I have previously written Spring MVC web applications where there is a front controller and we have a request mapping in each of the methods and this method in turn invokes a service implementation finally returning a view to the UI. Now when I design JSF applications am not able to understand the flow as such -
This is what I currently have in my application:
The initial index.html redirects to the login page.
A backing bean for the login page which populates label values. Since it is an input form there is no other logic involved.
Once the user clicks on submit -> in the action method I have logic which will invoke the service(No.1) for authentication process and redirect the user to the home page by returning the name of the page
The home page displays various fields which are bound to a backing bean whose fields have to be populated by another web service call(No.2).
It is between the steps (3) and (4), I have a confusion. Previously in Spring I had an explicit mapping and I can "actually" control the logic in the front controller method. In JSF, I dont know whether the logic for No.2 web service call should be combined along with authentication call since I dont have a method to populate the beans.
It is as if I dont have the explicit control over the flow. I have read many articles trying to understand this but not am able to understand. Please provide me pointers and also some references which will actually explain this better.
Why can't you control the logic in JSF bean?Example usage with EJB
#ManagedBean
#RequestScoped
public class LoginBean {
#EJB
private AuthBean authBean;
#EJB
private UserSettings settingsBean;
private String name, password;
#PostConstruct
private void init() {
//do your initialization here
}
public String loginAction() {
User user = authBean.authenticate(user, password);
if(user != null) {
UserSetting settings = settingsBean.getSettings(user.getId());
return "home";
}
}
//setters and getters
}

Resources