Search Results

Search found 14784 results on 592 pages for 'spring security'.

Page 44/592 | < Previous Page | 40 41 42 43 44 45 46 47 48 49 50 51  | Next Page >

  • Application design in Spring MVC

    - by Ravi
    Hello All, I'm new to Spring MVC and trying out a simple project.It will contain a simple adding, viewing, updating and deleting user work flows. It will have login page and once authenticated the user will be taken to a welcome screen which will have links to add, view, update and delete users. Clicking on any of the links will take to individual pages where the user can do the specific tasks. What I'm doing here is, I'm using a MultiActionController to group together all requests related to User work flow. So the request from "Add User" link will handled by the addUser method in the UserController which will redirect the user to the "Add User" page, and the user can then fill in the details and save the new user. Now here is where I'm getting confused. Where should I put the save process of the new user, should I put that in new mehtod inside UserController, or use the same "addUser" method. What is the best way to handle this kind of scenario. I hope I was able to clear my question.

    Read the article

  • executing stored procedure from Spring-Hibernate using Annotations

    - by HanuAthena
    I'm trying to execute a simple stored procedure with Spring/Hibernate using Annotations. Here are my code snippets: DAO class: public class UserDAO extends HibernateDaoSupport { public List selectUsers(final String eid){ return (List) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query q = session.getNamedQuery("SP_APPL_USER"); System.out.println(q); q.setString("eid", eid); return q.list(); } }); } } my entity class: @Entity @Table(name = "APPL_USER") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorFormula(value = "SUBSCRIBER_IND") @DiscriminatorValue("N") @NamedQuery(name = "req.all", query = "select n from Requestor n") @org.hibernate.annotations.NamedNativeQuery(name = "SP_APPL_USER", query = "call SP_APPL_USER(?, :eid)", callable = true, readOnly = true, resultClass = Requestor.class) public class Requestor { @Id @Column(name = "EMPL_ID") public String getEmpid() { return empid; } public void setEmpid(String empid) { this.empid = empid; } @Column(name = "EMPL_FRST_NM") public String getFirstname() { return firstname; } ... } public class Test { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "applicationContext.xml"); APFUser user = (APFUser)ctx.getBean("apfUser"); List selectUsers = user.getUserDAO().selectUsers("EMP456"); System.out.println(selectUsers); } } and the stored procedure: create or replace PROCEDURE SP_APPL_USER (p_cursor out sys_refcursor, eid in varchar2) as empId varchar2(8); fname varchar2(50); lname varchar2(50); begin empId := null; fname := null; lname := null; open p_cursor for select l.EMPL_ID, l.EMPL_FRST_NM, l.EMPL_LST_NM into empId, fname, lname from APPL_USER l where l.EMPL_ID = eid; end; If i enter invalid EID, its returning empty list which is OK. But when record is there, following exception is thrown: Exception in thread "main" org.springframework.jdbc.BadSqlGrammarException: Hibernate operation: could not execute query; bad SQL grammar [call SP_APPL_USER(?, ?)]; nested exception is java.sql.SQLException: Invalid column name Do I need to modify the entity(Requestor.class) ? How will the REFCURSOR be converted to the List? The stored procedure is expected to return more than one record.

    Read the article

  • Sending multi-part email from Google App Engine using Spring's JavaMailSender fails

    - by hleinone
    It works without the multi-part (modified from the example in Spring documentation): final MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(final MimeMessage mimeMessage) throws Exception { final MimeMessageHelper message = new MimeMessageHelper( mimeMessage); message.setTo(toAddress); message.setFrom(fromAddress); message.setSubject(subject); final String htmlText = FreeMarkerTemplateUtils .processTemplateIntoString(configuration .getTemplate(htmlTemplate), model); message.setText(htmlText, true); } }; mailSender.send(preparator); But once I change it to: final MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(final MimeMessage mimeMessage) throws Exception { final MimeMessageHelper message = new MimeMessageHelper( mimeMessage, true); ... message.setText(plainText, htmlText); } }; mailSender.send(preparator); I get: Failed message 1: javax.mail.MessagingException: Converting attachment data failed at com.google.appengine.api.mail.stdimpl.GMTransport.sendMessage(GMTransport.java:231) at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:402) ... This is especially difficult since the GMTransport is proprietary Google class and no sources are available, which would make it a bit easier to debug. Anyone have any ideas what to try next? My bean config, for helping you to help me: <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl" p:username="${mail.username}" p:password="${mail.password}" p:protocol="gm" />

    Read the article

  • Spring - Transaction Readonly

    - by AAK
    Hello Gurus! Just wanted your expert opinions on declarative transaction management for Spring. Here is my setup - A. DAO Layer is Plain old JDBC using jdbcTemplete (No hibernate etc) B. Service Layer is POJO with declarative trasnactions as follows - save*, readonly=false, rollback for Throwable Things work fine with above setup. However when I say get*, readonly=true I see errors in my log file saying - Database connection cannot be marked as readonly. This happens for all get* methods in Service Layer. Now my questions - A. Do I have to say get* as readonly? All my get* methods are pure read DB operations. I do not wish to run them in any transaction context. How serious is the above error? B. When I remove the get* confiiguration, I do not see the errors, morever all my simple get* operations are performed without transactions. Is this the way to go? C. Why would anyone want to have transactional methods where readonly = true? Is there any practical significance of this configuration? Thank you! As always your resposes are much appreciated!

    Read the article

  • Problem with Spring security's logout

    - by uther-lightbringer
    Hello, I've got a problem logging out in Spring framework. First when I want j_spring_security_logout to handle it for me i get 404 j_spring_security_logout not found: sample-security.xml: <http> <intercept-url pattern="/messageList.htm*" access="ROLE_USER,ROLE_GUEST" /> <intercept-url pattern="/messagePost.htm*" access="ROLE_USER" /> <intercept-url pattern="/messageDelete.htm*" access="ROLE_ADMIN" /> <form-login login-page="/login.jsp" default-target-url="/messageList.htm" authentication-failure-url="/login.jsp?error=true" /> <logout/> </http> Sample url link to logout in JSP page: <a href="<c:url value="/j_spring_security_logout" />">Logout</a> When i try to use a custom JSP page i.e. I use login form for this purpose then I get better result at least it gets to login page, but another problem is that you dont't get logged off as you can diretcly type url that should be guarded buy you get past it anyway. Slightly modified from previous listings: <http> <intercept-url pattern="/messageList.htm*" access="ROLE_USER,ROLE_GUEST" /> <intercept-url pattern="/messagePost.htm*" access="ROLE_USER" /> <intercept-url pattern="/messageDelete.htm*" access="ROLE_ADMIN" /> <form-login login-page="/login.jsp" default-target-url="/messageList.htm" authentication-failure-url="/login.jsp?error=true" /> <logout logout-success-url="/login.jsp" /> </http> <a href="<c:url value="/login.jsp" />">Logout</a> Thank you for help

    Read the article

  • Spring MVC- several parts/views from a controller

    - by leeeroy
    i'm looking into using Spring MVC - how would I structure the fact that a page can be composed of several different views Consider a controller that's basically: public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Post> posts = repository.getNewPosts(); return new ModelAndView("posts", "posts", posts); } However, I decide that on every page, I'd also want a side "pane" that shows data based on some logic. That "pane" would just be a .jsp that gets included from the above "posts" view, and I could change my controller to: public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Post> posts = repository.getNewPosts(); List<Items> items= repository.getItems(); return new ModelAndView("model", "model", new MyCommonViewModel(posts,items)); } But then I'd have to change every controller to also do List<Items> items= repository.getItems(); , and change everything again the next time I come up with something new. This seems messy. How do I structure this ? `

    Read the article

  • Setting spring bean property value using ref-bean

    - by Apache Fan
    Hi, I am trying to set a property value using spring. <bean id="velocityPropsBean" class="com.test.CustomProperties" abstract="false" singleton="true" lazy-init="false" autowire="default" dependency-check="default"> <property name="properties"> <props> <prop key="resource.loader">file</prop> <prop key="file.resource.loader.cache">true</prop> <prop key="file.resource.loader.class">org.apache.velocity.runtime.resource.loader.FileResourceLoader</prop> <prop key="file.resource.loader.path">NEED TO INSERT VALUE AT STARTUP</prop> </props> </property> </bean> <bean id="velocityResourcePath" class="java.lang.String" factory-bean="velocityHelper" factory-method="getLoaderPath"/> Now what i need to do is insert the result from getLoaderPath into file.resource.loader.path. The value of getLoaderPath changes so it has to be loaded at server startup. Any thoughts how i can inset the velocityResourcePath value to the property?

    Read the article

  • spring - constructor injection and overriding parent definition of nested bean

    - by mdma
    I've read the Spring 3 reference on inheriting bean definitions, but I'm confused about what is possible and not possible. For example, a bean that takes a collaborator bean, configured with the value 12 <bean name="beanService12" class="SomeSevice"> <constructor-arg index="0"> <bean name="beanBaseNested" class="SomeCollaborator"> <constructor-arg index="0" value="12"/> </bean> </constructor-arg> </bean> I'd then like to be able to create similar beans, with slightly different configured collaborators. Can I do something like <bean name="beanService13" parent="beanService12"> <constructor-arg index="0"> <bean> <constructor-arg index="0" value="13"/> </bean> </constructor> </bean> I'm not sure this is possible and, if it were, it feels a bit clunky. Is there a nicer way to override small parts of a large nested bean definition? It seems the child bean has to know quite a lot about the parent, e.g. constructor index. I'd prefer not to change the structure - the parent beans use collaborators to perform their function, but I can add properties and use property injection if that helps. This is a repeated pattern, would creating a custom schema help? Thanks for any advice!

    Read the article

  • NUnit integration programmatically with spring

    - by harkon
    Hi! I have a component based architecture framework designed and I use NUnit for isolated testing - okay so far. Now I want to enable integration tests. Therefore the tests use real implementations of the existing components. Each element of the component has a life cycle (init, start and stop) and I created a NUnit component. In the start section the Console runner of the NUnit will be executed. Okay - now if I have a test fixture class in my dlls in the execution path the runner exectues them - fine! But: And this is crucial! Each to be tested implementation exists so far in the process and I want to use this instances for testing. If I use NUnit runner in the current way each instance will be created twice - and above all: I have a spring container and a implementation registry. Via this registry I can get access to all instances in the processes. But how do I give the test fixture access to the existing registry? Good: I can start the component architecture framework in the startup of the nunit runner - but this is not what I want. My guide is the apache Cactus framework (with JUnit and tomcat, JBoss etc.) Can someone help? Thanks a lot! Check: http://cone.codeplex.com

    Read the article

  • Spring aop multiple pointcuts & advice but only the last one is working

    - by Jarle Hansen
    I have created two Spring AOP pointcuts that are completely separate and will be woven in for different parts of the system. The pointcuts are used in two different around advices, these around-advices will point to the same Java method. How the xml-file looks: <aop:config> <aop:pointcut expression="execution(......)" id="pointcutOne" /> <aop:pointcut expression="execution(.....)" id="pointcurTwo" /> <aop:aspect id="..." ref="springBean"> <aop:around pointcut-ref="pointcutOne" method="commonMethod" /> <aop:aroung pointcut-ref="pointcutTwo" method="commonMethod" /> </aop:aspect> </aop:config> The problem is that only the last pointcut works (if I change the order "pointcutOne" works because it is last). I have gotten it to work by creating one big pointcut, but I would like to have them separate. Any suggestions to why only one of the pointcuts works at a time?

    Read the article

  • Update database settings in properties file in Spring

    - by mvg
    Hi all, I am trying to create a Database Manager page which shows the database details on page load and updates the database settings when the user press submit I followed this tutorial and set the database settings in properties file. I managed to update the database settings in properties file programmatically. When I retrieved the database settings using the following code DriverManagerDataSource databaseSource = (DriverManagerDataSource)context.getBean("dataSource"); databaseSource.getUsername(); I managed to get the old value and unable to get the new value This is the mapping in applicationContext.xml file <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>classpath:/bundle/database.properties</value> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> I checked the properties file and found it to be updated with the latest input. What am I missing? Thanks in advance P.S I am using JSF1.2 with Spring 3 Update Just making my requirement simple. I am creating a setparate dbsettings page, so that when user wishes to connect to different database he/she can just enter the details in dbsettings page and connect

    Read the article

  • PropertyPlaceholderConfigurer vs Filters -- Spring Beans

    - by John
    Hi there. I've got a question regarding the difference between PropertyPlaceholderConfigurer (org.springframework.beans.factory.config.PropertyPlaceholderConfigurer) and normal filters defined in my pom.xml. I've been looking at examples, and it seems that even though filters are defined and marked to be active by default in the pom.xml they still make use of PropertyPlaceholderConfigurer in Spring's applicationContext.xml. This means that the pom.xml has a reference to a filter-LOCAL.properties while applicationContext.xml has a reference to application.properties and they both contain the same settings. Why is that? Is that how it is supposed to be done? I'm able to run the goal mvn jetty:run without the application.properties present, but if I add settings to the application.properties that differ from the filter-LOCAL.properties they don't seem to override. Here's an example of what I mean: pom.xml <profiles <profile <idLOCAL <activation <activeByDefaulttrue </activation <properties <envLOCAL </properties </profile </profiles applicationContext.xml <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" <property name="locations" <list <valueclasspath:application.properties </list </property <property name="ignoreResourceNotFound" value="true"/ </bean <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" <property name="driverClassName" value="${jdbc.driver}"/ <property name="url" value="${jdbc.url}"/ <property name="username" value="${jdbc.username}"/ <property name="password" value="${jdbc.password}"/ </bean an example of the content of application.properties and filters-LOCAL.properties jdbc.driver=org.postgresql.Driver jdbc.url=jdbc:postgresql://localhost/shoutbox_dev jdbc.username=tester jdbc.password=tester Can I remove the propertyConfigurer from the applicationContext, create a PROD filter and disregard the application.properties file, or will that give me issues when deploying to the production server?

    Read the article

  • Spring + iBatis + Hessian caching

    - by ILya
    Hi. I have a Hessian service on Spring + iBatis working on Tomcat. I'm wondering how to cache results... I've made the following config in my sqlmap file: <sqlMap namespace="Account"> <cacheModel id="accountCache" type="MEMORY" readOnly="true" serialize="false"> <flushInterval hours="24"/> <flushOnExecute statement="Account.addAccount"/> <flushOnExecute statement="Account.deleteAccount"/> <property name="reference-type" value="STRONG" /> </cacheModel> <typeAlias alias="Account" type="domain.Account" /> <select id="getAccounts" resultClass="Account" cacheModel="accountCache"> fix all; select id, name, pin from accounts; </select> <select id="getAccount" parameterClass="Long" resultClass="Account" cacheModel="accountCache"> fix all; select id, name, pin from accounts where id=#id#; </select> <insert id="addAccount" parameterClass="Account"> fix all; insert into accounts (id, name, pin) values (#id#, #name#, #pin#); </insert> <delete id="deleteAccount" parameterClass="Long"> fix all; delete from accounts where id = #id#; </delete> </sqlMap> Then i've done some tests... I have a hessian client application. I'm calling getAccounts several times and after each call it's a query to DBMS. How to make my service to query DBMS only a first time (after server restart) getAccounts called and for the following calls to use a cache?

    Read the article

  • Spring MVC 3.0 Rest problem

    - by Gidogeek
    Hi Guys, I'm trying out Spring MVC 3.0 for the first time and like to make it RESTfull. This is my controller: @Controller @RequestMapping(value = "/product") @SessionAttributes("product") public class ProductController { @Autowired private ProductService productService; public void setProductValidator(ProductValidator productValidator, ProductService productService) { this.productService = productService; } @RequestMapping(method = RequestMethod.GET) public Product create() { //model.addAttribute(new Product()); return new Product(); } @RequestMapping(method = RequestMethod.POST) public String create(@Valid Product product, BindingResult result) { if (result.hasErrors()) { return "product/create"; } productService.add(product); return "redirect:/product/show/" + product.getId(); } @RequestMapping(value = "/show/{id}", method = RequestMethod.GET) public Product show(@PathVariable int id) { Product product = productService.getProductWithID(id); if (product == null) { //throw new ResourceNotFoundException(id); } return product; } @RequestMapping(method = RequestMethod.GET) public List<Product> list() { return productService.getProducts(); } } I have 2 questions about this. I'm a believer in Convention over Configuration and therefor my views are in jsp/product/ folder and are called create.jsp , list.jsp and show.jsp this works relatively well until I add the @PathVariable attribute. When I hit root/product/show/1 I get the following error: ../jsp/product/show/1.jsp" not found how do I tell this method to use the show.jsp view ? If I don't add the RequestMapping on class level my show method will be mapped to root/show instead of root/owner/show how do I solve this ? I'd like to avoid using the class level RequestMapping.

    Read the article

  • Strange problems with the Spring RestTemplate in Android application

    - by HarryCater
    I begin to use RESTful api of the Spring Framework in my android client application. But I have encountered with problems when I tried to execute HTTP request via postForObject/postForEntity methods. Here is my code: public String _URL = "https://noticemed.com/app/mobile/login"; public void BeginAuthorization(View view) { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> _entity = new HttpEntity<String>(requestHeaders); RestTemplate templ = new RestTemplate(); templ.setRequestFactory(new HttpComponentsClientHttpRequestFactory()); templ.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); ResponseEntity<String> _response = templ.postForEntity(_URL,_entity,String.class); //HERE APP CRASHES String _body = _response.getBody(); And here is a stack trace in logcat after app crashing. As you see there is no definite error message. So the question what am I doing wrong? How to fix this? May there is other way to do it?I really need a help. Thanks in advance!

    Read the article

  • DWR and Spring Security - User is deauthenticated in few seconds

    - by Vojtech
    I am trying to implement user authentication via DWR as follows: public class PublicRemote { @Autowired @Qualifier("authenticationManager") private AuthenticationManager authenticationManager; public Map<String, Object> userLogin(String username, String password, boolean stay) { Map<String, Object> map = new HashMap<>(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); try { Authentication authentication = authenticationManager.authenticate(authRequest); SecurityContextHolder.getContext().setAuthentication(authentication); map.put("success", "true"); } catch (Exception e) { map.put("success", "false"); } return map; } public Map<String, Object> getUserState() { Map<String, Object> map = new HashMap<>(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); boolean authenticated = authentication != null && authentication.isAuthenticated(); map.put("authenticated", authenticated); if (authenticated) { map.put("authorities", authentication.getAuthorities()); } return map; } } The authentication works correctly and by calling getUserState() I can see that the user is successfully logged in. The problem is that this state will stay only for few seconds. In probably 5 seconds, the getAuthentication() starts returning null. Is there some problem with session in DWR or is it some misconfiguration of Spring Security?

    Read the article

  • form:select items problem in spring mvc portlet

    - by dhaval
    I have a set of drop-down control which I want to render with my custom tag library. The following is the code of the tag lib: <spring:bind path="${path}"> <c:choose> <c:when test="${readOnly}"> <span class="readOnly">${status.value}</span> </c:when> <c:otherwise> <form:select path="${path }" itemLabel="${label }" itemValue="${value }" items="${itemList}"> </form:select> </c:otherwise> </c:choose> And this is the code I have written in the JSP file: <tag:conditionalListControl path="model.selectedCountry" readOnly="false" label="name" value="id" listItems="model.countryList" className="simple" /> Upon execution the paring returns the following error: [jsp:165] javax.servlet.jsp.JspException: Type [java.lang.String] is not valid for option items But if i change the items="${itemList}" to items="${model.countryList}" which is the list I want to display, it works fine without any problem and also bind to required variables on form submit. But i don't want to hard code any variables in the tag lib. Any suggestions???

    Read the article

  • return ArrayList from spring controller for ajax call and render in second dropdown

    - by user1708125
    I've a spring bean with 3 Maps all of which are to be populated incrementally. First map is an item category list, second map is a product list and third map is a hobby for item type list All the maps are mapped to and on the JSP. When the page is loaded only the first map is populated on the onchange event of first map, I need to populate the second map in the bean and similarly on the onchange event of second map, I need to populate the third map in the bean. Is there a way to do this using Ajax?? I need some code samples to how to render JSON response in second and third dropdown. Clarification: @Donal: I have a simple JSP page with 3 dropdowns corresponding to 3 maps stored in my commandBean. So when the page loads for the first time only the first map and hence the first dropdown is populated. Now whenever the user selects anything out of the first dropdown, I need to send the same commandbean back with the values of the first dropdown and get the values for the second map and hence the second dropdown and so forth for the 3rd dropdown as well. For each dropdown I 've got 3 maps and 3 variables for storing the selected values. Now I want to understand if this is possible using Ajax. I hope this clarifies whatever you need to know. Thanx

    Read the article

  • Server side aggregation using Spring MVC Controllers

    - by Venu
    Hi! We have a web site with multiple pages each with lot of AJAX calls. All the Ajax calls go to a data proxy layer written in Spring 3 MVC application. In order to reduce the load on the server we are planning to aggregate calls on the client and send to the proxy layer. For ex: we have two calls /controller1/action1 and /controller2/action2 in different controllers. I want to write an aggregate controller and call it from the client instead of making two calls to the individual controllers. Something like /aggregatecontroller/aggregate (and we will post the information regarding which calls are being aggregated and required parameters). Is there any way we can call another controller/action from a controller/action and get output? The flow will be something like this: a. Call /aggregatecontroller/aggregate with info regd call1 and call2 b. aggregate action understands that it needs to aggregate call1 and call2 c. it calls /controller1/action1 and gets the response d. it calls /controller2/action2 and gets the response e. it merges both in a json response and sends it back to browser. Please let me know if you have any suggestion regd how to do this or if you think there is a better approach to do the server side aggregation. Thanks for your time.

    Read the article

  • Is private method in spring service implement class thread safe

    - by Roger Ray
    I got a service in an project using Spring framework. public class MyServiceImpl implements IMyService { public MyObject foo(SomeObject obj) { MyObject myobj = this.mapToMyObject(obj); myobj.setLastUpdatedDate(new Date()); return myobj; } private MyObject mapToMyObject(SomeObject obj){ MyObject myojb = new MyObject(); ConvertUtils.register(new MyNullConvertor(), String.class); ConvertUtils.register(new StringConvertorForDateType(), Date.class); BeanUtils.copyProperties(myojb , obj); ConvertUtils.deregister(Date.class); return myojb; } } Then I got a class to call foo() in multi-thread; There goes the problem. In some of the threads, I got error when calling BeanUtils.copyProperties(myojb , obj); saying Cannot invoke com.my.MyObject.setStartDate - java.lang.ClassCastException@2da93171 obviously, this is caused by ConvertUtils.deregister(Date.class) which is supposed to be called after BeanUtils.copyProperties(myojb , obj);. It looks like one of the threads deregistered the Date class out while another thread was just about to call BeanUtils.copyProperties(myojb , obj);. So My question is how do I make the private method mapToMyObject() thread safe? Or simply make the BeanUtils thread safe when it's used in a private method. And will the problem still be there if I keep the code this way but instead I call this foo() method in sevlet? If many sevlets call at the same time, would this be a multi-thread case as well?

    Read the article

  • Hibernate Session flush behaviour [ and Spring @Transactional ]

    - by EugeneP
    I use Spring and Hibernate in a web-app, SessionFactory is injected into a DAO bean, and then this DAO is used in a Servlet through webservicecontext. DAO methods are transactional, inside one of the methods I use ... getCurrentSession().save(myObject); One servlet calls this method with an object passed. The update seems to not be flushed at once, it takes about 5 seconds to see the changes in the database. The servlet's method in which that DAO's update method is called, takes a fraction of second to complete. After the @Transactional method of DAO is completed, flushing may NOT happen ? It does not seem to be a rule [ I already see it ]. Then the question is this: what to do to force the session to flush after every DAO method? It may not be a good thing to do, but talking about a Service layer, some methods must end with immediate flush, and Hibernate Session behavior is not predictable. So what to do to guarantee that my @Transactional method persists all the changes after the last line of that method code? getCurrentSession().flush() is the only solution? p.s. I read somewhere that @Transactional IS ASSOCIATED with a DB Transaction. Method returns, transaction must be committed. I do not see this happens.

    Read the article

  • Java Generics Issue (w/ Spring)

    - by drewzilla
    I think I may be a victim of type erasure but thought I'd check with others here first. I have the requirement to do something like this: public interface FooFactory { public <T extends Bar> Foo<T> createFoo( Class<T> clazz ); } It is perfectly valid to write this code. However, I'm trying to implement this functionality using a Spring BeanFactory and I can't do it. What I'd like to do is this... public class FooFactoryImpl implements BeanFactoryAware { private BeanFactory beanFactory; public <T extends Bar> Foo<T> createFoo( Class<T> clazz ) { return beanFactory.getBean( ????????? ); } public void setBeanFactory( BeanFactory beanFactory ) { this.beanFactory = beanFactory; } } As you can see, I've put in ???????? where I'd like to retrieve a bean of type Foo<T>, where T extends Bar. However, it is not possible to derive a Class object of type Foo<T> and so I assume what I'm trying to do is impossible? Anyone else see a way round this or an alternative way of implementing what I'm trying to do? Thanks, Andrew

    Read the article

  • Session scoped bean as class attribute of Spring MVC Controller

    - by Sotirios Delimanolis
    I have a User class: @Component @Scope("session") public class User { private String username; } And a Controller class: @Controller public class UserManager { @Autowired private User user; @ModelAttribute("user") private User createUser() { return user; } @RequestMapping(value = "/user") public String getUser(HttpServletRequest request) { Random r = new Random(); user.setUsername(new Double(r.nextDouble()).toString()); request.getSession().invalidate(); request.getSession(true); return "user"; } } I invalidate the session so that the next time i got to /users, I get another user. I'm expecting a different user because of user's session scope, but I get the same user. I checked in debug mode and it is the same object id in memory. My bean is declared as so: <bean id="user" class="org.synchronica.domain.User"> <aop:scoped-proxy/> </bean> I'm new to spring, so I'm obviously doing something wrong. I want one instance of User for each session. How?

    Read the article

  • Spring MVC - Set an actionURL parameter with Javascript

    - by jeffl8n
    Is it possible to dynamically set a Spring MVC portlet:actionURL portlet:param using javascript? I have tried with the following code, but the id value always comes across as null to the controller. I have verified that setting the portlet:param manually passes the value correctly: <portlet:param name="id" value="2" /> I have also verified the value in the javascript is being set correctly and is not null. (Note: I've changed the variable names, etc. from the original code to simplify it and obfuscate it since it is my employer's code.) JSP: <portlet:actionURL var="modifyURL"> <portlet:param name="do" value="modify" /> <portlet:param name="id" value="${model.id}" /> </portlet:actionURL> ... <form:form action="${modifyURL}" id="modifyForm" modelAttribute="model"> <form:hidden path="id" id="id" /> </form:form> Javascript called when the update URL is clicked: function update() { document.forms[0]["id"].value = selectedId; document.forms[0].submit(); } Controller: @RequestMapping(params = {"do=modify"}) public void modify(@ModelAttribute("model") Model model, @RequestParam(value = "id", required=true) Long id, ActionRequest request, ActionResponse response, SessionStatus sessionStatus, ModelMap modelMap) { ....

    Read the article

  • Generate Spring bean definition from a Java object

    - by joeslice
    Let's suggest that I have a bean defined in Spring: <bean id="neatBean" class="com..." abstract="true">...</bean> Then we have many clients, each of which have slightly different configuration for their 'neatBean'. The old way we would do it was to have a new file for each client (e.g., clientX_NeatFeature.xml) that contained a bunch of beans for this client (these are hand-edited and part of the code base): <bean id="clientXNeatBean" parent="neatBean"> <property id="whatever" value="something"/> </bean> Now, I want to have a UI where we can edit and redefine a client's neatBean on the fly. My question is: given a neatBean, and a UI that can 'override' properties of this bean, what would be a straightforward way to serialize this to an XML file as we do [manually] today? For example, if the user set property whatever to be "17" for client Y, I'd want to generate: <bean id="clientYNeatBean" parent="neatBean"> <property id="whatever" value="17"/> </bean> Note that moving this configuration to a different format (e.g., database, other-schema'd-xml) is an option, but not really an answer to the question at hand.

    Read the article

< Previous Page | 40 41 42 43 44 45 46 47 48 49 50 51  | Next Page >