Spring Boot ignores CSS / JS when loading page - java

My page (order.mustache) uses several CSS styles (external and local), images, background video and JS element. Most of the page layout is described in style.css, which is located in the 'resourses/static/css' directory.
When I start a page through Chrome as an HTML document, it displays correctly. But if I run it through Spring Boot (as a mustache page) - all local styles, images, JS and even youtube videos are ignored.
The browser console indicates an error 'Resource interpreted as Stylesheet but transferred with MIME type text / html:' http: // localhost: 8080 / static / css / style.css'.' On the Response tab of the Chrome developer panel, style.css is displayed as a copy of the order.mustache page. On the Headers tab, its type is text / html.
I can’t understand at what point these changes are happening, and what should I change so that the page works properly.
HTML:
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>...</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link href="../static/css/style.css" type="text/css" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Roboto:400,300,100,500,700,900' rel='stylesheet' type="text/css">
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
</head>
Controller:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Date;
import java.util.Map;
#Controller
public class GreetingController {
#Autowired
private ClientRepo repo;
#GetMapping
public String main(Map<String, Object> model) {
Iterable<Client> clients = repo.findAll();
model.put("clients", clients);
return "order";
}
#PostMapping
public String add(#RequestParam String firstName, #RequestParam String lastName, #RequestParam String nationality,
#RequestParam String sex, #RequestParam Date birthDate, #RequestParam long passNumber, Map<String, Object> model) {
Client client = new Client(firstName, lastName, nationality, sex, birthDate, passNumber);
repo.save(client);
Iterable<Client> clients = repo.findAll();
model.put("clients", client);
return "order";
}
}
Main:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public ViewResolver getViewResolver(ResourceLoader resourceLoader) {
MustacheViewResolver mustacheViewResolver
= new MustacheViewResolver();
mustacheViewResolver.setPrefix("templates/");
mustacheViewResolver.setSuffix(".mustache");
mustacheViewResolver.setCache(false);
return mustacheViewResolver;
}

Try to swap
<link href="../static/css/style.css" type="text/css" rel="stylesheet">
Maybe your custom styles cannot load after bootstrap.
Do like that :
<!-- My styles firstly -->
<link href="../static/css/style.css" type="text/css" rel="stylesheet">
<!-- And then bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link href='http://fonts.googleapis.com/css?family=Roboto:400,300,100,500,700,900' rel='stylesheet' type="text/css">
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

Related

How to handle refreshing of page in springboot facebook integration?

I am trying to implement facebook based sign in . Everything works however i don't know how to handle the refresh case that is once a user is redirected to the page how and the user clicks on refresh it triggers another request , how do i handle that ?
package com.example.demo.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import com.example.demo.FbService.FbService;
#Controller
#RequestMapping("/")
public class FbController {
#Autowired
private FbService facebookService;
#GetMapping("/createFacebookAuthorization")
public RedirectView createFacebookAuthorization(){
return new RedirectView(facebookService.createFacebookAuthorizationURL());
}
#GetMapping("/facebook")
public String createFacebookAccessToken(#RequestParam("code") String code){
String accToken=facebookService.createFacebookAccessToken(code);
Object obj=facebookService.getName(accToken);
return "details";
}
#RequestMapping("/")
public ModelAndView firstPage() {
return new ModelAndView("welcome");
}
}
package com.example.demo.FbService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.impl.FacebookTemplate;
import org.springframework.social.facebook.connect.FacebookConnectionFactory;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Operations;
import org.springframework.social.oauth2.OAuth2Parameters;
import org.springframework.stereotype.Service;
#Service
public class FbService {
#Value("${spring.social.facebook.appId}")
String facebookAppId;
#Value("${spring.social.facebook.appSecret}")
String facebookSecret;
public String createFacebookAuthorizationURL(){
FacebookConnectionFactory connectionFactory = new FacebookConnectionFactory(facebookAppId, facebookSecret);
OAuth2Operations oauthOperations = connectionFactory.getOAuthOperations();
OAuth2Parameters params = new OAuth2Parameters();
params.setRedirectUri("http://localhost:8080/facebook");
params.setScope("public_profile,email");
return oauthOperations.buildAuthorizeUrl(params);
}
public String createFacebookAccessToken(String code) {
FacebookConnectionFactory connectionFactory = new FacebookConnectionFactory(facebookAppId, facebookSecret);
AccessGrant accessGrant = connectionFactory.getOAuthOperations().exchangeForAccess(code, "http://localhost:8080/facebook", null);
return accessGrant.getAccessToken();
}
public Object getName(String accessToken) {
Facebook facebook = new FacebookTemplate(accessToken);
String[] fields = {"id", "name","email"};
return facebook.fetchObject("me", String.class, fields);
}
}
details.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Login</title>
</head>
<body>
<div style="border: 1px solid #ccc; padding: 5px; margin-bottom: 20px;">
Welcome
</div>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Login</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width" />
<base href="/" />
<link rel="stylesheet" type="text/css" href="/webjars/bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" href="/webjars/font-awesome/css/font-awesome.min.css"></link>
</head>
<body>
<div style="border: 1px solid #ccc; padding: 5px; margin-bottom: 20px;">
Validate using Facebook |
</div>
</body>
</html>
The starting page which sends the request
The redirected page which works fine
The error that appears after refresh is done
I know why it is coming but don't know what would be the solution to prevent it .
Any help would be appreciated .

