Thymeleaf can't view anything except one page - java

All I can is viewing index.html, but when I am trying to surf to adminLogin for example all i see is:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
There was an unexpected error (type=Not Found, status=404).
here is PortfolioApplication:
#SpringBootApplication
public class PortfolioApplication {
public static void main(String[] args) {
SpringApplication.run(PortfolioApplication.class, args);
}
#GetMapping("/")
public String getMainPage() {
return "index.html";
}
#GetMapping("/adminLogin")
public String getAboutPage() {
return "adminLogin.html";
}
}
when i am trying to call another pages from index.html nothing happens:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hotel_Management_java_project</title>
<link rel="stylesheet" href="css/home.css">
</head>
<body>
<div class="home" id="home">
<nav>
<div class="logo">
<a href="#">
<h2>TourAgency</h2>
</a>
</div>
<div class="header_content">
<ul>
<li>Главная</li>
<div class="login">
<button class="loginbtn" id="loginbtn">Вход</button>
<div class="Login_content">
<a th:href="#{/adminLogin}">Вход для админа</a>
<a th:href="#{/employeelogin}">Вход для работника</a>
<a th:href="#{/userlogin}">Вход для пользователя</a>
</div>
</div>
</ul>
</div>
</nav>
</body>
</html>
UserController:
#RestController
#RequestMapping("/users")
public class UserController {
#Autowired
private UserRepository urepo;
#RequestMapping("/")
public String index() {
return "index";
}
#RequestMapping("/userlogin")
public String index1(Model model) {
model.addAttribute("user", new User());
return "userlogin";
}
I was trying change #Controller to #RestController, putting my main class to up and so on, but i've got no result

Related

How can I get a response in the same View using SpringBoot?

I'm making a simple SpringBoot app that returns a word inserted by the user via a form. I managed to get the response in another view (the form is in home.html, the answer in answer.html) but now I want to get the response in the "home" view. I tried to adapt the code from the two-view version, but it doesn't work. Any thoughts? Thanks!
the HTML view:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Add a word</title>
</head>
<body>
<th:form action="/" object="word" method="POST">
<label>Dictionary - Add a word</label>
<br>
<input name="value">
<br>
<button type="submit">Submit</button>
</th:form>
<p th:text="${value}"></p>
</body>
</html>
The controller:
#RestController
public class Controller {
#GetMapping("/")
public ModelAndView home() {
return new ModelAndView("home", "word", new Word());
}
#PostMapping("/")
public ModelAndView home(#ModelAttribute("word") Word w, Model model) {
ModelAndView mAv = new ModelAndView("home", "word", model);
model.addAttribute("value", w.getValue());
return mAv;
}
}

How to display search results MVC

I'm a beginner and I came across an anomaly that I cant comprehend. From my point of view everything seems to be fine but I keep getting the same empty response when I perform a search in my MVC WebApp.
Take a look at my code. Any help would be greatly appreciated.
MY CONTROLLER
#Controller
public class ControllerACP {
#RequestMapping("/search")
public String Homea(Model model, #RequestParam(name = "query") String search) {
model.addAttribute("clients", clientRepository.search(search));
System.out.println(clientRepository.search(search)); // TO DISPLAY CONTENT ON CONSOLE
System.out.println(search); // ALSO DISPLAY CONTENT ON CONSOLE
return "search";
}
}
MY REPOSITORY
public interface ClientRepository extends CrudRepository<Client, Integer> {
#Query(value = "select * from client where name LIKE ('%:?%')", nativeQuery = true)
Iterable <Client> search(String search);
}
MY HTML FILE
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SEARCH</title>
<meta content="Dashboard" property="og:title">
<meta content="Dashboard" property="twitter:title">
<meta content="width=device-width, initial-scale=1" name="viewport">
<meta content="Webflow" name="generator">
<link href="css/normalize.css" rel="stylesheet" type="text/css">
<link href="css/webflow.css" rel="stylesheet" type="text/css">
<link href="css/ui-login-teste.webflow.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="w-container">
<h1>Search results</h1>
<form action="/search" class="w-form">
<input type="search" class="w-input" autofocus="true" maxlength="256" name="query" placeholder="Search…" id="search">
<input type="submit" value="Search" class="w-button">
</form>
</div>
<div class="w-container" th:each="client, interator: ${clients}">
<a th:href="#{/crud-cliente/pagina-do-cliente/{id}(id=${client.id})}" class="table-content-link w-inline-block">
<div class="valida-table-field foto" >
<div class="table-image-wrapper avatar" th:style="'background-image: url('+#{${'/uploads/' + client.foto}}+')'"></div>
</div>
<div class="valida-table-field nome-admin" >
<div class="_20px" th:text="${client.name}">Nome Completo</div>
</div>
<div class="valida-table-field categoria _6">
<div class="_20px">[[${client.phone}]]</div>
</div>
<div class="valida-table-field categoria _6">
<div class="_20px">[[${client.email}]]</div>
</div>
<div class="valida-table-field categoria _6">
<div class="_20px">[[${client.creation_date}]]</div>
</div>
</a>
</div>
</body>
</html>
You can try this query:
#Query(value = "select * from client where name LIKE :search", nativeQuery = true)
Iterable <Client> search(#Param("search") String search);
I suggest you debug your code and run the query separately in SSMS. Then alter your query and finalize the one where you get your desired output.
Your query should have the searched text between %%. Something Like
#Query(value = "select * from client where name LIKE ('%"+ searchedText +"%')", nativeQuery = true)
I hope it helps.

How to fix "Exception evaluating SpringEL expression" error after submitting a variable Spring/Thymeleaf

I am using Spring Boot/Thymeleaf to create a form that accepts an email address, redirects to a results page that displays the accepted email and sends it to a third party API (authenticated with Oauth2). I am having trouble with the form portion, I am attempting to use Thymeleaf to accept the input to display it on the result.html page. I am receiving an error when trying to display it on the results page, full error is:
[THYMELEAF][http-nio-8080-exec-4] Exception processing template "result.html": Exception evaluating SpringEL expression: "signup.email" (template: "result.html" - line 10, col 4)
I was attempting to follow the examples provided here:
https://spring.io/guides/gs/handling-form-submission/
I have attempted to modify the controller from #PostMapping and #GetMapping to #RequestMapping and add commenting described in a workaround such as:
<!--/*#thymesVar id="signup" type="com.mainconfig.controller1"*/-->
Here is the signup.html code containing the form:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html>
<head>
<title>My Jmml</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body style="background-color: #2B2B2B">
<br /><br />
<h2 style="text-align:center">Contact Information</h2>
<!-- Input Form -->
<!--/*#thymesVar id="signup" type="com.mainconfig.controller1"*/-->
<form action="#" th:action="#{/signup}" th:object="${signup}" method="post">
<div align="center">
<label>Email Address</label><br /><br />
<!--/*#thymesVar id="email" type="String"*/-->
<input type="text" th:field="*{email}" placeholder="Email" required />
<br />
<br />
<input class="submitbutton" type='submit' value='Submit'/>
<br />
</div>
</form>
</body>
</html>
Results page that should display the email (result.html):
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thank you for your submission!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Thank you for your submission!</h1>
<p th:text="'Email: ' + ${signup.email}" />
Submit another message
</body>
</html>
Controller:
#Controller
public class controller1 {
#RequestMapping (value = "/home")
public String home(Model model) {
return "index.html";
}
#RequestMapping(value = "/signup", method= RequestMethod.GET)
public String signupForm(Model model) {
model.addAttribute("signup", new emailInput());
return "signup.html";
}
#RequestMapping(value = "/signup", method= RequestMethod.POST)
public String signupSubmit(#ModelAttribute("email") emailInput email) {
return "result.html";
}
}
Expected output should be the email variable displayed on the results page after it being gathered in the signup form.
If you have a recommendation on how to better do what I am attempting, I am open to suggestions! I am very new to Spring/Thymeleaf but have had experience with Java/Jsp. Thank you for any help, please let me know if you need anything else to help!
Hopefully this will be a starting point for you.
Make sure you place the html files under /resources/templates.
I changed a bit your signup html and result.html as follows, they are still not perfect(avoid using inline styles and use an external stylesheet!):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title>My Jmml</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body style="background-color: #2B2B2B">
<br /><br />
<h2 style="text-align:center">Contact Information</h2>
<!-- Input Form -->
<!--/*#thymesVar id="signup" type="com.mainconfig.controller1"*/-->
<form th:action="#{/signup}" th:object="${signup}" method="post">
<div align="center">
<label>Email Address</label><br /><br />
<!--/*#thymesVar id="email" type="String"*/-->
<input type="text" th:field="*{email}" placeholder="Email" />
<br />
<br />
<input class="submitbutton" type="submit" value="Submit"/>
<br />
</div>
</form>
</body>
and the result.html looks like this
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title>Thank you for your submission!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Thank you for your submission!</h1>
<p th:text="'Email: ' + ${email}" />
Submit another message
</body>
</html>
I also created a form object, add additional fields here if you want
public class SignUpForm {
//you can put some annotations here if you want for validating the email
//for e.g #NotEmpty or a #Pattern(regexp to validate the email)
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
and in the end your Controller. I pass the email from the signup post request to the result.html via a flash attribute:
#Controller
public class Controller1 {
#RequestMapping(value = "/signup", method= RequestMethod.GET)
public String signupForm(#ModelAttribute("signup") SignUpForm form) {
return "/signup";
}
#RequestMapping(value = "/signup", method= RequestMethod.POST)
public String signupSubmit(#ModelAttribute("signup") SignUpForm form, RedirectAttributes redirectAttributes) {
//validate form first -> check bindingResult documentation
//do what you need with your form object
redirectAttributes.addFlashAttribute("email", form.getEmail());
return "redirect:/result";
}
#RequestMapping(value = "/result", method= RequestMethod.GET)
public String result() {
return "/result";
}
}

Scribe with QTIWorks

I'm using scribe to connect with QTIWorks
I found this question How to create a oAuth request using java?
I write this QTIWorks class
package testscribe;
import org.scribe.builder.api.DefaultApi10a;
import org.scribe.model.Token;
import org.scribe.model.Verb;
public class QTIWorks extends DefaultApi10a {
#Override
public Verb getRequestTokenVerb()
{
return Verb.GET;
}
#Override
public String getRequestTokenEndpoint() {
return "https://webapps.ph.ed.ac.uk/qtiworks-dev2/lti/domainlaunch";
}
#Override
public String getAccessTokenEndpoint() {
return "none";
}
/*#Override
public String getAuthorizationUrl(Token requestToken) {
return "none";*/
#Override
public String getAuthorizationUrl(Token token) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
and this is Main class
package testscribe;
import org.scribe.builder.ServiceBuilder;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;
public class Main {
public static void main(String[] args){
OAuthService service = new ServiceBuilder().provider(QTIWorks.class).apiKey("gmail.com/zeina.helwani").apiSecret("v6wPuluQXPwX3vva71ZpR7i1fsbGPaT6")
.scope("API.Public").build();
Token requestToken = service.getRequestToken();
OAuthRequest request = new OAuthRequest(Verb.POST,"https://webapps.ph.ed.ac.uk/qtiworks-dev2/lti/domainlaunch");
service.signRequest(requestToken, request);
Response response = request.send();
System.out.println(response.getBody());
}
}
but it is give me this error
Exception in thread "main" org.scribe.exceptions.OAuthException: Response body is incorrect. Can't extract token and secret from this: '
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>QTIWorks - Method Not Allowed (HTTP Error 405)</title>
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:400,400italic,700,700italic|Ubuntu:500">
<link rel="stylesheet" href="/qtiworks-dev2/lib/960/reset.css">
<link rel="stylesheet" href="/qtiworks-dev2/lib/960/text.css">
<link rel="stylesheet" href="/qtiworks-dev2/lib/fluid960gs/grid.css">
<link rel="stylesheet" href="/qtiworks-dev2/includes/qtiworks.css?v=1.0-SNAPSHOT">
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="/qtiworks-dev2/includes/qtiworks.js?v=1.0-SNAPSHOT"></script>
<!--[if lt IE 9]><script src="/qtiworks-dev2/lib/html5shiv.min.js"></script><![endif]-->
</head>
<body class="page">
<div class="container_12">
<header class="pageHeader">
<h1>QTIWorks</h1>
</header>
<h2>Method Not Allowed (HTTP Error 405)</h2>
<p>You used an HTTP method which is not allowed here.</p><h3>Further Details</h3>
<strong>Message:</strong> Request method 'GET' not supported<br>
<strong>Status Code:</strong> 405<br>
<strong>Request URI:</strong> /qtiworks-dev2/lti/domainlaunch<br>
<div class="clear"></div>
<footer>
<div class="logos">
<img src="/qtiworks-dev2/includes/images/jisc75.png" width="75" height="50" alt="JISC Logo" />
<img src="/qtiworks-dev2/includes/images/uoe.png" width="60" height="60" alt="University of Edinburgh Logo" />
</div>
<div class="copyright">
<p>
QTIWorks 1.0-SNAPSHOT ‒ Release notes
</p>
<p>
Copyright © Thu Apr 09 13:16:35 BST 2015
The School of Physics and Astronomy,
The University of Edinburgh.
</p>
<p>
Contact: David McKain
</p>
<p>
The University of Edinburgh is a charitable body, registered in Scotland,
with registration number SC005336.
</p>
</div>
</footer>
</div>
</body>
</html>
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:41)
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:27)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:64)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:40)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:45)
at testscribe.Main.main(Main.java:24)
Java Result: 1
I think this url "https://webapps.ph.ed.ac.uk/qtiworks-dev2/lti/domainlaunch" is invalid, but I don't know what I should use.

