Template might not exist or might not be accessible by any of the configured Template Resolvers springboot - spring-boot

I have a microservice app built-in spring boot, the main module is working at 8080 port and the other module is working at 7070 port. At /clicker endpoint I'm trying to redirect to
the site which is located on this port but always when I'm using /clicker endpoint I can see an error like this. But when I try to get [http://192.168.254.115:7070] directly from the browser, everything is working fine so I think that's not because of the bad config in the application.properties.
Error resolving template [http://192.168.254.115:7070], template might not exist or might not be accessible by any of the configured Template Resolvers
This controller works at 8080 port.
#CrossOrigin(origins = "*")
public class MainController {
#RequestMapping("/")
public String index() {
return "redirect:/login";
}
#RequestMapping("/home")
public String home(){
return "home.html";
}
#CrossOrigin
#RequestMapping("/clicker")
public ModelAndView goToClicker(HttpServletRequest request) {
//http://localhost:7070/
//http://192.168.254.115:7070/
String url = "http://" + request.getServerName() + ":" + "7070";
return new ModelAndView(url);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
<link rel="stylesheet" type="text/css" th:href="#{/styles/style.css}"/>
</head>
<body>
<div class = "main">
<div class = "container">
<button type="button">CLICKER</button>
</div>
</div>
</body>
</html>
And that's the controller which works at 7070 port.
#Controller
#CrossOrigin(origins = "*")
public class ClickerController {
#CrossOrigin
#RequestMapping("/")
public String index() {
return "clicker.html";
}
}

Related

Showing input parameter on same page in Thymeleaf

I am trying to show the results on the same page as the form in Thymleaf and Spring and this is what I have tried till now:
Controller:
#Controller
public class ThymeleafController {
#GetMapping("/hello")
public String getHello() {
return "hello";
}
#PostMapping("/test")
public String test(#RequestParam("text1")String str, Model model) {
model.addAttribute("sample", str);
return "test";
}
}
test.html page:
<!DOCTYPE html>
<html xmlns:th ="http://www.thymeleaf.org" >
<head>
<meta charset ="UTF-8" ></meta>
<title> Hello World</title>
</head>
<body>
<h1> Hello World</h1>
<form method ="post" action ="/test" >
Enter: <input type ="text" name ="text1" />
<input type ="submit" value ="click" />
</form>
<span th:text ="${sample == null} ? 'null' : ${sample}" ></span>
</body>
</html>
When i go on test page i see this error:
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
Can someone give me an ideea or an example how I could display a value on the same page as the form / input ? Thanks
Ref : https://hellokoding.com/handling-form-submission-example-with-java-spring-boot-and-freemarker/
Add for get , so this issue will get solved.
#Controller
public class ThymeleafController {
#GetMapping("/hello")
public String getHello() {
return "hello";
}
#GetMapping("/test")
public String testfrm() {
return "test";
}
#PostMapping("/test")
public String test(#RequestParam("text1")String str, Model model) {
return "test";
}
}

HttpStatus 406 "not acceptable" when returning Flux<String> on Spring 4.3.7 MVC Controller to a EventSource in html page

Im trying to make a timer of how much time a page is open via spring webflux, i had made this example work on springboot but with spring mvc is not working, so i know the code does work. may i have to set up something im not aware of?
Controller:
#Controller
public class HomeController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(){
return "home";
}
#RequestMapping(value = "/timer", method = RequestMethod.GET, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public #ResponseBody Flux<String> startTimer(){
Instant startTime = Instant.now();
return Flux.fromStream(
Stream.generate(() -> calculateTimeMethod(startTime, Instant.now()))
).delayElements(Duration.ofSeconds(1));
}
}
JSP home.jsp :
<html>
<head>
<title> Home </title>
</head>
<body>
<label> tiempo trascurrido </label>
<label id="timer"></label>
<script>
var eventSource = new EventSource("url/timer");
eventSource.onmessage = function ( event ) {
document.getElementById("timer").innerText = event.data;
};
</script>
</body>
</html>
home page load but timer doesnt start, console output shows: Failed to load resource: the server responded with a status of 406 (No Aceptable)

How to enter angular4 pages from spring mvc

I have angular4 + spring mvc project here is my project hierarchy
my index.html content
<!DOCTYPE html><html lang="en"><head>
<meta charset="utf-8">
<title>MonitoringFront</title>
<base href="./">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
<script type="text/javascript" src="runtime.js"></script><script type="text/javascript" src="polyfills.js"></script><script type="text/javascript" src="styles.js"></script><script type="text/javascript" src="vendor.js"></script><script type="text/javascript" src="main.js"></script></body></html>
and my web Configuration class
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "ge.mvc"})
public class WebMvcConfig implements WebMvcConfigurer {
#Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/monitoringFront");
return resolver;
}
}
and when I want to enter my pages for example login page which is my default page I am getting page not fount error when i am trying to enter http://localhost:8080/springMvcApp/ url . Did I do something wrong ?
my router urls from angular 4 app.module.ts file
const appRoutes:Routes = [
{
path: '',
component: LoginComponent
},
{
path: 'dashboard',
component: DashboardComponent
}
]
I considere that your problem is equals with this question, because you want to render only de angular application,
How to serve .html files with Spring
In my point of view you need to split the problems to have a better architecture in one side you need your front end using angular 5 and in the other side spring mvc to create rest services, and also you probably will need JWT for authentication.

Handling MultipartException with Spring Boot and display error page

