How to write 2 controllers in spring MVC - spring-mvc

Is it possible that spring MVC contain 2 controllers like DispatherServet write more than one time
when we developing spring MVC applications.

Yes..!! It is Possible.
You have to set a #RequestMapping annotation at the class level the value of that annotation will be the prefix of all requests coming to that controller.
Example:
For 1st Controller :
#Controller
#RequestMapping("test")
public class TestController {
}
For 2nd Controller :
#Controller
#RequestMapping("demo")
public class DemoController {
}
If both the controller have the same/different methods you can access like this
<your server>/test/<RequestMappingName of Method>
<your server>/demo/<RequestMappingName of Method>

Related

Please help to explain a strange combination of Lombok's #AllArgsConstructor and spring's #RestController

I'm working on a spring project from our customer.
Below is the code for controller
#Log4j2
#RestController
#AllArgsConstructor
#RequestMapping(path = "/api/theapi")
#Api(value = "Description for the API")
public class TheAPIController {
private final ModelMapper modelMapper;
private final ObjectMapper objectMapper;
private final TheDemoService demoService;
...other code for controller
}
Below is the code for Service:
#Service
public class TheDemoService{ ... }
I was so surprise about 2 things:
Question 1: Why we need to use #AllArgsConstructor from project Lombok?
As per my understanding, Spring provide #RestController that Spring runtime container will initialize an Instance for our Controller. So that, having a constructor for our Controller seems like an invalid approach for using Spring Inversion of Control, is this correct?
Question 2. Because of using #AllArgsConstructor, somehow, the instance for demoService is to be injected
But again, I surprise because the code of Controller does not have #Autowired in combine with demoService.
In the actual code, there is no #Autowired for "private final TheDemoService demoService".
Hence, I could think of a possibility there, is that because of Lombok's #AllArgsConstructor would inject an instance of our TheDemoService via a constructor of
TheAPIController, I could not reason anything about this logic.
It's Invalid approach, no need for defining constructor for RestController
It's implicitly auto wiring the service
if a class, which is configured as a Spring bean, has only one constructor, the Autowired annotation can be omitted and Spring will use that constructor and inject all necessary dependencies.
To sum up #AllArgsConstructor can/should be removed

How do I inject an EJB in Spring MVC using annotations?

My dispatcher-servlet.xml has basically:
<context:component-scan base package="package.ejb" />
<mvc:annotation-driven />
In the #Controller class I have:
#Controller
public class ApplicationController {
#EJB(lookup="java:global/MyEarName/MyWebModuleName/BeanImplementation!package.ejb.morepackages.BeanImplementation")
private MyBeanInterface myBean;
This didn't work, it looks like Spring doesn't see the #EJB annotation and it gives an error at deploy time saying it doesn't find any Autowire candidate. So I added the following code:
#Autowired
#Qualifier("BeanImplementation")
public void setMyBean(MyBeanInterface myBean) {
this.myBean = myBean;
}
And on my bean implementation:
#Component("BeanImplementation")
#Stateless(mappedName = "BeanImplementation", name = "BeanImplementation")
#LocalBean
public class BeanImplementation implements MyBeanInterface {
It worked, but I need to use the lookup string of the EJB and I can't since Spring doesn't see #EJB. I was forced to revert to a non-Spring application to use #EJB(lookup="...").
So, to clarify the question: how do I inject an EJB in Spring MVC using annotations and using the EJB lookup string? Thanks.

How can I make every controller except the account controller in my WebAPI application require a user to be authenticated

I realize that I can decorate each controller with [Authorize].
However is there a way that I can do this globally so that it's the default and then have the Account controller set as anonymous only ?
Create a BaseController which all other controllers inherit from. Have this class then inherit from Controller, like so
SomeController : BaseController
Then in BaseController
BaseController : Controller
Add an authorize attribute to the base controller. All controllers inheriting from BaseController will now require authorization. Controllers which don't, wont. So, your account controller will only inherit from Controller, not BaseController as you don't want this authorized.
There are other advantages of having a base controller. You can override OnAction executed to log application usage for instance.
I would create a second base controller called BaseUnsecuredController which your account controller can inherit from which won't have an authorize attrubute. Then have an abstract base controller class which contains the implementations of common actions you wish to share between the base controllers, like logging and error handling.
Hope this helps.
Use a basecontroller, from which each controller inherits. Then set the [Authorize] attribute on the base controller.
Apply the filter globally like this.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Existing code
config.Filters.Add(new System.Web.Http.AuthorizeAttribute());
}
}
Then, apply [AllowAnonymous] on the AccountController or specific action methods.
[AllowAnonymous]
public class AccountController : WebApiController {}
You can add the AuthorizeAttribute globally by changing your FilterConfig to add it to all requests:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//Other filters
filters.Add(new AuthorizeAttribute());
}
After that you can add the [OverrideAuthorization] attribute to your controller.
If you have any AuthenticationFilter set globally it won't be reseted. If you want to reset both you also need to use the [OverrideAuthentication] attribute.

How should look configuration for multiple controllers in Spring MVC?

I have 2 logical items News and Cars. For each of them I need to have separate controllers. How I should configure my application.
If youre using annotation based configuration, you can simply create 2 Classes that are annotated with #Controller, like:
package com.example.controllers;
#Controller
public class NewsController {
#RequestMapping(value = "/news")
public String handleNewsCall() {
...
}
}
and
package com.example.controllers;
#Controller
public class CarsController {
#RequestMapping(value = "/cars")
public String handleCarsCall() {
...
}
}
Don't forget to add the following lines to your spring xml if you use annotation based configuration.
<context:component-scan base-package="com.example" />
<mvc:annotation-driven />

Can we create a new controller by extending another controller class in the Spring 3.0?

I have a requirement in the my application that I need to extend a controller class by extending the another controller class.
#Controller
#RequestMapping("/bulkTrade.htm")
public class TradeController extends ApplicationObjectSupport {
// methods and fields.
}
I need to create a new controller that should extends the TradeController. By simply using the extends keyword is not working. Is there another way to do this?
you also need add the #Controller and #RequestMapping annotation in your class.
The #Controller make your class's instance as a bean in application context

Resources