Handling Session in spring MVC? - spring

i'm actually new to handling with spring mvc and in particular i have to implement session in spring mvc. Can anybody guide me out of how to handle with session in spring mvc ?

It is the example of controller method level session
#Controller
Class YourController{
#RequestMapping(value = "/yourrequest", method = RequestMethod.GET)
public String yourMethod(Model model,HttpSession session){
return null;
}
}
You can also put session valid to Controller Class.It is just done by adding SessionAttribute.This will be available in all methods in YourController Class
#Controller
#SessionAttribute("sessionName")
Class YourController{
#RequestMapping(value = "/yourrequest", method = RequestMethod.GET)
public String yourMethod(Model model){
model.addAttribute("sessionName",valueToBeAddedInSession);
return null;
}
}
Here the name of object added in Session should be same as it is added in modelAttribute e.g. sessionName.
The problem in case of session attribute is that we have to invalidate it manually
Thank you.

#Controller
#SessionAttributes({ "sessionVar1","sessionVar2" })
public class StartController {
public ModelAndView methodName(){
ModelAndView modelandView = new ModelAndView("view");
modelandView.addObject("sessionVar1", "sessionVal1");
modelandView.addObject("sessionVar2", "sessionVal2");
return modelandView;
}
}

Related

Request method 'POST' not supported at pass value

I use the interceptor in spring to make the user has login in,but when i transfer value from front end to back,the interceptor intercept the request,but it warns me that
WARN 8484 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved[org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
and send me to "/error",but i have add the controller into the excludePath like this
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(cookiesInterceptor).addPathPatterns("/**")
.excludePathPatterns("/adminapi/login")
.excludePathPatterns("/Login.html")
.excludePathPatterns("/index.html")
.excludePathPatterns("/static/**");
}
and the controller
#RequestMapping(value = "/adminapi")
public class AdminController {
#RequestMapping("/login")
public String .....
}
the action of form
<form th:action="#{/adminapi/login}" method="post">
so i do not know why the problem occur
In your AdminController,
replace #RequestMapping("/login")
with #PostMapping("/login")
This tells Spring Boot that you are using the POST method, otherwise by default GET is expected
I don't see the #Controller annotation in your AdminController
By the way, you should specify the method for your RequestMapping, you can use
#Controller
#RequestMapping(value = "/adminapi")
public class AdminController {
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String .....
}
or
#Controller
#RequestMapping(value = "/adminapi")
public class AdminController {
#PostMapping("/login")
public String .....
}
Check whether CSRF is enabled in spring security xml file . If so add the
So you should be able to submit the model attribute.
Seems duplicate check here Spring,Request method 'POST' not supported
Check whethr on the Controller receiving function for Spring MVC , you ahve this annotation. #ModelAttribute
For the requestmapping specify the method type .
#RequestMapping(value = "/login", method = RequestMethod.POST)

How to call Spring Boot RESt api using Spring MVC?