I have a very simple file upload set up with Spring Boot.
I was wondering if there was an easy way to display an error page when the maximum file size is exceeded.
I have uploaded a very simple example of what I'm trying to achieve on github.
Basically, the idea is to catch the MultipartException in a global Spring exception handler:
#ControllerAdvice
public class UploadExceptionHandler {
#ExceptionHandler(MultipartException.class)
public ModelAndView handleError(MultipartException exception) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("error", exception.getMessage());
modelAndView.setViewName("uploadPage");
return modelAndView;
}
}
The controller which handles the file upload is really simple:
#RequestMapping("/")
public String uploadPage() {
return "uploadPage";
}
#RequestMapping(value = "/", method = RequestMethod.POST)
public String onUpload(#RequestParam MultipartFile file) {
System.out.println(file.getOriginalFilename());
return "uploadPage";
}
And the uploadPage.html thymeleaf template associated with it too:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Upload</title>
</head>
<body>
<div style="color: red" th:text="${error}" th:if="${error}">
Error during upload
</div>
<form th:action="#{/}" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file"/>
<button type="submit" name="save">Submit</button>
</form>
</body>
</html>
The idea is to display an error message in the same upload page when the file is too big.
It was my understanding that one would configure Spring's MultipartResolver to resolve exceptions lazily and be able to catch those exceptions at Spring's level (MVC exception handlers) but this code does not seem to help:
#Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
public StandardServletMultipartResolver multipartResolver() {
StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
multipartResolver.setResolveLazily(true);
return multipartResolver;
}
So before I resort to extreme measures like a filter or extending the MultipartResolver...
Do you know a clean way to handle those exceptions with Spring MVC?
Answer
Thanks to #rossen-stoyanchev.
Here is what I ended up doing:
#RequestMapping("uploadError")
public ModelAndView onUploadError(HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView("uploadPage");
modelAndView.addObject("error", request.getAttribute(WebUtils.ERROR_MESSAGE_ATTRIBUTE));
return modelAndView;
}
#Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return container -> container.addErrorPages(new ErrorPage(MultipartException.class, "/uploadError"));
}
Works like a charm and feels like an elegant solution.
I updated the project on github if someone is interested.
Many thanks!
Multipart request parsing happens before a handler is selected and hence there is no #Controller and therefore no #ControllerAdvice to speak of yet. You can use an ErrorController (see http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-error-handling) for that.
BTW you don't need #RequestParam. It's enough that the argument type is MultipartFile.

Keep getting 401 (Authorization Required) with spring social twitter

I've been trying this Spring Social Accessing Twitter Data guide. And though I've double, triple an so on checked everything I keep getting this error when I click "Connect to Twitter" button:
POST request for "https://api.twitter.com/oauth/request_token" resulted in 401 (Authorization Required); invoking error handler
Here is my code:
src/main/resources/templates/connect/twitterConnect.html
<html>
<head>
<title>Hello Twitter</title>
</head>
<body>
<h3>Connect to Twitter</h3>
<form action="/connect/twitter" method="POST">
<div class="formInfo">
<p>You aren't connected to Twitter yet. Click the button to connect this application with your Twitter account.</p>
</div>
<p><button type="submit">Connect to Twitter</button></p>
</form>
</body>
src/main/resources/templates/connect/twitterConnected.html
<html>
<head>
<title>Hello Twitter</title>
</head>
<body>
<h3>Connected to Twitter</h3>
<p>
You are now connected to your Twitter account.
Click here to see your Twitter friends.
</p>
</body>
src/main/resources/templates/hello.html
<html>
<head>
<title>Hello Twitter</title>
</head>
<body>
<h3>Hello, <span th:text="${twitterProfile.name}">Some User</span>!</h3>
<h4>These are your friends:</h4>
<ul>
<li th:each="friend:${friends}" th:text="${friend.name}">Friend</li>
</ul>
</body>
src/main/java/hello/HelloController.java
#Controller
#RequestMapping("/")
public class HelloController {
private Twitter twitter;
private ConnectionRepository connectionRepository;
#Inject
public HelloController(Twitter twitter, ConnectionRepository connectionRepository) {
this.twitter = twitter;
this.connectionRepository = connectionRepository;
}
#RequestMapping(method=RequestMethod.GET)
public String helloTwitter(Model model) {
if (connectionRepository.findPrimaryConnection(Twitter.class) == null) {
return "redirect:/connect/twitter";
}
model.addAttribute(twitter.userOperations().getUserProfile());
CursoredList<TwitterProfile> friends = twitter.friendOperations().getFriends();
model.addAttribute("friends", friends);
return "hello";
}
}
src/main/java/hello/Application.java
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application {
/*
* SPRING BOOTSTRAP MAIN
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I ran into the same problem.
After some investigation I found out the problem is in the callback url. Spring social sets this to yourap/signin/twitter. For facebook and linkedin this is fine, but for some reason twitter nees a filled in callback url in the application settings as well.
So the solution: Go to your twitter application settings, and fill in a callback url (this doesn't even have to be the actual callback url your going to use, just fill in any url!). Most likely this is the cause of your problems.
What does your application.properties file look like? It should have entries for spring.social.twitter.appId and spring.social.twitter.appSecret, populated with values you get when registering your application with Twitter.
Be sure that you have those in application.properties and that there are no curly-braces around the values (the guide's text shows curly-braces, but those are meant as placeholders, not something you should actually have in application.properties).

Resources