Spring MVC Scala App just returns index.html page rest of the routes doesn't work

I am trying to create a simple spring MVC app in Scala I did define my methods in the controller to bring back html pages based on name from resources folder but it just always brings back just index page and the rest of html pages while trying to access the route it just fails, but same application works fine in Java.
full source code is here:-
Java:-
https://github.com/kali786516/SpringConfigServer-client/tree/master/src/main/java/com/example/SpringConfigServerclient
Scala:-
https://github.com/kali786516/SpringConfigServer-client/tree/master/src/main/scala/com/ps/spring/mvc/psbankapp
Error in Scala:-
Index html Works Fine:-
but rest of the routes doesn't work in scala
Scala controller:-
package com.ps.spring.mvc.psbankapp.controllers
import org.springframework.beans.factory.annotation.Value
import org.springframework.cloud.context.config.annotation.RefreshScope
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestMethod
//#RefreshScope
#Controller
//#ComponentScan(basePackages = Array("com.ps.spring.mvc.psbankapp"))
class AccountController {
#RequestMapping(value = Array("/"))
def showHomePage(): Unit = {
"index"
}
#RequestMapping(value = Array("/new"), method = Array(RequestMethod.GET))
def newAccount(): Unit = {
"newAccount"
}
#RequestMapping(value = Array("/showAccount"))
def showAccount(): Unit = {
"showAccount"
}
}
Java Controller:-
package com.example.SpringConfigServerclient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
#RefreshScope
#Controller
public class RateController {
#RequestMapping(value = "/index",method = RequestMethod.GET)
public String getIndex() {
return "index";
}
#RequestMapping(value = "/new",method = RequestMethod.GET)
public String newAccount() {
return "newAccount";
}
#RequestMapping(value = "/showAccount",method = RequestMethod.GET)
public String showAccount() {
return "showAccount";
}
}
Finally got it working by adding below context in my HTML files.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
Answer:-
Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers
full html if you need:-
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Pluralsight Training: Config Client</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"></link>
</head>
<body>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<h1>Pluralsight Training: Welcome to PS Bank Web Application index</h1>
</div>
<div class="col-md-2"></div>
</div>
</body>
</html>

Angular 1.7.2/Spring Boot - Infinite template loading when include navbar and footer

My project was migrated from Thymeleaf to Angular. Navbar and footer is being included from another files on all pages. What is interesting - navbar/footer works on most of pages, without Home Page, Login Page and Thank You For Register Page. Aforementioned pages don't load navbar/footer (HTML status 302) and we can see fields from login page in the background for a moment. Moreover browser works very slowly and show warning:
WARNING: Tried to load AngularJS more than once.
On the screen we can see navbar and fragment of footer on HomePage because I used Thymeleaf for problematic Login Page temporarily and were loaded they from there.
index.html (Home Page)
<!DOCTYPE html>
<html ng-app="">
<head>
<meta charset="UTF-8" />
<title>MyBoldGoals</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/assets/css/main.css"/>
<link rel="stylesheet" type="text/css" href="/assets/css/styles.css"/>
</head>
<body class="loading">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular-resource.min.js"></script>
<script src="js/home.js"></script>
<div ng-include="'navbar.htm'"></div>
<div id="wrapper">
<div id="bg"></div>
<div id="overlay"></div>
<div id="main">
<header id="header">
<h1>MyBoldGoals</h1>
<p>Set goals • Achieve the objectives • Win</p>
<nav>
<ul>
<li><span class="label">Facebook</span></li>
<li><span class="label">Twitter</span></li>
<li><span class="label">Github</span></li>
</ul>
</nav>
</header>
<footer id="footer">
<span class="copyright">© 2018 Developed by Pawel Dudek </span>
<span class="copyright">© Design: HTML5 UP.</span>
</footer>
</div>
</div>
<div ng-include="'footer.htm'"></div>
</body>
</html>
I think UserController.java cause a problem:
package pl.scartout.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import pl.scartout.model.User;
import pl.scartout.repo.UserRepo;
import pl.scartout.service.UserService;
#Controller
public class UserController {
private UserService userService;
private UserRepo userRepo;
#Autowired
public void setUserService(UserService userService, UserRepo userRepo) {
this.userService = userService;
this.userRepo = userRepo;
}
#GetMapping("/login")
public String login(Model model) {
model.addAttribute("user", new User());
return "login";
}
#PostMapping("/register")
public String addUser(#ModelAttribute #Valid User user,
BindingResult bindResult) {
if(bindResult.hasErrors())
return "login";
else {
if (userRepo.findByUsername(user.getUsername())==null) {
userService.addWithDefaultRole(user);
return "thankyou";
}
else return "login";
}
}
}
HomeController.java
package pl.scartout.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HomeController {
#RequestMapping("/")
public String home() {
return "home";
}
}
Full project may clone from: Link You have to make changes (add ng-app="" because I used Thymeleaf for problematic pages temporarily).
You need to specify ng-app within the <body>. It should be inside of <div> tag within the body. This will tell the app where to load the content. It won't work where you have it now because the scripts are being loaded after you have initiated the app.

