I defined my session scoped proxy bean as below:
#Configuration
public class SessionScopeBeans {
#Bean
#SessionScope
public User user() {
return new User();
}
}
and then inject it into controller:
#Controller
public class MyController {
User user;
...
I tried all solutions I found:
// fail in Bean way but I don't know why
<span th:text="${#user.getName()}"></span>
// definitely fail because it doesn't relate to sessionAttribute
<span th:text="${session.user.name}"></span>
<span th:text="${#session.user.name}"></span>
I don't want to use sessionAttribute because I don't want to change controller method signiture. What can I do?
In question How to access spring session bean scope in thymeleaf , question owner said that he can access via bean way but I failed. Is it because of the way I define and inject my bean?
EDIT
I removed #Resource(name = "user") because I found that is not necessary for injecting User to my controller.
The error is:
2020-06-22 15:43:31.092 ERROR 17124 --- [nio-8083-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/home.html]")] with root cause
java.lang.IllegalStateException: Cannot create a session after the response has been committed
I found some discussion about this error but they all related to spring-security or spring-session. I didn't use these two modules!!
EDIT 2
After some code changes with no brain, suddenly I found <span th:text="${#user}"></span> can print out my class instance as string!! No matter how I inject my User bean: #Resource, #Autowired, or even no wiring annotation!! But, <span th:text="${#user.getName()}"></span> print nothing when I am sure it has value in it. A little step forward but block again...=(
EDIT 3
Finally, I found the stupid thing I did! Below is my controller and I assign user object to another one returned from DAO. So I have 2 user objects, one is controlled by Spring, wired into controller as a session scope bean which is all blank and another is created by DAO as a local variable in controller which contains information. Thymeleaf get the wired one...
#Autowired
private User user;
#PostMapping("/signin")
public String signin(#RequestParam String account, #RequestParam String password, Model model) {
user = dao.getUser(account);
return "redirect:/home";
}
#GetMapping("/home")
public String home(Model model) {
System.out.println(user.getTel());
return "home";
}
Related
Two beans qualidied different with the same name are getting me an exception.
Exception message:
***************************
APPLICATION FAILED TO START
***************************
Description:
The bean 'tipusFonsSql', defined in class path resource [net/gencat/clt/arxius/connector/config/SqlGiacTxtResourceLoader.class], could not be registered. A bean with that name has already been defined in class path resource [net/gencat/clt/arxius/connector/config/SqlGiacImgResourceLoader.class] and overriding is disabled.
It's telling me that class SqlGiacTxtResourceLoader and class SqlGiacImgResourceLoader are defining two beans with a same name.
Nevertheless, they are "#Qualified" different. I mean:
Into SqlGiacImgResourceLoader
#Bean
#GiacImg #TipusFonsQ
public String tipusFonsSql() {
//...
}
Into SqlGiacTxtResourceLoader
#Bean
#GiacTxt #TipusFonsQ
public String tipusFonsSql() {
//...
}
As you can see, one is "#aulified" with #GiacImg annotation and the other ony by #GiacTxt.
Any ideas?
You have to name them like this
#Bean(name = "GiacImg TipusFonsQ")
public String tipusFonsSql() {
//...
}
and
#Bean(name = "GiacTxt TipusFonsQ")
public String tipusFonsSql() {
//...
}
to avoid bean conflict
There is 2 way to resolve this issue ( haha there could be many but I know below 2 approach):------
1st Method
change the bean name:---
#Bean(name = "custome bean name")
2nd Method
write down the below key in the application.properties:--
spring.main.allow-bean-definition-overriding=true
NOTE:-in your case you can change method name also
I am new to spring state machines. I am trying to setup state machine for my transaction data and externalise it to mongo database. But i am getting error while creating "StateMachineRuntimePersister" bean.
Error says - Parameter 0 of method mongoPersist in com.pws.funder.config.PersistConfig required a bean of type 'org.springframework.statemachine.data.mongodb.MongoDbStateMachineRepository' that could not be found
#Configuration
public class PersistConfig {
#Bean(name="runtime")
public StateMachineRuntimePersister<WalletGatewayStates, WalletGatewayEvents, UUID> mongoPersist(
MongoDbStateMachineRepository mongoRepository) {
return new MongoDbPersistingStateMachineInterceptor<WalletGatewayStates,WalletGatewayEvents,UUID>(mongoRepository);
}
}
Any leads would be helpful.
Just create interface like this:
public interface StateMachineRepository extends MongoDbStateMachineRepository {
}
and pass it into mongoPersist method.
Spring automatically creates implementation from your repository interface and put this bean in the context.
I am using Grails : 2.3.5
and Spring Security Core plugin : 1.2.7.3
In Grails Spring Security RequestMap is a separate table but in my application I want to use the requestMap concept with the existing table.
I have a RolePermissionMap table is there and I want to use this table for the RequestMap.
class Role{
Long id
String name
String description
}
class Permission{
Long id
String name
String description
String requestUrl
}
class RolePermissionMap {
Long id
Role role
Permission permission
}
Now I am overriding the loadRequestmaps() method by extending the RequestmapFilterInvocationDefinition class like below
class RolePermissionMapFilterInvocation extends RequestmapFilterInvocationDefinition {
#Override
protected Map<String, String> loadRequestmaps() {
Map<String, String> data = new HashMap<String, String>();
for (Object requestmap : ReflectionUtils.loadAllRequestmaps()) {
// Original code
//String urlPattern = ReflectionUtils.getRequestmapUrl(requestmap);
//String configAttribute = ReflectionUtils.getRequestmapConfigAttribute(requestmap);
//data.put(urlPattern, configAttribute);
// modified code
Permission permission = ReflectionUtils.getRequestmapUrl(requestmap);
Role role = ReflectionUtils.getRequestmapConfigAttribute(requestmap);
data.put(permission.getRequestUrl(), role.getName());
}
return data;
}
}
Then I will add this bean in resources.groovy
beans = {
objectDefinitionSource(RolePermissionMapFilterInvocation)
}
I am also trying to override the ReflectionUtils class also for getting the return types of getRequestmapUrl(requestmap) and getRequestmapConfigAttribute() methods also as required
When I run with this approach am getting exception below
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'objectDefinitionSource': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: url matcher is required
for resolving the url matcher I added a bean in resources.groovy but it failed
Do I need to create a bean with urlMaper or need to mention ReflectionUtils class any where ?
Please show me a way.. Thanks in Advance
The plugin expects the url field in your request map class to be a String, in order to use a different type you'd have to subclass RequestMapFilterInvocationDefinition to extract the URL patterns correctly, and install your custom class as the bean named objectDefinitionSource in your app's resources.groovy to replace the default bean definition supplied by SpringSecurityCoreGrailsPlugin.groovy in its doWithSpring.
In Spring MVC we can use
#SessionAttributes("variable")
and
model.addAttribute("variable", new Object());
Such that this variable once set is availabel to user session.
Now i want this variable to be set at application scope such that if user 1 sets this attribute it will be available to all my users user 2, user 3, user 4 etc.
and this variable will be used on my jsp page.
Please suggest.
If you mean web application scope, then you need to set it in the ServletContext attributes. Because this isn't a common thing to do in web applications from a user perspective, Spring doesn't offer a shortcut. Instead, just retrieve the ServletContext either by injecting it into your #Controller or providing it as a parameter to a handler method and add the attribute
ServletContext ctx = ...;
ctx.setAttribute("name", new Object());
Note that there is a single ServletContext per web application. The ServletContext does not guarantee any atomicity, ie. it is not synchronized. You need to do that synchronization yourself, if required by the application.
You can define one simple Pojo as Spring Bean Service to do.
#Service
public class MyVariable{
private Object myVar;
public Object getMyVar() {
return myVar;
}
public void setMyVar(Object myVar) {
this.myVar = myVar;
}
}
Then, you can #Autowired this service in your #Controller and get it to anything.
I have an existing application in Sping 3.0 that uses ControllerClassNameHandlerMapping to map Controller and methods such as:
StartController.class is mapped to http://127.0.0.1/app/start/*
then
StartController.class has a method called init() that is mapped to http://127.0.0.1/app/start/init.html
Here is my configuration:
#Bean
public ControllerClassNameHandlerMapping classNameControllerMappings() {
return new ControllerClassNameHandlerMapping() {{
setCaseSensitive(true);
setDefaultHandler(new UrlFilenameViewController());
setInterceptors(new Object[]
{callProgressionInterceptorHandler(),
callSessionInterceptorHandler(),
localeChangeInterceptor()});
}};
}
Most of my controllers have 5-15 Request Mapped methods in each controller.
But when I upgrade to Spring 3.1+, the Request Mapping becomes ambiguous for each controller and is not mapped correctly.
I have read that one solution is to explicitely add the mthod name:
#RequestMapping(method = RequestMethod.GET)
Will now be:
#RequestMapping(method = RequestMethod.GET, value = "init")
I really do not want to manually add #RequestMapping value to 100+ methods if I dont have to.
Can anyone help with a better solution?
Here is the error I keep getting:
47672 [btpool0-1] ERROR org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'addressConfirmationController' bean method
public void com.comcast.ivr.d2.web.controllers.AddressConfirmationController.houseNumber_rc(org.springframework.ui.ModelMap)
to {[],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'addressConfirmationController' bean method
I also added setOrder(1); to ControllerClassNameHandlerMapping and still get this error.
UPDATE:
I saw on http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html the following excerpt:
Prior to Spring 3.1, type and method-level request mappings were examined in two separate stages -- a controller was selected first by the DefaultAnnotationHandlerMapping and the actual method to invoke was narrowed down second by the AnnotationMethodHandlerAdapter.
With the new support classes in Spring 3.1, the RequestMappingHandlerMapping is the only place where a decision is made about which method should process the request. Think of controller methods as a collection of unique endpoints with mappings for each method derived from type and method-level #RequestMapping information.
Does this mean I cannot keep the same #RequestMapping without adding mapping details in the #RequestMapping as I did <3.1 ?
I have hundreds of methods that would need to be modified in order for this to happen... :-(