How to create multi layout in Spring MVC

I know about Apache Tiles in Spring, it seem working same jsp:include, but it doesn't solve my problem:
I want a file with name is layout1.jsp, in this file, I will define a layout like:
<html>
<head>
<style href="style1.css" />
</head>
<body>
<div class="main">
<div class="left">
<ul>
<li>
<li>
<li>
</ul>
</div>
<div class="content">
<h1>${message }</h1>
</div>
<div class="footer">
<span>This is footer</span>
</div>
</div>
</body>
</html>
And a file is layout2.jsp:
<html>
<head>
<style href="style2.css" />
</head>
<body>
<div class="main">
<div class="left2">
<ul>
<li>
<li>
<li>
</ul>
</div>
<div class="content2">
<h1>${message }</h1>
</div>
<div class="footer2">
<span>This is footer</span>
</div>
</div>
</body>
</html>
When user chose layout name on combobox, controller will set layout dynamic before render layout.
How should I do?
For switching the css file an you could use the Spring Theme Resolver. And you can use the same mechanism to change some small parts of your html (like the div classes)
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<style href="<spring:theme code='styleSheet'/>" />
</head>
<body>
...
<div class="<spring:theme code='contentClass'/>">
<h1>${message }</h1>
</div>
...
</body>
</html>
(But I would recommend to use the same html with same classes and just switch the css).
Do not forget to setup the theme resolver!
#See Spring Reference: Chapter Using themes
I found a method to solve this problem:
My application separator to multi module, example "Admin", "Default", each module have a interceptor, example a module interceptor:
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
String servletPath = request.getServletPath();
if (!servletPath.equals("/") && servletPath.substring(servletPath.length() - 1).equals("/")) {
response.sendRedirect(request.getContextPath() + servletPath.replaceAll("\\/+$", ""));
return false;
}
return true;
}
In view I have a class InternalResourceViewResolver.java:
package view;
import helper.AppHelper;
import java.util.Locale;
import org.springframework.web.servlet.View;
public class InternalResourceViewResolver extends
org.springframework.web.servlet.view.InternalResourceViewResolver {
public View resolveViewName(String viewName, Locale locale)
throws Exception {
AppHelper.setPage("../" + AppHelper.getModule() + "/" + viewName + ".jsp");
return super.resolveViewName("layout/" + AppHelper.getLayout(), locale);
}
}
AppHelper class:
package helper;
public class AppHelper {
private static String module = "default";
private static String layout = "main";
private static String page = "index";
public static String getModule() {
return module;
}
public static void setModule(String module) {
AppHelper.module = module;
}
public static String getLayout() {
return layout;
}
public static void setLayout(String layout) {
AppHelper.layout = layout;
}
public static String getPage() {
return page;
}
public static void setPage(String page) {
AppHelper.page = page;
}
}
In other module, example for Admin:
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("ServletPath" + request.getServletPath());
AppHelper.setModule("admin");
AppHelper.setLayout("admin");
return true;
}
And my view page:
In layout:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="<c:url value="/resources/css/main.css" />" rel="stylesheet">
<title>Welcome to web</title>
</head>
<body>
<div class="wrapper">
<div class="main">
<div class="header"></div>
<div class="content">
<div class="content-left">
<jsp:include page="<%=helper.AppHelper.getPage() %>"></jsp:include>
</div>
<div class="content-right"></div>
</div>
<div class="footer"></div>
</div>
</div>
</body>
</html>
Placeholder page:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<h1>${message }</h1>
<h2>${welcome }</h2>
<c:forEach items="${batches }" var="batch">
${batch.id } - ${batch.name }
</c:forEach>
Here directory struct:
- src\main\webapp\WEB-INF\pages
- admin
- index
- index.jsp
- setting.jsp
- product
- index.jsp
- detail.jsp
- other
...
- default
- index
- index.jsp
- contact.jsp
- product
...
- layout
admin.jsp
main.jsp
You could do this using Tiles too ...
use apache-tiles 2.2.1 or above
In application's tiles.xml where you put layout models do this
<definition name="masterTile" templateExpression="${requestScope.layout} >
<put-attribute name="title" value="" />
<put-attribute name="header" value="/view/header.jsp" />
<put-attribute name="menu" value="/view/menu"/>
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/view/footer.jsp"/>
</definition>
For more on this refer here Tiles Expression Language Support

Categories

Resources