How to read data from a NON secured webpage in java(Router or AP)?

Here is my code to get the source from the access point I was trying to poll:
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://x.x.x.x"); //Some valid IP
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
System.out.println("In");
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Here is what I got instead of the desired source code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/x
html1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<link rel="stylesheet" type="text/css" href="_canopy.css" media="screen" />
<link rel="stylesheet" type="text/css" href="_canopypda.css" media="handheld" />
<meta http-equiv='Refresh' content='0; URL=index.htm?mac_esn=0a003e40eb1e' />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta name='viewport' content='width=device-width,initial-scale=1,user-scalable=
no' />
<title>Welcome to Canopy</title>
<script language="javascript" type="text/javascript">
<!--- Hide script from old browsers
function CheckForJS()
{
var d = new Date();
var t = d.getTime();
document.cookie = "JS=true; expires=" + (t+600);
}
// end hiding from old browsers -->
</script>
</head>
<body onload="CheckForJS();">
<p>
Press Here to Continue.
</p>
</body>
</html>
I am trying to access the web gui for this unit to grab its signal strength and store it in a text file. I kind of think the problem is that the gui is not secured by https standards and requires more authorization but it could just be that I am doing the process wrong to begin with. If anyone can help me get the full source of the page or steer me in the right direction of what I need to do, that would be greatly appreciated.
The tag
<meta http-equiv='Refresh' content='0; URL=index.htm?mac_esn=0a003e40eb1e' />
means that a web browser would refresh the page with url index.htm?mac_esn=0a003e40eb1e after 0 seconds, i.e. redirect to that page.
You need to do the same, i.e. parse that line and do another request.

Thymeleaf Template Engine do not follow the expression language

Spring boot Maven dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
#Service
public class MailContentBuilder {
private TemplateEngine templateEngine;
#Autowired
public MailContentBuilder(TemplateEngine templateEngine) {
this.templateEngine=templateEngine;
}
public String build(String templateName,String user,String email) throws IOException {
Context context=new Context();
context.setVariable("user", "Alpha");
context.setVariable("email", "alpha#gmail.com");
String test=templateEngine.process(templateName, context);
return test;
}
}
this is my mail sender method.
MimeMessage mimeMessage=javaMailSender.createMimeMessage();
//mimeMessage.setContent(mailContentBuilder.build("changepassword","alpha","ema il#email.com"), "text/html");
MimeMessageHelper helper=new MimeMessageHelper(mimeMessage);
helper.setTo(auth0UserService.getUser(userid).getEmail());
helper.setFrom(fromUsername);
helper.setSubject("Password Change Confirmation");
helper.setText(mailContentBuilder.build("changepassword","alpha","email#email.com"), true);
javaMailSender.send(mimeMessage);
this is my template, in src/resources/templates
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Change password</title>
</head>
<body >
helloooo th:text="${user}"
</body>
</html>
This is what it sends, it does not follow the expression language, but writes to the page as it is. no use of variables.
helloooo th:text="${user}"
th:text has to be an attribute to an html tag, so something like
<p th:text="helloooo ${user}" />
should work, judging from a glance at http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#using-texts

Categories