I'm learnig how Spring boot + MVC works. I can display a message on the screen, but I can not modifying the style. The js e css file don't map with Spring.
2020-04-17 14:38:29.169 WARN 9552 --- [nio-8080-exec-3] o.s.web.servlet.PageNotFound : No mapping for GET /js/main.js
2020-04-17 14:38:29.169 WARN 9552 --- [nio-8080-exec-2] o.s.web.servlet.PageNotFound : No mapping for GET /css/main.css
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class HelloController {
#GetMapping("/")
public String index() {
return "index";
}
#PostMapping("/hello")
public String sayhello(#RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "hello";
}
#GetMapping({"/helloworld", "/helloname"})
public String hello(Model model, #RequestParam(value="name", required=false, defaultValue="WORLD") String name) {
model.addAttribute("name", name);
return "helloname";
}
}
I've tryied to modify the path in the application.properties, but it didn't change anything.
spring.mvc.view.prefix = /WEB-INF/view/
spring.mvc.view.suffix = .jsp
spring.mvc.static-path-pattern = /resources/**
This is my jsp page. When I run this page , I get the error message, that I've posted before
<!DOCTYPE html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css"
href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />
<c:url value="/css/main.css" var="jstlCss" />
<link href="${jstlCss}" rel="stylesheet" />
</head>
<body>
<div class="container">
<header>
<h1>Spring MVC + JSP + JPA + Spring Boot 2</h1>
</header>
<div class="starter-template">
<h1>Users List</h1>
<table
class="table table-striped table-hover table-condensed table-bordered">
<tr>
<th>Date</th>
<th>Device</th>
<!-- <th>Amount</th>
<th>OEE</th> -->
</tr>
<c:forEach items="${OEE}" var="oee">
<tr>
<!-- <td>${oee.oeeID.date}</td>
<td>${oee.oeeID.device}</td> -->
<td>${oee.amount}</td>
<td>${oee.oee}</td>
</tr>
</c:forEach>
</table>
</div>
</div>
<script type="text/javascript"
src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
use this
#Configuration
#EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
}
Related
I have this Endpoint:
#RestController
public class FileImportsController {
private EntityImportRequestsService entityImportRequestsService;
#Autowired
public FileImportsController(EntityImportRequestsService entityImportRequestsService) {
this.entityImportRequestsService = entityImportRequestsService;
}
#GetMapping("/imported_files")
public String viewHomePage(Model model) {
List<EntityImportRequestsTable> listProducts = entityImportRequestsService.findAll();
System.out.println("Size is " + listProducts.size());
model.addAttribute("listProducts", listProducts);
return "index";
}
}
Entity:
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Builder(toBuilder = true)
#Entity
#Table(name = "EntityImportRequests")
public class EntityImportRequestsTable implements Serializable {
#Id
#Column(name = "requestId")
private String requestId;
}
Web page index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<title>Product Manager</title>
</head>
<body>
<div align="center">
<h1>Product List</h1>
<table border="1" cellpadding="10">
<tr>
<th>requestId</th>
</tr>
<tr th:each="product: ${listProducts}">
<td th:text="${product.requestId}" />
<td th:text="${product.name}" />
<td th:text="${product.price}" />
</tr>
</table>
</div>
</body>
</html>
When I open the page data is not displayed. What is the proper way to call endpoint imported_files and display all the data?
Hi I'm building a skeleton of a car renting webapp and I'm trying to create a view that shows some details like location name, car name etc.
View code- car-list.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Vehicle List</title>
<h2 th:text="${location1}">Locations</h2>
<table class="table table-stripped">
<thead>
<td th:text="${vehicle1Name}">Vehicle Name</td>
</tr>
</thead>
<td th:text="${vehicle2Name}">Vehicle Name</td>
</tr>
</table>
</head>
<body>
</body>
</html>
And heres my controller
package com.project.CS4125.controller;
import com.project.CS4125.model.*;
import com.project.CS4125.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
#Controller
#RequestMapping("/car-list")
public class VehicleController {
#GetMapping("/car-list")
public String carList(Model model){
Vehicle VWGolf = new BasicCar();
Vehicle Duster = new SUVDecorator(new BasicCar());
Location limerick= new Location("Limerick");
model.addAttribute("location1", limerick.getLocationName());
model.addAttribute("vehicle1Name", "Volkswagen Golf");
model.addAttribute("vehicle2Name", "Dacia Duster");
return "index";
}
}
My problem is the view comes up completely empty, any help appreciated.
EDIT
Before this page I have a register and login page
index.html (register page
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Register</title>
</head>
<body>
<form action="#" th:action="#{/register}" th:object="${user}"
method="post">
<p>User Name <input type="text" name="name"></p>
<p>Password <input type="password" name="password"></p>
<button type="submit">Register</button>
</form>
<button>Login Here</button>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="#" th:action="#{/login}" th:object="${user}"
method="post">
<p>User Name <input type="text" name="name"></p>
<p>Password <input type="password" name="password"></p>
<button type="submit">Login</button>
</form>
<button>Register Here</button>
</body>
</html>
And heres the controller for these
#Controller
#RequestMapping("/")
public class IndexController {
#Autowired
private UserService userService;
#Autowired
private CustomerFactory userFactory;
#PostMapping("/register")
public String registerUser(#ModelAttribute User user){
User u = userFactory.createUser(user.getName(), user.getPassword());
userService.saveUser(u);
return "login";
}
#GetMapping("/login")
public String login(){
return "login";
}
#PostMapping("/login")
public String loginUser(#ModelAttribute User user){
User authenticatedUser = userService.authenticate(user.getName(), user.getPassword());
System.out.println(authenticatedUser.toString());
return "car-list";
}
}
Even after adding the code from the answer below I'm still getting an empty page, after submitting the login form moving to the car list page its still empty.
I also noticed in the answer the URL is http://localhost:8080/car-list but when I try it its http://localhost:8080/login
I've just tested your code and you have two problems.
The first one is at your:
#Controller
#RequestMapping("/car-list")
public class VehicleController {
#GetMapping("/car-list")
In this GetMapping you're saying that you want to access your template at /car-list/car-list.
The seccond one is with your template name. You're returning "index" when you should return "car-list", at this you're returning the template name.
So, editting your code like this:
#Controller
#RequestMapping("/car-list")
public class VehicleController {
#GetMapping
public String carList(Model model){
model.addAttribute("location1", "Answer");
model.addAttribute("vehicle1Name", "Volkswagen Golf");
model.addAttribute("vehicle2Name", "Dacia Duster");
return "car-list";
}
}
I got:
Template working and returning
I am trying to perform crud operation with spring boot and i am new to it. I have successfully performed delete and create part. The problem i am having when i am trying to edit my fields. I am using MYSQL as my database. I am having error mentioned in question title. Any help to resolve it and please check my logic i think my logic is wrong in /showUpdate method. When i press edit button then it is not taking me to edit page and throwing me this error.
My controller class is pasted below:
Snapshot of Actual error i am having
package com.bilal.location.controllers;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.bilal.location.entities.Location;
import com.bilal.location.service.LocationService;
#Controller
public class LocationController {
#Autowired
LocationService service;
#RequestMapping("/showCreate")
public String showCreate() {
return "createLocation";
}
#RequestMapping("/savLoc")
public String saveLocation(#ModelAttribute("location") Location location,ModelMap modelMap) {
Location locationSaved = service.saveLocation(location);
String msg = "Location saved with id: " + locationSaved.getId();
modelMap.addAttribute("msg", msg);
return "createLocation";
}
#RequestMapping("/displayLocations")
public String displayLocations(ModelMap modelMap) {
List<Location> locations = service.getAllLocations();
modelMap.addAttribute("locations", locations);
return "displayLocations";
}
#RequestMapping("/deleteLocation")
public String deleteLocation(#RequestParam("id")int id,ModelMap modelMap) {
Location location = new Location();
location.setId(id);
service.deleteLocation(location);
List<Location> locations = service.getAllLocations();
modelMap.addAttribute("locations", locations);
return "displayLocations";
}
#RequestMapping("/showUpdate")
public String showUpdate(#RequestParam("id")int id,ModelMap modelMap) {
Optional<Location> location = service.getLocationById(id);
modelMap.addAttribute("location", location);
return "updateLocation";
}
#RequestMapping("/updateLoc")
public String updateLocation(#ModelAttribute("location") Location location,ModelMap modelMap) {
service.updateLocation(location);
List<Location> locations = service.getAllLocations();
modelMap.addAttribute("locations", locations);
return "displayLocations";
}
}
Display Location JSP Page:
<%# 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"%>
<%#page isELIgnored="false" %>
<!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=ISO-8859-1">
<title>Display Locations</title>
</head>
<body>
<h2>Locations:</h2>
<%--Table Starting from here --%>
<table>
<tr>
<th>id</th>
<th>code</th>
<th>name</th>
<th>type</th>
</tr>
<c:forEach items = "${locations}" var="location" >
<tr>
<td>${location.id}</td>
<td>${location.code}</td>
<td>${location.name}</td>
<td>${location.type}</td>
<td>delete</td>
<td>edit</td>
</tr>
</c:forEach>
</table>
<%--Table Ending here --%>
Add Location
</body>
</html>
Update Location JSP Page
<%# 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"%>
<%#page isELIgnored="false" %>
<!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=ISO-8859-1">
<title>Create Location</title>
</head>
<body>
<form action="updateLoc" method="post">
<pre>
id: <input type="text" name="id" value = "${location.id}" readonly/>
code: <input type="text" name="code" value = "${location.code}"/>
name: <input type="text" name="name" value = "${location.name}"/>
type: rural <input type ="radio" name="type" value ="RURAL" ${location.type=='URBAN'?'checked':'' }/>
Urban <input type ="radio" name="type" value= "URBAN" ${location.type=='RURAL'?'checked':'' }/>
<input type="submit" name="save"/>
</pre>
</form>
</body>
</html>
Read the error message carefully. It says you are trying to acces .id, but not on your Location, but on an Optional instead - which doesn't have that property.
Check your code:
#RequestMapping("/showUpdate")
public String showUpdate(#RequestParam("id")int id,ModelMap modelMap) {
Optional<Location> location = service.getLocationById(id);
modelMap.addAttribute("location", location);
return "updateLocation";
}
You are not adding the location, but an Optional that might contain the location.
You can check whether an Optional holds a value by calling ìsPresent(), e.g.
if (location.isPresent()) {
modelMap.addAttribute("location", location.get());
} else {
// ERROR?
}
More on Optional, if you are not familiar: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
In my case it was solve by
In controller
ModelAndView modelAndView = new ModelAndView();
Optional<Employee> employee = employeeRepository.findById( employeeDto.getId());
if (employee.isPresent()) {
modelAndView.addObject("employeeDto", employee.get());
System.out.println(employee);
} else {
System.out.println("Error Found"); // error message
}
In views
I am trying to create a form using thymeleaf that contains a series of checkboxes. The object source that I am passing through to the thymeleaf template contains a String and a List.
package com.controller;
import java.util.List;
public class Source {
private String sourceName;
private List<String> testList;
public String getSourceName()
{
return sourceName;
}
public void setSourceName(String name)
{
this.sourceName = name;
}
public List<String> getTestList()
{
return testList;
}
public void setTestList(List<String> list)
{
this.testList = list;
}
}
I pass an object of type source into the template using this MVC controller.
package com.controller;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.View;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import com.web_application.AllEnvironmentsFromFile;
import com.web_application.AllTestsAndPaths;
import com.web_application.RunDao;
import com.web_application.TestAndPath;
#RestController
public class ManualTestController {
#Autowired
private ThymeleafViewResolver resolver;
#Autowired
RunDao rDao;
#Autowired
AllEnvironmentsFromFile environments;
#RequestMapping(value="/manualTest", method=RequestMethod.GET)
public View greetingForm(Model model) throws Exception {
AllTestsAndPaths a = new AllTestsAndPaths();
List<TestAndPath> testList = a.testsAndPaths();
String[] environmentList = new String[environments.getEnvironments().size()];
for(int i = 0; i < environments.getEnvironments().size(); i++)
{
environmentList[i] = environments.getEnvironments().get(i).getName();
}
model.addAttribute("testList", testList);
model.addAttribute("source", new Source());
model.addAttribute("environmentList", environmentList);
return resolver.resolveViewName("manualTest", Locale.US); }
#RequestMapping(value="/manualTest", method=RequestMethod.POST)
public String greetingSubmit(#ModelAttribute Source source, Model model) {
System.out.println(source.getSourceName());
for(String hello : source.getTestList())
{
System.out.println(hello);
}
model.addAttribute("source", source);
return "result";
}
}
The manualTest template looks like this
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<form action="#" th:action="#{/manualTest}" th:object="${source}" method="post">
<p>Source: <input type="text" th:field="*{sourceName}" /></p>
<table border="1">
<tr>
<td>Test Name</td>
<td th:each="environment : ${environmentList}"
th:text="${environment}">Tests</td>
</tr>
<th:block th:each="test : ${testList}">
<tr>
<td th:text="${test.name}">A Test'</td>
<th:block th:each="enviro : ${environmentList}">
<td><input type="checkbox" path="${testList}" value="hello" /></td>
</th:block>
</tr>
</th:block>
</table>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
My problem is that the values of the checkbox are not being stored in the array. When i run this code and click submit i get a null pointer exception because the list in the source object is empty. The sourceName works perfectly but the checkboxes are not actually adding anything.
THis code ended up working, You need to pass in an object containing an arrayList. Also it helped that I combined two variables into one string and i later separated them by -.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Insert title here</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<form action="#" th:action="#{/manualTest}" th:object="${source}" method="post">
<table border="1">
<tr>
<td>Test Name</td>
<td th:each="environment : ${environmentList}"
th:text="${environment}">Tests</td>
</tr>
<th:block th:each="test : ${testList}">
<tr>
<td th:text="${test.name}">A Test'</td>
<th:block th:each="enviro : ${environmentList}">
<td><input type="checkbox" th:field="*{testList}" th:value="|${test.name}-${enviro}|" /></td>
</th:block>
</tr>
</th:block>
</table>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
what should i download for working with validation in spring.know annotations are unknown in my classes for example in blow code:
public String register2( #Valid User user , BindingResult br)
{
if(br.hasErrors())
{
return "edit";
}
//System.out.println("you registers!");
return "thanks";
}
#valid is unknown .which library should i download for work with jsr-303 standard in spring mcv?and where should i download?
and how i setup that in eclipse helious?
thanks
EDIT:MY CODE APPENDED=>
my controller=>
package codes;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.Validator;
import org.apache.jasper.tagplugins.jstl.core.Out;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.BindingResultUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.portlet.ModelAndView;
#org.springframework.stereotype.Controller
public class Controller {
#RequestMapping(value="/register/" , method=RequestMethod.GET)
public String register(Model model)
{
model.addAttribute("myUser",new User());
return "edit";
}
#RequestMapping(value="/register/" , method=RequestMethod.POST)
public String register2( ModelAndView model,#Valid User myUser , BindingResult br)
{
try
{
if(br.hasErrors())
{
return "edit";
}
else
{
System.out.println(myUser);
System.out.println(myUser.getName());
System.out.println(myUser.getFamily());
System.out.println("salam");
return "thanks";
}
}
catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
return "thanks";
}
}
my edit.jsp page(form)=>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!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=ISO-8859-1">
<title>Register</title>
</head>
<body>
<div>
<sf:form method="post" modelAttribute="myUser" >
<label for="USER_NAME">name:</label>
<sf:input path="name" id="USER_NAME"/>
<sf:errors path="name" ></sf:errors>
<br>
<label for="USER_FAMILY">family:</label>
<sf:input path="family" id="USER_FAMILY"/>
<br>
<input type="submit" value="REGISTER" />
</sf:form>
</div>
</body>
</html>
NOTE:only when my user object is invalide i get exception and when thatz valid i give not exeption
You can use Hibernate Validator.
To run it, you need to add these jars to your project:
hibernate-validator*.jar
validation-api*.jar
slf4j-api*.jar
You can find all of them in the Hibernate Validator package.