Springboot homepage after login - spring

I just want to display the homepage and the users name after login but I keep getting a 404 not found error.
here is the index.html page
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:action="#{/index}">Hello<h1 th: th:text="${name}"></h1> </h1>
</body>
</html>
And here is my controller
#Controller
#AllArgsConstructor
public class UserController {
private final UserService userService;
private final ConfirmationTokenService confirmationTokenService;
#GetMapping("/sign-in")
String signIn() {
return "sign-in";
}
#GetMapping("/sign-up")
String signUpPage(User user) {
return "sign-up";
}
#PostMapping("/sign-up")
String signUp(User user) {
userService.signUpUser(user);
return "redirect:/sign-in";
}
#GetMapping("/sign-up/confirm")
String confirmMail(#RequestParam("token") String token) {
Optional<ConfirmationToken> optionalConfirmationToken = confirmationTokenService.findConfirmationTokenByToken(token);
optionalConfirmationToken.ifPresent(userService::confirmUser);
return "redirect:/sign-in";
}
#RequestMapping(value = {"/index"}, method = RequestMethod.GET)
public String welcome(User user, Model model) {
model.addAttribute("Name", user.getName());
return "index";
}
I've been trying this for a while now and I don't know what I'm doing wrong. The websecurity config is configured so that the default succesuful URL is index.html

Try changing the request mapping to
#RequestMapping(value = {"/index", "/"}, method = RequestMethod.GET)
Also, try calling localhost:9090/index (without the .html) as Eleftheria Stein-Kousathana said.

Related

Getting Error while bootstraping the Spring-boot Application

Well i am developing a spring boot application by choosing view technology as jsp.But when am trying to bootstraping the spring-boot application i am getting white level error page.
Model Class
public class Person {
private String p_first_name;
private String p_last_name;
private int age;
private String city;
private String state;
private String country;
public Person(String p_first_name, String p_last_name, int age, String city, String state, String country) {
super();
this.p_first_name = p_first_name;
this.p_last_name = p_last_name;
this.age = age;
this.city = city;
this.state = state;
this.country = country;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
public String getP_first_name() {
return p_first_name;
}
public void setP_first_name(String p_first_name) {
this.p_first_name = p_first_name;
}
public String getP_last_name() {
return p_last_name;
}
public void setP_last_name(String p_last_name) {
this.p_last_name = p_last_name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Controller Class
#Controller
public class PersonController {
private static ArrayList<Person> persons = new ArrayList<Person>();
static {
persons.add(new Person("kumar", "bikash", 28, "bangalore", "karnataka", "india"));
persons.add(new Person("kumar", "pratap", 24, "delhi", "delhi", "india"));
persons.add(new Person("kumar", "ravi", 29, "delhi", "delhi", "india"));
persons.add(new Person("kumar", "mangalam", 65, "delhi", "delhi", "india"));
}
#RequestMapping(value = { "/", "/index" }, method = RequestMethod.GET)
public String index(Model model) {
String message = "Hello" + "Spring Boot implementation with jsp Page";
model.addAttribute("message", message);
return "index";
}
#RequestMapping(value = "/personList", method = RequestMethod.GET)
public String getPersonList(Model model) {
model.addAttribute("persons", persons);
return "personList";
}
}
application.properties
# VIEW RESOLVER CONFIGURATION
spring.mvc.view.prefix=/WEB-INF/jsp
spring.mvc.view.suffix=.jsp
jsp file
index.jsp
=========
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Integration of Spring Boot with jsp page</title>
</head>
<body>
<h1>Welcome to Spring boot</h1>
<p>This project is an Example of how to integrate Spring Boot with
jsp page.</p>
<h2>${message} </h2>
</body>
</html>
personList.jsp
==============
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Person List content Present here</title>
</head>
<body>
<h1>Person List</h1>
<div>
<table border="1">
<tr>
<th>FirstName:</th>
<th>LasttName:</th>
<th>Age:</th>
<th>city:</th>
<th>State:</th>
<th>Country:</th>
</tr>
<c:forEach items="${persons}" var=person>
<tr>
<td>${person.firstname}</td>
<td>${person.lastname}</td>
<td>${person.age }</td>
<td>${person.city }</td>
<td>${person.state }</td>
<td>${person.country }</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
Error page
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Jun 07 23:41:57 IST 2019
There was an unexpected error (type=Not Found, status=404).
No message available
well please review the below code.Help me to resolve thing where i am
getting wrong?
Are you looking to enable your own errorpage disabling the white level error page? May be this can help you.
If you do not specify any custom implementation in the configuration,
BasicErrorController bean is automatically registered in Spring Boot. You can add your implementation of ErrorController.
#Controller
public class MyErrorController implements ErrorController {
#RequestMapping("/error")
public String handleError() {
//do something like logging
return "error";
}
#Override
public String getErrorPath() {
return "/error";
}
}
1) I would suggest trying the #RestController annotation to make sure that you get at least the JSON response. (Only for Debugging)
2) After the first part is figured out, you can go back to your #Controller annotation and make sure that the string you return in the request mapping method is available as a jsp file. I would recommend trying with a single endpoint initially ("/") and having the appropriate jsp page for it.
3) If it still produces the same issue, you can refer to this post
Spring Boot JSP 404.Whitelabel Error Page
4) You can also disable and customize the default error page by following this link https://www.baeldung.com/spring-boot-custom-error-page

