Menu
  • HOME
  • TAGS

@PathVariable and @RequestParam not working together

Tag: spring,spring-mvc,annotations,spring-annotations,path-variables

I have below code in my controller:

@RequestMapping(value = "/child/{nodeId}/{relType}",method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON)    
    public Iterable<Node> getConnectedNodes(@RequestParam("page")int page, @RequestParam("size")int size, @PathVariable("nodeId") String nodeId, @PathVariable("relType") String relType) {
        return nodeService.getConnectedNodes(nodeId, relType,page,size);    
    }

And this is the API url i am hitting

http://localhost:8080/node/child/e17a64ff-dc2b-49b1-a995-67dba9413d67/Collegues?page=0&size=1

Here in debug mode I can see values of path variables i.e. nodeId and relType but can not see values of request param page and size which I am passing through my request in URL above.

What's wrong with @RequestParam ? Please help.

Best How To :

Can you try with below snippet:

@RequestMapping(value = "/child/{nodeId}/{relType}",method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON)    
        public Iterable<Node> getConnectedNodes(@RequestParam(value="page", required=false) int page, @RequestParam(value="size", required=false) int size, @PathVariable("nodeId") String nodeId, @PathVariable("relType") String relType) {
            return nodeService.getConnectedNodes(nodeId, relType,page,size);    

}

Error while setting targetConnectionFactory in UserCredentialsConnectionFactoryAdapter Spring 4

java,spring,jms,spring-boot,spring-jms

The big difference between your code and the example is in the XML config example that myTargetConnectionFactory is actually a bean managed by Spring. You aren't doing that. You are just creating a new object Spring doesn't know about. The magic happens when setting the targetConnectionFactory of myConnectionFactory. Even though...

Spring Data Rest: Return Resources of User

java,spring,spring-security,spring-data-rest

If you are using Spring security integration you can use ACL (maybe to heavy) or simple postFilter like following: public interface ShoppingItemRepository extends CrudRepository<ShoppingItem, Long> { @PostFilter("filterObject.user.getId() == principal.id") @Override Iterable<ShoppingItem> findAll(); } ...

Spring Resttemplate login fails

java,spring,spring-mvc,spring-security,csrf

You seem to have upgraded Spring Security to 4.x as well (evidenced by xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd). Unfortunately, Spring Security 4.x is not a drop-in replacement for 3.x. You will need to review the Official Migration Guide for configuration elements that need to be tweaked. However, some of the ones that stand...

Dynamic fields thymeleaf list iteration

spring,spring-mvc,spring-boot,thymeleaf

Actually when binding fields to a form, in order to acces to a list with th:each. As the doc specify, we should use the two variable item, and phoneStat this way and not just phoneStat : <div th:each="item, phoneStat : *{phones}"> <select th:field="*{phones[__${phoneStat.index}__].variety}" > <option> </option> </select> <div class=" input-field...

How can implement long running process in spring hibernate?

java,spring,hibernate

I recommend you to use DeferredResult of Spring. It´s a Future implementation, that use the http long poling technique. http://docs.spring.io/spring-framework/docs/3.2.0.BUILD-SNAPSHOT/api/org/springframework/web/context/request/async/DeferredResult.html So let´s says that you will make a request, and the server it will return you the deferredResult, and then your request will keep it open until the internal process(Hibernate)...

Default Spring bean when profile is not present

java,spring,spring-mvc,spring-profiles

The problem here is that your class DevController inherits from DefaultController. Keep classes separate. Don't extend DevController with DefaultController even if the contents are same.

How to set property using “tasklet ref” tag

spring,spring-batch

Isn't this what you want: <step id="validaSituacaoStep"> <tasklet ref="validarSituacaoTasklet "/> </step> <bean id="validarSituacaoTasklet" class="my.package.tasklet.ValidarSituacaoTasklet" scope="step"> <property name="situacao" value="EM_FECHAMENTO"/> </bean> UPDATE Based on the comment left, this should work: <step id="validaSituacaoStep"> <tasklet> <bean class="my.package.tasklet.ValidarSituacaoTasklet" scope="step"> <property name="situacao" value="EM_FECHAMENTO"/>...

