w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Spring REST service.. How do I secure REST calls I am making in Spring MVC
Use HTTPS Use Spring Security with HTTP-header-based authentication Official examples: https://github.com/SpringSource/spring-security/tree/master/samples

Categories : Spring

replacing AnnotationMethodHandlerAdapter with RequestMappingHandlerAdapter issue
So as it turns out, simple switching the bean definition doesn't work due to the fact that the RequestMappingHandlerAdapter is depending on a whole host of entities being created and configured. Spring, by default, is using a WebMvcConfigurationSupport entity to do all this default configuration, but simply creating my own bean version doesn't help because spring creates its own. My approach ended up being something along the lines of below, where I left basically all of the configuration up to spring's default, but then added my own converter. The only drawback is that it's switching xml configuration to javaconfig, but in my case, it's ok. There's an article here that describes something similar. @Configuration public class WebConfig extends WebMvcConfigurationSupport { @Bean pu

Categories : Spring

How to configure spring mvc project which contains controller both annotated and configured
<!-- Registering MVC stuff necessary for @RequestMapping --> <mvc:annotation-driven /> <!-- Your view controller definition --> <mvc:view-controller path="/home" view-name="home" />

Categories : Spring

Spring MVC Rest: No mapping found for HTTP request with URI [/ecommerce-api/rest/checkout] in DispatcherServlet
Weird behaviour is often caused by inconsistency in your compiled and source files. I suggest you to perform proper cleaning (assume you are using eclipse). Stop server, then perform Project -> clean. After that clean server. Try restart your application. Other tip is try to debug what is happening when spring is looking for correct handler.

Categories : Java

Sending Objects from Spring MVC 3 REST client to REST provider
Reasons for your issues: If you want to accept data in your controller through @RequestParam, the request should contain the data as, well request parameters. Think url containing ?empCode=xyz&password=abc. Or in the request body as empCode=xyz&password=abc The way you are sending an Employee object in the client code, the object will be serialized into the request body. With the code you have provided, the client will make a request with the employee object converted to its JSON representation in the request body. Something your controller method is not equipped to read. (Assuming you have mapping jackson jars in the classpath) Possible solutions: Change the controller method signature, instead of @RequestParam, use @RequestBody, which tell Spring to extract the value of the

Categories : Json

How to pass user and password to Spring REST service with Spring RESTTemplate
it would help if you posted the method signature from the server side. how are you doing your authentication? here's a get example. post would be the same but using postForObject() String result = restTemplate.getForObject("http://127.0.0.1:8080/springmvc-rest-secured-test/json/{user}/{password}", String.class, "user", "pass");

Categories : Spring

Static Resources (js,css..) in Spring MVC app not available when adding spring-data-rest
I'm faced with same with some differences. In my case I add my handler for static resources: @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("/WEB-INF/static/"); } After that some static files with long path (like /a/b/c/d.css or /a/b/c/d.js) served as static content but some files (like /a/b/c.js) is not. I found that in my case RepositoryRestHandlerMapping registers itself using Ordered.HIGHEST_PRECEDENCE and most of CSS and JavaScript requests handled into this handler by rules like [/{repository}/{id}/{property}]. This is a bug in Spring-Data, now this fixed (thanks to Oliver Gierke), you can get fixed version 2.0.0.BUILD-SNAPSHOT from snapshot repo and I hope this can help.

Categories : Spring

Spring MVC + Spring Security login with a rest web service
you can define a custom pre-auth filter by extending AbstractPreAuthenticatedProcessingFilter. In your implementation of getPreAuthenticatedPrincipal() method you can check if cookie exists and if it exists return cookie name is principal and cookie value in credentials. Use PreAuthenticatedAuthenticationProvider and provide your custom preAuthenticatedUserDetailsService to check if cookie is vali, if its valid also fetch granted authorities else throw AuthenticationException like BadCredentialsException For authenticating user using username/password, add a form-login filter, basic-filter or a custom filter with custom authentication provider (or custom userdetailsService) to validate user/password In case cookie exists, pre auth filter will set authenticated user in sprin

Categories : Spring

Cryptic issue: RequestMappingHandlerAdapter: Constructor threw exception; nested exception is java.lang.NullPointerException
After much researching, I pinpointed the problem to one of our maven dependencies, i.e. our Sybase JDBC driver: <dependency> <groupId>com.sybase</groupId> <artifactId>jconn4</artifactId> <version>7.07.GA</version> <scope>runtime</scope> </dependency> Therefore, this has got nothing to do with spring of the jdk.

Categories : Spring

Saving an image to Parse through the REST API, then using it in iOS app
I looked up the interface of PFFile and I didn't find a way of downloading a PFFile directly. However, you said that you set the URL of the file as a string property of PFObject. Instead, why don't you set that property as a PFFile? PFObject *object = .... PFFile *imageFile = [object objectForKey:@"imageFile"]; creature.file = file;

Categories : IOS

Django Rest Framework not saving foreign key for a small number of requests
You could use two different ModelSerializer classes, one for creation, that makes sure, that an Order object can't be created without a related User and one for updating orders, that passes required=False to the related field's constructor, so that you still can save existing orders that haven't a related User.

Categories : Python

Saving a hasMany relationship containing array of IDs back to REST server using Ember-Data
If you're using a hasMany, then you want to be setting 'jobRole' with a collection of live JobRole objects, not with an array of IDs. // assume role1 and role2 are JobRole objects // obtained via store.find() (or something...) someUser.set('jobRole',[role1,role2]); Alternatively, if you want to set the property with a list of IDs, then you could just use a non-typed DS.attr and the array will be passed through as is. Lrt.User = DS.Model.extend({ jobRole: DS.attr() }); //then later someUser.set('jobRole',[1,42]);

Categories : Ember Js

Spring MVC Daylight saving issue
I want to know, how come spring mvc form submission getting EST whereas my application is EDT You're using the America/New_York time zone, which alternates between EST and EDT as daylight saving time changes occur. When you use a time without a date, you're implying the date of 1/1/1970 - which for America/New_York was in EST at that time. You should instead be applying the time to a particular date so it will use the correct offset for that time.

Categories : Java

Spring @Async saving searches
Have a look at ThreadPoolTaskExecutor. When all threads in the pool are busy your job will just be queued until a thread is available. The maximum queue capacity and number of threads can be adjusted via queueCapacity / maxPoolSize property (queueCapacity defaults to INTEGER.MAX_VALUE). One the thing you have to be concerned about is memory exhaustion. If you set your queue capacity too high and your job ran for too long, all the jobs can stack up in the queue eating up memory. Also consider denial of service. An hacker can perform attack by filling up all the queue (hence denying genuine user's job from running) So I'd say yes this is a good approach in the sense your Controller don't have to wait until the job is done, however consider how much memory each queued jobs take, how much m

Categories : Java

Spring MVC REST
You can try using Regular expressions on the @PathVariable. Like this from the Spring Docs: @RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}{extension:\.[a-z]+}") public void handle(@PathVariable String version, @PathVariable String extension) { // ... } } You'll just have to think on a regular expression that matches the "example/test/case/version/sample" that is your expression. See the title: "URI Template Patterns with Regular Expressions" on this page: http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html for more information

Categories : Rest

Spring JpaTransactionManager not saving Activiti entities to DB
I've already waste a lot of time trying to pass common transaction manager to Spring and Activiti - and no result. No mean of full answer to your question, but I hope it will save you some time Activiti forum: http://forums.activiti.org/content/activiti-doesnt-submit-rollback http://forums.activiti.org/content/activitispringhibernate-common-transaction-manager Demo: These repos illustrate that Activiti don't accept jpa/hibernate transactions: https://github.com/JOLO-/activiti-jpa-spring-transaction-demo.git https://github.com/JOLO-/activiti-hibernate-spring-transaction-demo.git You also can see demo https://github.com/Activiti/Activiti (Activiti + Spring + Bitronix) it may help (I have no time to check it yet). P.S. As an alternative to common transaction I see compensation eve

Categories : Spring

Spring Rest API validation
Use validation groups: public interface ValidateOnCreate {} public interface ValidateOnUpdate {} . public class myItem{ @NotEmpty(groups = { ValidateOnCreate.class, ValidateOnUpdate.class }) private String foo; @NotEmpty(groups = ValidateOnUpdate.class) private String bar; ... } . @RequestMapping(value="/", method=RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public @ResponseBody myItem createItem( @Validated(ValidateOnCreate.class) @RequestBody myItem item) { ... } @RequestMapping(value="/", method=RequestMethod.PUT) @ResponseStatus(HttpStatus.NO_CONTENT) public @ResponseBody myItem createItem( @Validated(ValidateOnUpdate.class) @RequestBody myItem item) { ... } Note that you need Spring-specific @Validated in this case, because @Valid do

Categories : Spring

Spring MVC Rest URL and URL redirection
As far as know, I don't think so. But one way will be like, each time your controller will produce JSON response. But for web application you need to add extra call for each request which will load desired page and then call your CRUD methods on load of your page and parse the JSON response to fill the data.

Categories : Java

Spring MVC REST PUT is not working
Only getand post are officialy supported with forms. I'm not aware of any browser that supports put with forms. It is supported with AJAX, though. Apart from that the support of the Java Servlet API for PUT is not ideal. You might need to include a filter in your web.xml: <filter> <filter-name>httpPutFormContentFilter</filter-name> <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class> </filter> Before I forget: You can send a post request and use another filter to fake a put request: <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> To get this working you have to include

Categories : Rest

Spring REST API and i18n
I have two suggestions to try out. First, are you certain that the LocaleChangeInterceptor is getting invoked? Most of the configurations I've seen have an id of handlerMapping for the HandlerMapping. The other suggestion is concerning another id, namely sessionLocaleResolver, I think it should be localeResolver. I'm not sure if Spring relies on those id values or the class types by default for wiring all of this together, but it is worth a shot.

Categories : Java

Spring + rest + mysql
Here's a pretty decent tutorial on getting started with Spring MVC: http://www.mkyong.com/spring3/spring-3-mvc-hello-world-example/ For mysql, have a look at: http://www.mkyong.com/spring/maven-spring-jdbc-example/

Categories : Web Services

Why is my email getting cut off with Spring MVC and REST?
If you are using spring 3.0.x add the following to your spring config file: <!-- Spring Configuration needed to avoid URI using dots to be truncated --> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="useDefaultSuffixPattern" value="false" /> </bean> if you are using a more recent version of spring check this discussion: Spring MVC @PathVariable with dot (.) is getting truncated Spring default configuration cuts off extensions in urls.

Categories : Spring

Spring REST with both JSON and XML
You should use the ContentNegotiatingViewResolver. There is an issue in that a collection of POJOs are not mapped correctly with some XML marshallers. XStream has solutions for this (Moxy too?). Here's a place to start: http://blog.springsource.org/2013/06/03/content-negotiation-using-views/ Basically, you use a MappingJacksonView and a similar one for XML, which is a "fake" view that uses Jackson (or an XML marshaller) to marshall your POJO(s) to the correct format. The server will send back the correct type based on one of: the HTTP Accept header a "filetype extension", such as ".json" a querystring parameter, such as "format=json"

Categories : Java

How do I add errors to my Spring MVC REST Service?
Define a new exception class, e.g. ResourceNotFoundException and throw an instance of this from your annotated controller method getName. Then also define an annotated exception handler method in your Controller class to handle that exception, and return a 404 Not Found status code, potentially logging it. @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) public void handleResourceNotFoundException(ResourceNotFoundException ex) { LOG.warn("user requested a resource which didn't exist", ex); } Or even returning some error message, using @ResponseBody annotation: @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) @ResponseBody public String handleResourceNotFoundException(ResourceNotFoundExc

Categories : Json

Handling exceptions in Spring MVC along with Rest API
I noticed this have been left for a month or so, so it might be old. But this article may help http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/. The section 3.5 is probably what you are looking for, a custom Exception Resolver.

Categories : Spring

Spring Data Rest - Caching
The easiest way to implement this on the repository level is to use Spring's @Cacheable as it can be seen in the Spring Data JPA Examples project. Another option is to leverage HTTP Caching using the Apache HTTPD settings or a Varnish for example.

Categories : Caching

Image upload with Spring REST
This is a piece of code I wrote time ago (you could pass the filename as a @PathVariable): server side: @RequestMapping(value = "/file", method = RequestMethod.POST) public String uploadFile(@RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse response) { //add your logics here //File newFile = new File("blablabla.xxx"); //file.transferTo(newFile); ... test with rest template: @Test public void testFileUpload() { String url = "http://blablabla.com/file"; Resource resource = new ClassPathResource("images/file.xxx"); MultiValueMap<String, Object> mvm = new LinkedMultiValueMap<String, Object>(); mvm.add("file", resource); ResponseEntity<String> respEnt = rt.postForEntity(url, mvm, S

Categories : Java

seperating GUI and DAO via REST Webservices and Spring
I think this post can be useful for you: Spring MVC RESTful multiple view - 404 Not Found I like the idea to work with restful, because you can really split the application not just in the back-end, but in the front-end as well. This way you can just get JSON in your javascript. But of course each case is different each other. Follows a video about the subject: http://www.infoq.com/presentations/REST-API-Spring-MVC

Categories : Java

REST with Spring Controller issue
You forget to add the leguname to the url: use /leagues/SuperHero/levels/ instead (/leagues/levels/) If you want to filter out /leagues/levels/`, then you can try to add an additional handler method: @RequestMapping(value="/leagues/levels/") for example, to return all levels of any league

Categories : Spring

Spring Themes not working with REST
I expect that /MyApp/themes/default.css should deliver default.css. But this is a resource file, and you mapped them by <mvc:resources mapping="/resources/**" location="/resources/" /> So the right request url would be /MyApp/resources/default.css (assuming that the default.css is located in webapp/resources/default.css)

Categories : Spring

Spring 4.x/3.x (Web MVC) REST API and JSON2 Post requests, how to get it right once for all?
CURL Post call curl -i -H "Content-Type: application/json" -X POST -d '{"id":100,"username":"JohnBlog","name":"John","lastName":"Blog","email":"JohnBlog@user.com"}' http://localhost:8080/[YOURWEBAPP]/api/user/add Different Error Scenarios: Here I explore different errors you might come across after you have made a curl call and what might have possibly gone wrong. Scenario One: HTTP/1.1 404 Not Found Server: Apache-Coyote/1.1 Content-Type: text/html;charset=utf-8 Content-Length: 949 Date: Tue, 04 Jun 2013 02:59:35 GMT This implies that the REST API does not exist in the URL you have provide. Root cause: You might have a typo in your request (believe me this can happen)! It could be that your spring configuration is not right. If this is the case it needs further digging into wha

Categories : Java

How can I get this working with a GET or should it be a POST with REST Service in Spring
get as it is not changing anything onserver just returning data here is the spec. Use request parameters like this @RequestMapping(value = "/checkstatus", method = RequestMethod.get) @ResponseBody public ResponseEntity<String> getCheckEnrollStatus(@RequestParam final Long id) or uri parameters, like @RequestMapping(value = "/checkstatus/{id}", method = RequestMethod.get) @ResponseBody public ResponseEntity<String> getCheckEnrollStatus(@PathVariable final Long id) throws ResourceNotFoundException {

Categories : Web Services

Spring REST API custom exceptions handling
The ServletRequestBindingException is a hint that something went wrong before the handler method of the controller. In this case some binding issue. Exception handlers annotated with @ExceptionHandler are only called when an exception is thrown within a controller handler method (@RequestMapping).

Categories : Spring

Spring Data REST PUT Method Not Allowed
You are trying to use the same url for POST and PUT requests, but PUT usually requires the id of the object that has to be updated. Spring does have mapping for localhost:8080/<applicationname>/<entityName>, but only for POST request and hence the error. Try using PUT with: http://localhost:8080/<applicationname>/<entityName>/<objectId>

Categories : Java

Does Spring Data REST support JPA @Version?
I would say no, and that has not much to do with the use of Spring Data REST. You already mention you cannot set the version yourself as what happens then is undefined (I had this pleasant experience myself also). You basically have the same issue when posting normal form data and not storing the current version in the session (@SessionAttributes). What we ended up doing was that we wrote a hibernate interceptor (would be a listener now I guess) which does the checking (so that we could actually set the version field). This worked without to much problems (but that was about 6 years ago), so Hibernate might have changed and could be acting differently now.

Categories : Spring

Spring REST web service appContext failed
You're missing the Spring expression JAR file. Since you have already have the Spring core JAR file, you should have the expression JAR file if using a project build manager such as Maven as spring-expression is a dependency of spring-core. In this case, the chances are that there was an problem deploying expression JAR file (either it doesn't exist in your local Maven repository or is corrupt). See here how to refresh your local Maven repositories. If you're not using a build manager such as Maven, then you will need to manually download the JAR file, matching the version with your existing Spring JAR files.

Categories : Java

Why Spring REST do not analyze "get","post" methods with same url
Spring can support GET and POST for the same url. I've done it many times. For example (this is POST and PUT, but it's the same difference): @Controller @RequestMapping(value="player") public class PlayerController { @Autowired private PlayerService playerService; @RequestMapping(method = RequestMethod.POST) @ResponseBody public Player createNewPlayer(@RequestBody Player player) { return playerService.createNewPlayer(player); } @RequestMapping(method = RequestMethod.PUT) @ResponseBody public Player updatePlayer(@RequestBody Player player) { return playerService.updatePlayer(player); } } If you can post the error message you're getting, maybe we can help you figure out what's wrong.

Categories : Spring

REST API with JSON representations using Apache CXF without Spring
I got it figured out. I needed to configure JSONProvider as one of initparams for NonSpringServlet in the deployment descriptor. This wasn't working for me before as I was missng the cxf extensions library and the jettison library. These dependencies don't get automatically pulled by maven or gradle if you only have a dependency on cxf front end jars.

Categories : Json

Spring MVC REST Web services: post from PHP using JSON
Though is bit late to answer, here is my code. You can find good explanation here. @RequestMapping(method = RequestMethod.POST) public @ResponseBody Transaction createTransaction(MyModel myModel, @RequestParam("secKey") String secKey) { log.debug(" create MyModel {}", mymodel); return new MyModel(); } I think you should have another look at your delete operation. It uses post request and it is better if you can use, put or delete.

Categories : PHP

How do I post to a REST service using RestTemplate in Spring
I noticed at least two problems: The first one is that you are sending your request to a wrong url. The request mapping of our controller method the following: @RequestMapping(value = "/user/{id}", method = RequestMethod.POST ) But you send to request to url: "http://" + mRESTServer.getHost() + ":8080/springmvc-rest-secured-test/json/user/2" You might want to remove the string 'json' from the path. The second problem is that your controller method returns an User object but when you call the postForObject() method of the RestTemplate class, you state that the return type of your controller method is String. You should change the line: String returns = rt.postForObject(uri, u, String.class); to: User returns = rt.postForObject(uri, u, User.class); See the Javadoc of the Rest

Categories : Spring



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.