Returning HTML page in a JSON property in Spring Boot conditionally

So I'm in a scenario writing Restful Services where based on request data, I've to return either a short string or HTML page IN A JSON variable. lets say like this:
response {
result : YourRequestedString
}
OR
response {
result : <html>...</html>
}
The decision of what will be returned is on server side.
So, is there a way that I can render my Thymeleaf (or any other maybe plain HTML) templates while I'm in the same controller method (directly or by calling some controller method that returns me the rendered page). That I can send back to the client.
Thanks to #Leffchik I got it working, here's my setup with Thymeleaf so it can help others.
Setup htmlTemplateEngine
#Bean
public TemplateEngine htmlTemplateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(htmlTemplateResolver());
return templateEngine;
}
private ITemplateResolver htmlTemplateResolver() {
final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setResolvablePatterns(Collections.singleton("html/*"));
templateResolver.setPrefix("/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCharacterEncoding("utf-8");
templateResolver.setCacheable(false);
return templateResolver;
}
Here's the html page in src/main/resources/templates/html/hello.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 th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>
RestController goes like this
#RestController
public class TestController {
#Autowired
TemplateEngine htmlTemplateEngine;
#RequestMapping("/testHello")
public ResponseEntity<?> test(#RequestParam(value = "name", required = false, defaultValue = "World") String name) {
final org.thymeleaf.context.Context ctx = new org.thymeleaf.context.Context();
ctx.setVariable("name", name);
// Rendered template in String, You can now return in a JSON property
final String htmlContent = this.htmlTemplateEngine.process("html/hello.html", ctx);
return ResponseEntity.ok().body(htmlContent);
}
}
Hope it helps !
Returning an HTML Page in a REST Api is not encouraged. But if you fancy you can return a ResponseEntity<Response> from your controller.
#GetMapping("/mymethod")
public ResponseEntity<Response> myMethod() {
ResponseEntity responseEntity = null;
if(string) {
responseEntity = new ResponseEntity(getString(), HttpStatus.OK);
} else {
responseEntity = new ResponseEntity(getHtml(), HttpStatus.OK);
}
return responseEntity;
}

Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor'

Trying to change value inside my model class which contains a private String name and I wanted to change the name using Thymeleaf in HTML page then see the change in another url response body.
When I try to access my ("/myname") page in localhost I got the error:
Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor'
Here is my Model:
public class Name {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here is my Controller
#Controller
public class MainController {
#RequestMapping("/name")
#ResponseBody
public String showName() {
Name myname = new Name();
return myname.getName();
}
#RequestMapping("/myname")
public String setName() {
return "myname";
}
#RequestMapping(value = "myname", method = RequestMethod.POST)
public String showName(#ModelAttribute Name iko, BindingResult errors, Model model) {
return "name";
}
}
Here is my html thymeleaf pages:
myname.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1"/>
<title>Insert title here</title>
</head>
<body>
<form action="#" th:action="#{/myname}" th:object="${iko}" method="post">
<label>Enter the name</label><br/>
<input type="text" th:field="*{name}"/>
<button type="submit">SUBMIT</button>
</form>
</body>
</html>

Spring Social with Spring Boot not getting user email id

I am new as developer, trying hands on Spring social facebook integration. Followed this link
I am getting data like user's name', 'gender', 'locale'. Which can be given as constructor value to User class(see took help).
But I want to get user "email-id", somehow that's not possible the way i am getting data for 'name', 'locale' and 'gender.
We need to use method getEmail() as per docs. But I am not able to do it.
("A simple app with OAuth security implemented")
Here is the snippet....
My controller class code is
#Controller
#RequestMapping("/")
public class HelloController {
private Facebook facebook;
private ConnectionRepository connectionRepository;
public HelloController(Facebook facebook, ConnectionRepository connectionRepository) {
this.facebook = facebook;
this.connectionRepository = connectionRepository;
}
#GetMapping
public String helloFacebook(Model model) {
if (connectionRepository.findPrimaryConnection(Facebook.class) == null) {
return "redirect:/connect/facebook";
}
String [] fields = {"name", "gender", "locale"};
User userProfile = facebook.fetchObject("me", User.class, fields);
model.addAttribute("feed", userProfile);
//String email = facebook.getEmail();
/*this above one "facebook.getEmail()" gives Internal server error 500 */
return "hello";
}
}
Model class is ...
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
<h3>Hello, <span th:text="${feed.name}">Some User</span>!</h3>
<h4>Your gender is : <span th:text="${feed.gender}"></span></h4>
<h4>Your locale is : <span th:text="${feed.locale}"></span></h4>
<h4>Your email is : <span th:text="${feed.getEmail()}"></span></h4>
</body>
</html>
Main class is as...
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Any help is appreciated. Thanks.

Accessing Model attributes in Thymleaf and Spring boot

I am learning to use thymeleaf templates for a project I am completing and seem to be missing something.
I am trying to create a very simple Hello type app, here is my code (note I am using groovy):
Controller:
#Controller
class TestController {
#RequestMapping("/")
String homePage(#RequestParam("name") String name, ModelAndView modelAndView){
modelAndView.addObject("name", name)
return "home"
}
}
home.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h1>Hello</h1>
<p th:text="${name}" />
</body>
</html>
What have I missed? I just get "Hello" and nothing else when I hit:
http://localhost:8080/app-0.0.1-SNAPSHOT/?name=Sam
you have alternate option with access controller data with view name returning
#Controller
class TestController {
#RequestMapping("/")
public String homePage(#RequestParam("name") String name,Model model){
model.addAttribute("name", name)
return "home"
}
}
in your html file
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h1>Hello</h1>
<p th:text="${name}" />
</body>
</html>
bind model object with parameter and now you need to set addAttribute with key and value par you can access data without using ModelAndView object.
I'm not sure but you can to change ModelAndView by Model:
#Controller
class TestController {
#RequestMapping("/")
String homePage(#RequestParam("name") String name, Model model){
model.addAttribute("name", name)
return "home"
}
}
To answer my own question, if I change the controller to return a ModelAndView, like so:
#Controller
class TestController {
#RequestMapping("/")
ModelAndView homePage(#RequestParam("name") String name){
ModelAndView mav = new ModelAndView()
mav.addObject("name", name)
mav.setViewName("home")
return mav
}
}
Then all is good, although the tutorials show it working like my original example - I'm quite happy to do it this way.
#Controller
#RequestMapping("/")
class TestController {
#GetMapping
public String homePage(#RequestParam(name = "name") String name,Model model){
model.addAttribute("name", name);
return "home";
}
}

Resources