Hibernate : Stale state exception

java,spring,hibernate,spring-mvc,transactions

The reason for the exception is that you were loading a GroupCanvas before and this has a reference to the GroupSection. Then you delete the GroupSection but when the transaction commits GroupCanvas still holds a reference to the deleted GroupSection and you get the StaleStateException. As you saw, deleting the...

Logging operations in lightadmin

java,spring,logging,lightadmin

You can use the class AbstractRepositoryEventListener like it's show on the LightAdmin documentation here Add you logger insertion by overiding onAfterSave, onAfterCreate and onAfterDelete into your own RepositoryEventListener. After you just need to register your listener like this public class YourAdministration extends AdministrationConfiguration<YourObject> { public EntityMetadataConfigurationUnit configuration(EntityMetadataConfigurationUnitBuilder configurationBuilder) { return...

how to autowire in spring for test classes?

spring,testing

Here is a skeleton of how your test class should look like @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") @TransactionConfiguration(transactionManager = "<< YOURTRANSACTIONMANAGER >>", defaultRollback = true) @Transactional public class ServiceTest { //The name of your resource/service should be the same as defined in your bean definition @Resource private YourService service; @Test public void testYourService()...

Can't Override Equals method on Java when calling contains

java,spring,hibernate

You need to provide an complmentary hashCode() method whenever providing an equals() method and visa-versa. The reason for this is to fulfil the API contracts when interacting with the objects in collections. See the site for tips on creating the code hashcode-equals The Java Docs have more information about the...

Cannot create bean when start the application

java,spring,javabeans,sftp,job-scheduling

please visit DefaultSftpSessionFactory it has following : setUser public void setUser(String user) The remote user to use. This is a mandatory property. Parameters: user - The user. See Also: JSch.getSession(String, String, int) ...

Mybatis skipping update the specific column if its parameter is null

spring-mvc,mybatis

Your gripe is with SQL, not MyBatis. If your update statement includes say SET mobile = null, the SQL will do just that. But MyBatis provides good dynamic SQL facilities with the if statement. See https://mybatis.github.io/mybatis-3/dynamic-sql.html. That should put you on the right track for a custom solution. Also, consider...

Spring: @NestedConfigurationProperty List in @ConfigurationProperties

spring,properties,configuration,spring-boot

You need to add setters and getters to ServerConfiguration You don't need to annotate class with nested properties with @ConfigurationProperties There is a mismatch in names between ServerConfiguration.description and property my.servers[X].server.name=test ...

viewResolver with more folders inside of WEB-INF/jsp is not working in spring

java,spring,jsp,spring-mvc

Say you have a jsp test.jsp under /WEB-INF/jsp/reports From your controller return @RequestMapping("/helloWorld") public String helloWorld(Model model) { model.addAttribute("message", "Hello World!"); return "reports/test"; } ...

Trouble with Login using Spring Boot and JDBC Security

spring,spring-security,spring-boot

There are 2 things flawed in your setup. You should post to /login instead of /j_spring_security_check as that is the new URL when using java config (and in Spring 4 for XML config also). You have set the usernameParameter to name and your form still has username. Fix those flaws...

Is it possible to construct an object partially with Spring DI and partially with Jersey DI?

spring,dependency-injection,jersey,jersey-2.0,hk2

