#RequestMapping at class level - spring-boot

I'm new to springboot. I want to create a class with #RequestMapping at class level. I have a static html file located resource/static/main/index.html
#Controller
#RequestMapping("/home")
public class HomeController {
#GetMapping
#ResponseBody
public String Welcome(){
return "Hello World";
}
#GetMapping("/message")
public String message(){
return "main/index.html";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, user-scalable=yes">
<title>Hello Message!</title>
</head>
<body>
Welcome everyone!
</body>
</html>
http://localhost:8080/home display Hello World in my browser. When I enter http://localhost:8080/home/message, I get a 404 message, The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. If I remove #RequestMapping("/home") from the class level then it works. My goal is to have mulitple #GetMapping and #RequestMapping at the class level

If you are using thymeleaf then try:
#GetMapping("/message")
public String message(){
return "main/index";
}
The index view location must be resources/templates

Related

Why doesn't ModelAndView add a property?

i have such a RestController
#Controller
public class ExchangeRateController {
private final static Logger LOGGER = LoggerFactory.getLogger(ExchangeRateController.class);
#GetMapping(value = "/current")
public ModelAndView geExchangeRate(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("Response.html");
modelAndView.addObject("resultUrl",url);
modelAndView.addObject("embedUrl",embedUrl);
return modelAndView;
}
}
Inside, I get the URL of the image and want to embed it using Model on my page.But it gives me an error 404 or an empty page, although if to take these addresses and just write in an html file, then everything works.How can this be done so that they are added to the place of scr and href?
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<iframe src="${resultUrl}" width="980" height="560" frameBorder="0" class="giphy-embed" allowFullScreen></iframe>
<p>text</p>
</body>
</html>
Try to use #Controller instead of #RestController and change #RequestMapping("/current")
Use th:src and th:href.
<iframe th:src="${resultUrl}" width="980" height="560" frameBorder="0" class="giphy-embed" allowFullScreen></iframe>
<p><a th:href="${embedUrl}">text</a></p>

What is the way to use variable expression in thymeleaf 2.5.6 version

I just create simple template by the help of thmeleaf, When I try to
access the variable from controller class by the help of variable
Expression , But I get Issue on variable expression ,In the time of
variable expression access . Showing below type of error
cannot Resolve variable name
My variable name is today which I define in my controller class
Homecontroller.kt
package com.nilmani.thymeleafdemo.controller
import org.springframework.web.bind.annotation.RestController
import org.thymeleaf.ITemplateEngine
import org.thymeleaf.context.WebContext
import java.text.SimpleDateFormat
import java.util.*
import javax.servlet.ServletContext
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
#RestController
class HomeController : IGTVGController() {
#Throws(Exception::class)
fun process(request:HttpServletRequest,response: HttpServletResponse,
servletContext: ServletContext,templateEngine: ITemplateEngine){
val dateForm:SimpleDateFormat= SimpleDateFormat("dd-mm-yyyy")
val calendar:Calendar = Calendar.getInstance()
val ctx : WebContext = WebContext(request,response,servletContext,request.locale)
ctx.setVariable("today",dateForm.format(calendar.time))
templateEngine.process("home",ctx,response.writer)
}
}
home.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Welcome TO our WebPage</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all"
href="../../css/gtvg.css" th:href="#{/css/gtvg.css}" />
</head>
<body>
<p th:utext="#{home.welcome}">Welcome to our website</p>
<p>Today is: <span th:text= "${today}"></span></p>
</body>
</html>
error shows at this point below point
th:text= "${today}"
What is the reason for not support of variable expression . I already
added thymeleaf gradle depedency in my project.But the variable
expression not working
I don't know Kotlin, so I hope you can convert my Java answer to it.
I see you use #RestController, but if you are using Thymeleaf, use #Controller
You can have Spring Boot inject the Model class and add your attributes there
The easiest is to return a String value that represents the name of the Thymeleaf template.
Using all that, you get something like this:
#Controller
public class HomeController {
public String process(Model model) {
model.addAttribute("today", ...);
return "home"; //this refers to home.html like this
}
}
PS: You should not use Calendar anymore, see https://www.baeldung.com/java-8-date-time-intro for more info on the "new" date/time API introduced in Java 8.

Hardcoding URL in Spring

package com.example.servingwebcontent;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class GreetingController {
#GetMapping("/greeting")
public String greeting(#RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
}
<!DOCTYPE HTML>
<html>
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Get your greeting here</p>
</body>
</html>
The examples from the official guide: https://spring.io/guides/gs/serving-web-content/
We can see that the url, that is greeting, is hardcoded.
Suppose, I write that url in 50 places. And now I want to change the url.
Is it somehow possible to escape hardcoding?
The HTTP request can be GET, POST, PUT, DELETE, and PATCH.
To map the HTTP request with your definition, you need to use #GetMapping, #PostMapping, #PutMapping, #DeleteMapping, and #PatchMapping in the controller class.
So, URL /greeting can be used in those 5 requests only. So, we can't write the same URL in 50 places in the controller class.

HTML Page Doesn't Show Up on Springboot Application

I'm trying to create a registration page. The website is very simple, homepage will be returning signup page and when clicked "Submit" it should save it to the database. But I'm having trouble with getting the page.
Applicant.java
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.Date;
#Entity
#Table(name = "bayilik_basvuru")
public class Applicant {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#NotBlank(message = "İsim Soyisim Girilmelidir.")
#Column(name = "isim_soyisim")
private String adSoyad;
public Applicant() {
}
public String getAdSoyad() {
return adSoyad;
}
public void setAdSoyad(String adSoyad) {
this.adSoyad = adSoyad;
}
}
Controller
#Controller
public class HomeContoller {
#Autowired
private ApplicantDAO dao;
#RequestMapping("/")
public ModelAndView getApplicationPage(){
ModelAndView model = new ModelAndView();
Applicant applicant = new Applicant();
model.addObject("applicant",applicant);
model.setViewName("index");
return model;
}
#PostMapping("/save")
public String saveApplicant(#Valid Applicant applicant, BindingResult result){
if (result.hasErrors()) {
return "add-student";
}
dao.save(applicant);
return "index";
}
}
Index.html -> form's piece,
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Bayilik Ön Başvuru Formu</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" th:href="#{../css/style.css}" />
<link rel="stylesheet" type="text/css" th:href="#{../css/bootstrap-datetimepicker.min.css}" />
<link rel="stylesheet" type="text/css" th:href="#{../css/roboto-font.css}" />
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body>
<form class="form-horizantal" th:action="#{/save}" th:object="${applicant}"
method="POST">
<div class="form-group">
<label class="col-md-4 control-label">İsim Soyisim</label>
<div class="col-md-8">
<input type="text" th:field="*{adSoyad}" class="form-control" /> <!-- it gives error at this line at the start of the th:field-->
<span th:if="${#fields.hasErrors('adSoyad')}" th:errors="*{adSoyad}" class="text-danger"></span>
</div>
</div>
</body>
</html>
I have been dealing with this for hours. I've compared it to many examples and html file looks good, controller looks good I don't know what I'm doing wrong.
In my pom file I have thymeleaf;
<dependencies>
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
...
<dependendcies>
By the way the error is this;
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Oct 31 01:40:47 EET 2019
There was an unexpected error (type=Internal Server Error, status=500).
Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "index" - line 27, col 56) // this line is the same line I showed on the index.html file
You are not using the annotation #ModelAttribute on your /save endpoint . try using it like :
#PostMapping("/save")
public String saveApplicant( #Valid #ModelAttribute("applicant") Applicant applicant, BindingResult result){
if (result.hasErrors()) {
return "add-student";
}
dao.save(applicant);
return "index";
}
In your thymeleaf template th:object="${applicant}" expression declares the model object to use for collecting the form data. So , in your controller you have to use the annotation #ModelAttribute to bind the Applicant object to the incoming form content.
Change your get method to properly add the object:
#GetMapping("/") //simpler, more informative
public String getApplicationPage(Model model){
model.addAttribute("applicant", new Applicant()); //note method name
return "index";
}
Look at Project Lombok to greatly simplify your beans. You are missing a getter and setter for your id property and an annotation of #Getter and #Setter on the class would remove a lot of boilerplate.
You would also want the #ModelAttribute annotation on your post method for the Applicant parameter.
In the future, also please post your full stack trace.
It seems like there was an hierarchy problem on the project. Code worked after I fixed the hierarchy of files.
Thanks to repliers for their attempt to help but they couldn't know the core of the problem since I didn't attach the hierarchy's screenshot on the question.

Failed to load resource: the server responded with a status of 404 (Not Found) in spring mvc

I am trying to load the css file into jsp, it is not loading and showing the message Failed to load resource: the server responded with a status of 404 (Not Found).the following is my code
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Bootstrap Form With Spring Mvc Example</title>
<link href="<c:url value='/resources/css/bootstrap.css'/>" rel="stylesheet" media="screen">
</head>
in configuration class I have added the below code:
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
I have tried all the solutions, I did not find what's the wrong,can any one help me?
Try it this way:
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**")
.addResourceLocations("/css/");
}
This assumes your directory structure is:
src
main
java
resources
css
webapp
The point is that you don't specify the resources level in your resource handler.
Is your css file in WebContent folder..Please check for it.And if your are using maven it must be in resources folder.If the folder structure is correct.
Please treat the jsp pages like html ..
paste your css file near your jsp folder.And try to access it using href directly instead of using c tag.
<link href="../css/bootstrap.css" rel="stylesheet" media="screen">
This approach is dirty one.But good for jsp pages integrated thymeLeaf kindof tools.
Edit your configuration class to inherit from WebMvcConfigurerAdapter as shown below. It solved my own problem after trying a lot of other options. Hope it would work for you.
public class Config extends WebMvcConfigurerAdapter{
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}

Resources