I have created REST api using Spring Boot.
So, that is the fragment of it:
#RestController
#RequestMapping("/api/employee")
public class EmployeeController {
#Autowired
private EmployeeService employeeService;
#GetMapping(value = "/all", produces = "application/json")
public ResponseEntity<List<Employee>> getAllEmployees() {
return ResponseEntity.ok(employeeService.findall());
}
Now, I would like to create more like MVC application part - simple view that shows all Employees using thymeleaf. (Just simple UI to use this app more convinient than sending curl requests)
#Controller
public class MainPageController {
#GetMapping("/employees")
public String showEmployees() {
// i don't know what to do here
return "employeesPage";
}
What is the appropriate way to do so? Is there a more simple way to do it?
Looking forward for your answers!
So you do exactly the same you did on your EmployeeController but instead of a JSON, you return a view.
Get your employes through EmployeeService and put them on a collection
Create your employee view under /templates folder (many tutorials of how to do it)
return this view with your collection of employees
Example:
#GetMapping(value = "employees")
public ModelAndView showEmployees() {
ModelAndView mav = new ModelAndView("employeesPage");
mav.addObject("employees", employeeService.findall());
return mav;
}
Check here for more detailed info:
https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html

calling a method by class level annotated with #RequestMapping that includes an autowired class

I am trying to call a method that is annotated with #RequestMapping(signIn) through a class level (from method: authentication) like so:
#RequestMapping(value = /authenticate, method = RequestMethod.POST)
public #ResponseBody Response authentication(HttpServletRequest request)
{
UserController user = new UserController();
return user.signIn(request, null);
}
and my controller looks like:
#Autowired
private UserManager userManager;
#RequestMapping(value = /signin, method = RequestMethod.POST)
public #ResponseBody Response signIn(HttpServletRequest request) {
JsonObject json = Misc.parseJson(request);
String lang = Misc.getLang(request);
user.setEmail(Misc.getEmail(json));
user.setPassword(Misc.getEncryptedPassword(json));
return ResponseUtils.success(userManager.auth(user, lang));
}
user manager is annotated with #component:
#Component
public class UserManager {
public User auth(User user, String lang) {
....
return user;
}
}
Problem is when I call the method "signIn" and just new-up a UserController instance through "/authenticate" mapping, the UserManager becomes NULL. So now I'm assuming that autowiring doesn't work when it's done this way.
Is there any other way to call the signIn method? I would hate to copy paste an already existing code to another class just to get this to work...
Autowiering only works in spring managed bean. If you create a class with new keyword, it is not a spring managed bean and autowiering would not work.
You can try to autowire the class which contains the method which is annotated or better put the code in a service class which can be used by both methods.
It's not problem with #Autowired .There are two type of Annotation
firstly method base annotation and field level annotation. You just used field level annotation.Check your import class with "org.springframework.beans.factory.annotation.Autowired" or it can be problem with initiation of "UserManager"
I don't know why you not moving logic into separate Service classs, but try this:
UserController.java
public UserController(UserManager userManager) {
this.userManager = userManager;
}
and then inside controller where authentication resource method is located:
#Autowired UserManager userManager;
#RequestMapping(value = /authenticate, method = RequestMethod.POST)
public #ResponseBody Response authentication(HttpServletRequest request) {
UserController user = new UserController(userManager);
return user.signIn(request);
}
So in the end I just separated the logic instead. Though one solution that I tried and I could have used was to just add another mapping to the signIn method instead of adding a new method in the other class since the logic was similar. Still I opted for a separate logic instead since there were a lot of unnecessary code in the signIn method for my purpose.

Spring boot #GetMapping for root not working

My Spring Boot controller is working just fine, except that I cannot create a mapping for the home directory. I have tried:
#Controller
public class MyController {
#GetMapping(value = {"/"})
public ModelAndView searchPage(Locale locale) {
ModelAndView model = new ModelAndView();
model.setViewName("pageTemplate");
return model;
}
}
#GetMapping(value = "/")
#GetMapping(value = "")
#GetMapping
#RequestMapping with all values above
I always get my 404 error page. If this is supposed to work, how can I debug why it is not?
Found it. I set in application.properties:
logging.level.org.springframework.web: DEBUG
which then displayed
o.s.w.s.mvc.ServletForwardingController : Forwarded to servlet [springVaadinServlet] in ServletForwardingController 'vaadinUiForwardingController'
It turns out that I have used #SpringUI without specifying a path

How do I configure a controller bean?

If we have a look at the Mkyong tutorial for a simple Hello World MVC application.
Now lets say instead of returning a straight hello, the controller instead calls a business logic layer to get what it wants.
#Controller
#RequestMapping("/welcome")
public class HelloController {
private BusinessLogic myBusinessLogic;
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
String text = myBusinessLogic.getMessage();
model.addAttribute("message", text);
return "hello";
}
}
I have two questions here.
How do I instantiate myBusinessLogic? In the exampke mkyong has given, there's no bean configuring the HelloController.
How do I configure the bean's scope?

Resources