I need to call index() method in java class. But I tried this way it is not working.
It is going up to console.log('coming here....'); in controller.js, after that http path is not recognizing.
#RestController
public class DatumBoxShedule {
#Autowired
private DatumService datumService;
#RequestMapping(value = "/loadIndex", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public String index() throws IOException {
}
}
controller.js
app.controller('datumBoxShedule', function($scope, $http) {
$scope.newTodo = {};
$scope.loadIndex = function(){
console.log('coming here....');
$http.get('loadIndex')
.success(function(data, status, headers, config) {
$scope.todos = data;
})
.error(function(data, status, headers, config) {
alert('Error loading DatumBoxShedule');
});
};
$scope.loadIndex();
});
Is the Angular project part of the Spring project?
Are other mappings working (in other words: is the REST-Service running)?
If not: do you have an embedded container like Tomcat in your depenedencies?
For example, you could add the dependency for Tomcat to your project:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
I figureout ,issue is not in the anujularjs.Issue is in the spring.
my componantscan is not working
package main.java.datumbox;
#Configuration
#SpringBootApplication
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
#ComponentScan({"main.java.datumbox.service.impl","main.java.datumbox.controller","main.java.datumbox.service"})
public class Application{
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class,args);
}
}
package main.java.datumbox.service.impl;
public class DatumServiceImpl{
#Autowired(required = true)
DatumDataRepository datumDataRepository;
}
package main.java.datumbox.controller;
#RestController
public class DatumBoxController {
#Autowired
private DatumService datumService;
#Autowired
private DatumServiceImpl datumServiceImpl;
#RequestMapping( value = "/loadIndex" , produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public String index() throws IOException {
}
}
package main.java.datumbox.service;
#Service
public class DatumService{
#Autowired
HitApiService hitApiService;
}
error is coming..
APPLICATION FAILED TO START
Description:
Field datumServiceImpl in main.java.datumbox.controller.DatumBoxController required a bean of type 'main.java.datumbox.service.impl.DatumServiceImpl' that could not be found.
Action:
Consider defining a bean of type 'main.java.datumbox.service.impl.DatumServiceImpl' in your configuration.
Related
Hi I have this project running on Spring boot. When I tried to run, it give me the following error:
Description:
Field clientCredentialsApi in com.mycompany.microservice.myproject.bot.controller.BotCommandController required a bean of type 'org.springframework.web.client.RestOperations' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.web.client.RestOperations' in your configuration.
Here is my Code:
Application.java
package com.mycompany.microservice.myproject
//some imports
#SpringBootApplication`
#ComponentScan(basePackages = "com.mycompany.*")
public class Application {
public static void main(String[] args) {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
And here is the Controller:
BotCommandController.java
package com.mycompany.microservice.myproject.bot.controller;
//some imports
#RestController
#RequestMapping("/bot-command")
public class BotCommandController {
#Autowired
private RestOperations clientCredentialsApi;
#RequestMapping(value = "/sraix", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String sraixCommand(#RequestParam(name = "input", required = false) final String input,#RequestParam(name = "cs", required = false) final String cs) throws Exception {
final UserApiObject userApiObject = clientCredentialsApi.getForObject(env.getProperty("gms.location") + "/rest/user/" + userId, UserApiObject.class);
return userApiObject.getRole();
}
You are trying to autowire bean that you didn't define or implemented. RestOperations is an interface and has to be implemented.
#Autowired
private RestOperations clientCredentialsApi;
Spring is looking up for the classes annotated with #Bean or #Component or #Service to inject their references. In your case, you didn't define bean RestOperations and Spring can't inject it into BotCommandController.
Something like this:
#Bean
RestOperations rest(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.basicAuthorization("user", "password").build();
}
I am using Java8 with Spring 4.3.1.RELEASE. I have a project that needs to serve both static html pages and RESTful Services.
I can get one to work at a time, but not both at the same time.
For example, I need to access:
http://localhost:8080/jbosswildfly-1.0/category/list
http://localhost:8080/jbosswildfly-1.0/category/list/{id}
and
http://localhost:8080/jbosswildfly-1.0/index.html
http://localhost:8080/jbosswildfly-1.0/tocs.html
http://localhost:8080/jbosswildfly-1.0/www/index.html
My issue is with regards to my servlet-mapping.
I have the following:
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(servletContext);
Dynamic rest = servletContext.addServlet("rest", new DispatcherServlet(ctx));
//dynamic.addMapping("/**/*.do");
rest.addMapping("/*.html");
rest.addMapping("/category/list");
rest.addMapping("/category/list/*");
rest.setLoadOnStartup(1);
}
}
I have tried a number of combinations of mappings, but cannot seem to get static content and RESTful services to work simultaneously.
In the above example, I can get the following to work:
http://localhost:8080/jbosswildfly-1.0/index.html
http://localhost:8080/jbosswildfly-1.0/snoop.jsp
http://localhost:8080/jbosswildfly-1.0/WebContent/index.html
http://localhost:8080/jbosswildfly-1.0/category/list
But, the following is not found:
http://localhost:8080/jbosswildfly-1.0/category/list/AC
The following allows the RESTful Services to be accessed, but not the static html files:
rest.addMapping("/");
Any help appreciated.
UPDATE
Here is the code for one of my RESTful Services:
#CrossOrigin(origins = {"*"})
#RestController
#RequestMapping(CategoryRESTService.BASE_URI)
public class CategoryRESTService {
public static final String BASE_URI = "/category";
#Autowired
private CategoryService categoryService;
#RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Category>> findAllCategorys() {
List<Category> categories = categoryService.findAll();
return new ResponseEntity<List<Category>>(categories, HttpStatus.OK);
}
#RequestMapping(value = "/list/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Category> findCategoryById(#PathVariable String id) {
Category category = categoryService.findById(id);
return new ResponseEntity<Category>(category, HttpStatus.OK);
}
}
try to use rest.addMapping("/"); mapping, at the same time you have to configure static resource resolver, for example
through xml configuration
<mvc:resources mapping="*.html" location="location of the resource folder" />
or java-base config
#Configuration
#EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("*.html")
.addResourceLocations("location of the resource folder");
}
}
Can somebody tell me how to configure #RestController?
I do this :
#RestController
#EnableAutoConfiguration
public class Application {
#RequestMapping("/test.htm")
#ResponseBody
String home() {
return "Hello Worlds!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
#Controller
public class MusicControler {
class Test{
String name;
int age;
}
#RequestMapping(value = "/MyController")
public Test MyController() {
Test test = new Test();
test.name = "zl.shi";
test.age = 16;
return test;
}
}
When I request /test.htm, it is ok but I get response 404 for /testController.htm. Can someone help me about it?
use following code to create rest controller
#RestController
#RequestMapping("/service/")
public class Application {
#RequestMapping(value = "/getmemberdetail/{id}/{info}", method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<String> getuserdetail(#PathVariable int portalType,#PathVariable("id") int id,#PathVariable("info") String info) throws JsonProcessingException, ParseException{}
}
if you want to know how to use it you should read about it
Difference between spring #Controller and #RestController annotation
when you make starter-project spring you should make another class where you are going to put you controller don't forget RestController annotation or the controller annotation ( as best practice you shouldn't use the starter class of spring boot ) i hope this helps you
ps don't tag spring-mvc and spring-boot it's not the same thing
I am implementing rest services with Spring Boot. The entity classes are defined in a separate package. So I added that with Component annotation in Application.java.
#Configuration
#EnableAutoConfiguration
#ComponentScan("org.mdacc.rists.cghub.model")
#EnableJpaRepositories(basePackages = "org.mdacc.rists.cghub.model")
public class Application
{
public static void main( String[] args )
{
SpringApplication.run(Application.class, args);
}
}
Here is my controller class:
// SeqController.java
#RestController
public class SeqController {
#Autowired
private SeqService seqService;
#RequestMapping(
value = "/api/seqs",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<SeqTb>> getSeqs() {
List<SeqTb> seqs = seqService.findAll();
return new ResponseEntity<List<SeqTb>>(seqs, HttpStatus.OK);
}
}
I also created a JPA data repository that extends JPARepository in which I added custom query code.
// SeqRepository.java
#Repository
public interface SeqRepository extends JpaRepository<SeqTb, Integer> {
#Override
public List<SeqTb> findAll();
#Query("SELECT s FROM SeqTb s where s.analysisId = :analysisId")
public SeqTb findByAnalysisId(String analysisId);
}
Below is the servicebean class that implements a service interface
// SeqServiceBean.java
#Service
public class SeqServiceBean implements SeqService {
#Autowired
private SeqRepository seqRepository;
#Override
public List<SeqTb> findAll() {
List<SeqTb> seqs = seqRepository.findAll();
return seqs;
}
public SeqTb findByAnalysisId(String analysisId) {
SeqTb seq = seqRepository.findByAnalysisId(analysisId);
return seq;
}
}
When I started the application and type the following url in the browser "http://localhost:8080/api/seqs" , I got 404 error. What did I miss?
Edit #1:
I decided to take out the JPA repository stuff and change the controller class to the following:
#RestController
//#RequestMapping("/")
public class SeqController {
private static BigInteger nextId;
private static Map<BigInteger, Greeting> greetingMap;
private static Greeting save(Greeting greeting) {
if(greetingMap == null) {
greetingMap = new HashMap<BigInteger, Greeting>();
nextId = BigInteger.ONE;
}
greeting.setId(nextId);
nextId = nextId.add(BigInteger.ONE);
greetingMap.put(greeting.getId(), greeting);
return greeting;
}
static {
Greeting g1 = new Greeting();
g1.setText("Hello World!");
save(g1);
Greeting g2 = new Greeting();
g1.setText("Hola Mundo!");
save(g2);
}
#RequestMapping(
value = "/api/greetings",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<Greeting>> getGreetings() {
Collection<Greeting> greetings = greetingMap.values();
return new ResponseEntity<Collection<Greeting>>(greetings, HttpStatus.OK);
}
}
When I started the application and put "localhost:8080/api/greetings" in my browser I still got 404.
==>Did you make sure that your Spring Boot application class and your Rest Controller are in the same base package? For Example if your package for Spring Boot application class is com.example.demo, then your Rest Controller should be in same base package as com.example.demo.controller.
==>I think that is the reason boot is unable to map to the uri of your rest controller. Because #SpringBootApplication has #ComponentScan and #Configuration embedded in it already. Try doing this. I hope it works.
If spring boot starter web is not there in your pom.xml then add the same as the reason could be the code not being able to map the endpoints.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
The first thing I would try is to put #RequestMapping("/") on the class definition of the controller. Keep the same value on the method.
Another thing, unrelated to your problem, is that you do not need to define that custom query. JPA is actually smart enough to do the query you defined just by using that method name. Check out the findByLastName example here: https://spring.io/guides/gs/accessing-data-jpa/.
I have a application that uses Spring cloud config (--spring.profiles.active=native) and also serves up some html pages within the same application. All is fine until I introduce static resources (src/main/resources/css/bootstrap-switch.css). The URL calls to http://localhost:8080/css/bootstrap-switch.css fails with this Exception:
{"timestamp":1438114326940,"status":406,"error":"Not Acceptable","exception":"org.springframework.web.HttpMediaTypeNotAcceptableException","message":"Could not find acceptable representation","path":"/css/bootstrap-switch.css"}
When I disable the #EnableConfigServer, the URL returns the CSS content. I am on Spring Cloud Config version 1.0.2.
Here's my minimalist code that can reproduce this issue:
#SpringBootApplication
#EnableConfigServer
public class Application {
public static void main(String args[]) {
SpringApplication.run(ApplicationConfiguration.class, args);
}
}
#Configuration
#SpringBootApplication
class ApplicationConfiguration {
#Bean
public TestController testController() {
return new TestController();
}
#Bean
public MvcController mvcController() {
return new MvcController();
}
}
#RestController
class TestController {
#RequestMapping("/test")
#ResponseBody
public String test() {
return "hello world";
}
}
#Controller
class MvcController {
#RequestMapping("/landing")
public String landingPage() {
return "landing";
}
}
Config server by default has an api that matches /*/*. You can move the root of the api by changing spring.cloud.config.server.prefix=myroot.