Spring rest controller not returning html - spring-mvc

I'm using spring boot 1.5.2 and my spring rest controller looks like this
#RestController
#RequestMapping("/")
public class HomeController {
#RequestMapping(method=RequestMethod.GET)
public String index() {
return "index";
}
}
when I go to http://localhost:8090/assessment/ it reaches my controller but doesn't return my index.html, which is in a maven project under src/main/resources or src/main/resources/static. If I go to this url http://localhost:8090/assessment/index.html, it returns my index.html. I looked at this tutorial https://spring.io/guides/gs/serving-web-content/ and they use thymeleaf. Do I have to use thymeleaf or something like it for my spring rest controller to return my view?
My application class looks like this
#SpringBootApplication
#ComponentScan(basePackages={"com.pkg.*"})
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
When I add the thymeleaf dependency to my classpath I get this error (500 response code)
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers
I guess I do need thymeleaf? I'm going to try and configure it properly now.
It works after changing my controller method to return index.html like this
#RequestMapping(method=RequestMethod.GET)
public String index() {
return "index.html";
}
I think thymeleaf or software like it allows you to leave off the file extension, not sure though.

RestController annotation returns the json from the method not HTML or JSP. It is the combination of #Controller and #ResponseBody in one. The main purpose of #RestController is to create RESTful web services. For returning html or jsp, simply annotated the controller class with #Controller.

Your example would be something like this:
Your Controller Method with your route "assessment"
#Controller
public class HomeController {
#GetMapping("/assessment")
public String index() {
return "index";
}
}
Your Thymeleaf template in "src/main/resources/templates/index.html"
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Hello World!</p>
</body>
</html>

I solved this by removing #EnableWebMvc annotation from configuration class.
Spring MVC Auto-configuration provides static index.html support.
If you want to take complete control of Spring MVC, you can add your
own #Configuration annotated with #EnableWebMvc.
Get more detail from Spring MVC Auto-configuration.

If you try to "Building a RESTful Web Service" -> annotate your controller class with #RestController annotation if not annotate your controller class with #Controller class.
When we use spring as SpringMVC - #Controller
When we use spring as SpringRESTfull Web Service - #RestController
Use this link to read : Spring Stereo Type

Related

How do I inject an EJB in Spring MVC using annotations?

My dispatcher-servlet.xml has basically:
<context:component-scan base package="package.ejb" />
<mvc:annotation-driven />
In the #Controller class I have:
#Controller
public class ApplicationController {
#EJB(lookup="java:global/MyEarName/MyWebModuleName/BeanImplementation!package.ejb.morepackages.BeanImplementation")
private MyBeanInterface myBean;
This didn't work, it looks like Spring doesn't see the #EJB annotation and it gives an error at deploy time saying it doesn't find any Autowire candidate. So I added the following code:
#Autowired
#Qualifier("BeanImplementation")
public void setMyBean(MyBeanInterface myBean) {
this.myBean = myBean;
}
And on my bean implementation:
#Component("BeanImplementation")
#Stateless(mappedName = "BeanImplementation", name = "BeanImplementation")
#LocalBean
public class BeanImplementation implements MyBeanInterface {
It worked, but I need to use the lookup string of the EJB and I can't since Spring doesn't see #EJB. I was forced to revert to a non-Spring application to use #EJB(lookup="...").
So, to clarify the question: how do I inject an EJB in Spring MVC using annotations and using the EJB lookup string? Thanks.

In dotnet mvc 5, how to inject a service into a view?

In dotnet core mvc,i can inject a service into a view by using #inject directive,but how to do this in dotnet mvc 5.It seems that there is no #inject directive in mvc 5.
ASP.NET MVC 5 doesn't have #inject
This keyword only exists in ASP.NET Core.
Work-around using #model
However you can still inject a dependency in the controller and from the controller pass it to the model. #model and #Model can be used freely in the razor page/view.
MyController.cs:
public class MyController : Controller
{
public MyController(IMyDependency dependency)
{
_dependency = dependency;
}
public ActionResult Index()
{
View(new ViewModel
{
Dependency = _dependency
});
}
}
Razor.cshtml:
#model ViewModel
#if (Model.Dependency.CanView)
{
<!-- Put the code here -->
}
It also means you can put a IServiceProvider in the model and resolve directly in the view. However, in terms of separation of concerns, it's not the ideal.

asp.net help page does not show right routes

I am using attribute routes to route actions in controllers, but asp.net generate wrong Help Page
[HttpGet]
[Route("getAll")]
[AllowAnonymous]
public IHttpActionResult GetCategories(){...}
But the result is
Set up your config to use attribute routing.
public static class WebApiConfig
{
public static void Configure(HttpConfiguration configuration)
{
//the following config sets up your routing mechanism to use attributes
configuration.MapHttpAttributeRoutes();
}
}

How to write 2 controllers in spring MVC

Is it possible that spring MVC contain 2 controllers like DispatherServet write more than one time
when we developing spring MVC applications.
Yes..!! It is Possible.
You have to set a #RequestMapping annotation at the class level the value of that annotation will be the prefix of all requests coming to that controller.
Example:
For 1st Controller :
#Controller
#RequestMapping("test")
public class TestController {
}
For 2nd Controller :
#Controller
#RequestMapping("demo")
public class DemoController {
}
If both the controller have the same/different methods you can access like this
<your server>/test/<RequestMappingName of Method>
<your server>/demo/<RequestMappingName of Method>

How should look configuration for multiple controllers in Spring MVC?

I have 2 logical items News and Cars. For each of them I need to have separate controllers. How I should configure my application.
If youre using annotation based configuration, you can simply create 2 Classes that are annotated with #Controller, like:
package com.example.controllers;
#Controller
public class NewsController {
#RequestMapping(value = "/news")
public String handleNewsCall() {
...
}
}
and
package com.example.controllers;
#Controller
public class CarsController {
#RequestMapping(value = "/cars")
public String handleCarsCall() {
...
}
}
Don't forget to add the following lines to your spring xml if you use annotation based configuration.
<context:component-scan base-package="com.example" />
<mvc:annotation-driven />

Resources