It should work. Given you have the required Spring-Jersey integration dependency[1] and have correctly configured the application[2] 1. See Spring DI support in Jersey 2. See official Jersey Spring example What happens is HK2 (Jersey's DI framework) will look for an InjectionResolver for the @Autowired annotation, in order to resolve...

How to apply HandlerInterceptor to Spring Boot Actuator endpoints?

java,spring,spring-mvc,spring-boot

You can use an EndpointHandlerMappingCustomizer to configure the interceptors of the Actuator's endpoints. For example: @Bean public EndpointHandlerMappingCustomizer mappingCustomizer() { return new EndpointHandlerMappingCustomizer() { @Override public void customize(EndpointHandlerMapping mapping) { mapping.setInterceptors(new Object[] { application.executeTimeInterceptor() }); } }; } ...

Importing Spring MVC Project Manually to Eclipse

java,eclipse,spring,spring-mvc

you will extract zip file and go to inside folder in templete.zip is import succesully into eclipse IDE.i have tested.

Cron expression must consist of 6 fields (found 1 in “#{systemEnvironment['db_cron']}”)

spring,groovy,cron,spring-el

You should set env variable like you do: export db_cron="0 19 21 * * *" then restart your ide if you are using or restart your terminal session. @Scheduled(cron = "${db_cron}") def void schedule() { ... } I tried it and here is my screenshot. Everything works as expected......

Spring OAuth2 not giving refresh token

java,spring,spring-security,spring-security-oauth2

The client needs authorizedGrantType "refresh_token". Try this @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("resource-serv") .scopes("read") .resourceIds("my-resource") .secret("secret123") .and() .withClient("app") .authorizedGrantTypes("client_credentials", "password", "refresh_token") .scopes("read") .resourceIds("my-resource") .secret("appclientsecret"); } ...

shall I use Spring framework for a performance-critical proxy application? [closed]

java,spring,authentication,servlets

Before re-writing your code first thing you should analyze is why do you require Spring framework? What problem are you facing in your current architecture? Just because size of the response data stokes up shouldn't be the only reason to re-write your code. You can better design your existing code...

How to send current page number in Ajax request

javascript,jquery,ajax,spring-mvc,datatables

DataTables already sends parameters start and length in the request that you can use to calculate page number, see Server-side processing. If you still need to have the URL structure with the page number, you can use the code below: "ajax": { "data": function(){ var info = $('#propertyTable').DataTable().page.info(); $('#propertyTable').DataTable().ajax.url( "${contextPath}/admin/getNextPageData/"+(info.page...

How to implement customer subdomain in Spring framework

spring,saas,multi-tenancy

Create a custom filter which parses whole url and extracts subdomain, then check if the user is on proper domain with proper rights. Also worth mentioning Nginx should redirect "*.yourdomain.com" so all subdomains don't have to exist in Nginx, they could exist in database and each user has his unique...

Spring Boot - How to set the default schema for PostgreSQL?

java,spring,hibernate,postgresql

You can try setting the default schema for the jdbc user. 1) ALTER USER user_name SET search_path to 'schema' 2) Did you try this property? spring.datasource.schema http://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html...

Spring Data JPA user posts

java,spring,jpa,data

Create a second entity (java class) e.g. UserPost: @Entity @Table(...) public class UserPost { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private long userId; ... } Then add @OneToMany relationship field to User. Cascading, lazy-loading, etc. depends on how you'd use it. It'd look like this inside User: @OneToMany(cascade={...}) @JoinColumn(name="userId")...

Using Spring Security, what's the right way to manage authorization to query responses?

java,spring,spring-security

You're trying to query a list of items that a user may not be the owner of but should be able to access anyways, yes? Like shared documents or some-such. If that is the case, you need to upgrade to Spring Security 4 . It allows for SpEL expressions with...

Form submit portlet with Spring MVC

java,jsp,spring-mvc,liferay,portlet

Which version of Liferay you are using? if it is > 6.2 GA1 Then in your liferay-portlet.xml file, please add this attribute and recompile and test again. <requires-namespaced-parameters>false</requires-namespaced-parameters> Liferay adds namespace to the request parameters by default. You need to disable it. ...

Spring: Response time

java,spring,spring-ws

Yes, implementing an EndpointInterceptor is the best fit for this task, as it gives you access to the SOAP messages through the MessageContext. See the Reference Documenation.

GenericApplicationContext cannot be cast to WebApplicationContext : Spring Web Flow

java,spring,spring-mvc,classcastexception,spring-webflow-2

FlowBuilderServices is meant to be a Spring-managed bean, but in your config it is just a new instance. It likes to be ApplicationContextAware and InitializingBean, but that is gonna work only if managed by Spring. The solution is simple: put @Bean on getFlowBuilderServices() method. And I think you should also...

Why is my Spring Boot autowired JPA Repository failing JUnit test?

java,spring,junit,spring-boot

Exception comes from this line: ReflectionTestUtils.setField(userResource, "userRepository", userRepository); Second parameter of setField method is a field name. UserResource has field "repository" - not "userRepository" as you try to set in your test....

@RestController throws HTTP Status 406

java,spring,rest,maven

The issue is with the dependencies that you have in pom.xml file. In Spring 4.1.* version the pom.xml dependency for Jackson libraries should include these: <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.4.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.4.1.1</version> </dependency> You...

Transaction error in Spring

java,spring,jpa

In the stacktrace, there are no Spring AOP class listed between these two lines: at com.vizaco.onlinecontrol.service.impl.UserServiceImpl.saveUser(UserServiceImpl.java:51) at com.vizaco.onlinecontrol.controller.UserController.createUser(UserController.java:112) Your Dependency Injection is not setup right.. the Controller should be getting a Spring Bean of UserService ...

How get value from property file to input in springConfig.xml

java,xml,spring-mvc

Look at this line of your stack trace: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mailSender' defined in class path resource [springConfig.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'port'; nested exception is java.lang.NumberFormatException: For input...

Use $or operator in @Query annotation in spring data mongodb repository

java,spring,mongodb,spring-data-mongodb

Per MongoDB reference for $or, your Query should be @Query("{'$or':[ {'type':?0}, {'name':?1} ]}") you'll need to give pass type and name params....

Job not executing at fixed rate

spring-mvc,jobs,execution

The difference is about time rather than number of tasks. Fixed rate will keep track of time and spun new thread to match the fixed-time of 5 seconds. So in short, you would not have multiple threads as you are expecting. In 15 seconds, there should be three executions. But...

Jsp list output [email protected]?

jsp,spring-mvc,spring-boot

There are two things I see wrong. First if your code is really as posted and not a typo, than you should note that you don't print anything inside a loop as you just iterate and never do anything with the user variable The following <c:forEach items = "${tweets}" var="user"...

JdbcTemplate Mockito ClassCastException

spring,mockito,classcastexception

Remove the answer = Answers.RETURNS_SMART_NULLS. Test passes when I remove that. What does that feature do? The default null behavior works fine for me. As a bonus, you can also use the MockitoJunitRunner to clean up the code a bit... @RunWith(MockitoJUnitRunner.class) public class DaoJdbcTest { @Mock private JdbcTemplate jdbcTemplate; @InjectMocks...

How do I combine Facet and FilterQueries using Spring data Solr?

spring,solr,filtering,facet

I assume you're using Spring Data Solr, from your reference to SimpleFacetQuery. Based on your sample query, the code would look something like this: // creates query with facet SimpleFacetQuery query = new SimpleFacetQuery( new Criteria("lastName").startsWith("Harris")) .setFacetOptions(new FacetOptions() .addFacetOnField("state")); // filter parameters on query query.addFilterQuery(new SimpleFilterQuery( Criteria.where("filterQueryField").is("red"))); // using query...

How to check JAVA variable ${account} in jsp?

java,spring-mvc

First make sure that you have the JSTL library in your classpath, then import it into your JSP page with: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> Now you can compare the string in JSP with: <ul class="dropdown-menu dropdown-user"> <c:if test="${uaccount == 'admin'}"> <li><a href="users_info">user info</a></li> </c:if> <li><a href="${pageContext.request.contextPath}/logout">logout</a></li> </ul> ...

Override Spring form error messages

java,spring,default,custom-errors

You can override the defaults by creating custom messages in your localization bundle with keys following conventions defined by Spring's DefaultMessageCodeResolver. For the sake of completeness here is the relevant part of its documentation: Will create two message codes for an object error, in the following order (when using the...

Is it possible to login from a winforms application to a website which uses spring security?

java,c#,winforms,spring-mvc,spring-security

Authentication can be setup in many ways with Spring Security. For example: <http pattern="/webservice/**" create-session="stateless" realm="TestRealm"> <http-basic/> <intercept-url pattern="/**" access="ROLE_USER"/> </http> Then it is as simple as this to authenticate from C#: var request = (HttpWebRequest)WebRequest.Create(url); request.Credentials = new NetworkCredential(username, pwd); ...