Mapping some URLS with Spring Boot - mongodb

Hi there im new with spring boot and mvc model im trying to create some methods to call some data to the Mongo D.B using postman im getting the data but now i want to show this data in a web page but i cant figure out how mapping works in spring boot.
I have this methods:
#Controller
#RequestMapping("/Informacion")
public class InformacionControlador {
#Autowired
private informacionRepo informacioRepo;
public InformacionControlador(informacionRepo informacioRepo) {
this.informacioRepo = informacioRepo;
}
//This method is comment because using postman get the answer in json format
// #GetMapping("/Listar")
// public List<Informacion> getAll() {
// List<Informacion> info = this.informacioRepo.findAll();
// return info;
// }
//Now this is the method that i want to work like the first one but
//instead of json answer y want to see the data in ListarInformacion page
#GetMapping("/Listar")
public String informacion(ModelMap model) {
model.addAttribute("info", informacioRepo.findAll());
return "ListarInformacion";
}
#PutMapping
public void insert(#RequestBody Informacion informacion) {
this.informacioRepo.insert(informacion);
}
}
Also i put this lines in application.properties file to set the folder where the page will be storage
spring.mvc.view.prefix=/webapp/Vistas
spring.mvc.view.suffix=.jsp
This is my ListarInformacion page
<html>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<head>
<title>Title</title>
</head>
<body>
<form:form method="GET" action="/webapp/Vistas/ListarInformacion" modelAttribute="Informacion">
<table class="table table-striped table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Nombre</th>
<th scope="col">Identificación</th>
<th scope="col">Fecha Creación</th>
</tr>
</thead>
<c:forEach var="p" items="${info}">
<tr>
<td>${p.idInformacion}</td>
<td>${p.nombre}</td>
<td>${p.pais}</td>
<td><fmt:formatDate pattern="dd/MM/yyyy" value="${p.fechaCreacion}"/></td>
<td>
</td>
</tr>
</c:forEach>
</table>
</form:form>
</body>
</html>
this is the location of my files
can anyone tell me what am i missin because when i try to access to the url localhost:8080/Informacion/Listar the answer is a String that says /ListarInformacion ant its no redirecting me to the page that its supose to redirect

You should try to access localhost:8080/Informacion/Listar as you have already given mapping to the controller class (/Informacion)
the preferred location to put the jsp in a spring boot project is
--webapp
--WEB-INF
--jsp
--your.jsp
in your case it is
-
-webapp
--WEB-INF(Create WEB-INF directory if you don't have)
--Vistas(folder)
--jsp
--hello.jsp
And your view path in properties file will be spring.mvc.view.prefix=/WEB-INF/Vistas

Related

Dynamic queries and JpaSpecificationExecutor in Spring

I am trying to create a simple Spring project where restaurants can add menu items to shared database and users can use a html form to search the dishes based on a range of criteria- especially dietary requirements
Form example:
Restaurant Name: Chez Hans
Gluten Free: (X)
Egg Free: (X)
Vegan: ()
Example SQL command
Select all FROM "dishes" Dish WHERE restaurant_name = "Chez Hans" AND egg_free = TRUE AND
gluten_Free = TRUE;
A list of dishes that fit their criteria would then be returned to the user.
Any field in the form can be left blank, and not checking a box for example, "vegan" does not mean that criteria should be set as 'false', but rather not included within the query.
Because of this it seemed the best way to handle the issue was using JpaSpecificationExecutor to create dynamic SQL queries (similar to the implementation in the answer to the problem below)
Filtering database rows with spring-data-jpa and spring-mvc
I have created a solution based on my research and prior knowledge. However, when I implement my solution, no dishes are returned- even though there are dishes in the database that fit the search criteria. No errors are being produced, but simply a blank table, so I am not sure where I am going wrong.
I have researched countless articles/videos regarding JpaSpecificationExecutor/dynamic queries but there are parts of the that theory I am still unsure about. This is what I gather about JpaSpecificationExecutor/dynamic queries (but I may be wrong)
The meta model is not need to create dynamic queries but to verify the correctness of database query statements
To create queries using meta-model classes a wrapper class is required (In my example- DishSearch)
The following lines are to cast metamodel SingularAttribute class back to the original class value.
Path dname = root.get(Dish_.dname);
Path vegan= root.get(Dish_.vegan);
I am quite new to Spring and still finding it pretty difficult. Any help or advice would be very much appreciated!
Please see below my DishSpecification class:
package com.bron.demoJPA.specification;
public class DishSpecification implements Specification<Dish> {
private final DishSearch criteria;
public DishSpecification(DishSearch ds) {
criteria =ds;
}
#Override
public Predicate toPredicate(Root<Dish> root, CriteriaQuery<?> query,
CriteriaBuilder cb) {
Path<String> dname = root.get(Dish_.dname);
Path<Boolean> vegan= root.get(Dish_.vegan);
Path<Boolean> eggFree= root.get(Dish_.eggFree);
Path<Boolean> glutenFree= root.get(Dish_.glutenFree);
final List<Predicate> predicates = new ArrayList<Predicate>();
if(criteria.getDname()!=null) {
predicates.add(cb.equal(dname, criteria.getDname()));
}
if(criteria.isVegan()!=false) {
predicates.add(cb.equal(vegan, criteria.isVegan()));
}
if(criteria.isEggFree()!=false) {
predicates.add(cb.equal(eggFree, criteria.isEggFree()));
}
if(criteria.isGlutenFree()!=false) {
predicates.add(cb.equal(glutenFree, criteria.isGlutenFree()));
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
}
Please see my DishSearch Class:
package com.bron.demoJPA.specification;
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
public class DishSearch {
private Long dishId;
private String dname;
private String description;
private double price;
private boolean vegan;
private boolean glutenFree;
private boolean eggFree;
private AppUser app;
}
Please see my SearchController Class:
#Controller
public class SearchController {
#Autowired
DishRepository drep;
#GetMapping("/showSearchForm")
public String showNewDishForm(Model model) {
// Create model attribute to bind form data
DishSearch dishSearch = new DishSearch();
model.addAttribute("dishSearch", dishSearch);
return "search_Dish";
}
#PostMapping("/showDishList")
public String saveUser(#ModelAttribute("dishSearch")DishSearch dishSearch) {
Specification<Dish> spec = new DishSpecification(dishSearch);
drep.findAll(spec);
return "show_dish_List";
}
}
Please see my DishRepository Class:
#Repository
public interface DishRepository extends JpaRepository<Dish, Long>, JpaSpecificationExecutor<Dish>{
#Transactional
#Modifying
List<Dish> findAll(Specification<Dish> spec);
}
Please see my search_Dish.html Thymeleaf Template:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Dish Management System</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<br>
<div class="col-sm-10 offset-sm-1 text-center">
<div class="container">
<h2> Manage Dishes </h2>
<hr>
</div>
<form action="#" th:action="#{/showDishList}" th:object="${dishSearch}" method="POST">
<div class="col-sm-10 offset-sm-1 text-center">
<input type="text" th:field="*{dname}"
placeholder="Dish Name" class="form-control mb-4 col-10">
</div>
<div class="form-check form-check-inline">
<label class=" form-check-label" for="inlineCheckbox1 ">Vegan?</label>
<input type="checkbox" th:field="*{vegan}" />
<label class="form-check-label" for="inlineCheckbox1">Gluten Free?</label>
<input type="checkbox" th:field="*{glutenFree}" />
<label class="form-check-label" for="inlineCheckbox1">Egg Free?</label>
<input type="checkbox" th:field="*{EggFree}" />
</div>
<br>
<br>
<br>
<br>
<button type="submit" class="btn btn-info col-4"> Search Database</button>
</form>
</div>
<hr>
</body>
</html>
Please see my show_dish_List.html Thymeleaf Template:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Search Results</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
<br>
<div class="col-sm-10 offset-sm-1 text-center">
<h1>Dish List</h1>
</div>
<table border="1" class="table table-striped table-responsive-md">
<thead>
<tr>
<th>Dish Name</th>
<th>Dish description</th>
<th>Dish Price</th>
<th>Restaurant</th>
</tr>
</thead>
<tbody>
<tr th:each="dishSearch : ${listDishSearch}">
<td th:text="${dishSearch.dname}"></td>
<td th:text="${dishSearch.description}"></td>
<td th:text="${dishSearch.price}"></td>
</tr>
</tbody>
</table>
<div class="col-sm-10 offset-sm-1 text-center">
<a th:href="#{/showNewDishForm}"
class="btn btn-primary btn-sm mb-3"> Search Again</a>
</div>
----------------------------Update------------------------------
In addition to the answer provided below, in the Dish Specification Class I changed
if(criteria.getDname()!=null) {
predicates.add(cb.equal(dname, criteria.getDname()));
}
to
if(criteria.getDname()!="") {
predicates.add(cb.equal(dname, criteria.getDname()));
}
and the search is working fine now!
I believe the issue is that you are not adding the result in the Model which is being used to render the page show_dish_List.html, therefore nothing is being populated in the UI. Your UI is expecting the data to be in listDishSearch and there is nothing in that variable.
Update your code to:
#PostMapping("/showDishList")
public String saveUser(#ModelAttribute("dishSearch") DishSearch dishSearch, Model model) {
Specification<Dish> spec = new DishSpecification(dishSearch);
model.addAttribute("listDishSearch", drep.findAll(spec));
return "show_dish_List";
}
and everything should be working fine.
Remove the method findAll from your DishRepository repository. It is already being provided by the interface JpaSpecificationExecutor.

HTTP Status 404 – Not Found Tomcat

This is my code. I'm trying to add values to my table using JSP and MYSQL. Name of the table and database is correct.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import ="java.sql.*" %>
<%# page import ="javax.sql.*" %>
<!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>Inserting Data from form</title>
</head>
<body>
<h1> Insert a Record</h1>
<form method="post" action="insertrecord.jsp">
<table>
<tr>
<td>
<input type="text" name="uname">
</td>
<td>
<input type="password" name="upass">
</td>
<tr>
<tr>
<td><input type="submit" name="submit" value ="submit"></td>
</tr>
</table>
</form>
<%
String sub = request.getParameter("submit");
if(sub!=null)
{
String uname=request.getParameter("uname");
String password = request.getParameter("upass");
if(uname!=null && password!=null)
{
try
{
Connection con;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","");
Statement stmt = con.createStatement();
int i = stmt.executeUpdate("insert into user values ('"+uname+"','"+password+"')");
out.println("Record Inserted Successfully");
stmt.close();
con.close();
}
catch(SQLException e)
{
out.println(e.getMessage());
}
}
}
%>
</body>
</html>
When I click on submit. I'm getting this error:
HTTP Status 404 – Not Found
Type Status Report
Message /something/insertrecord.jsp
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Apache Tomcat/9.0.5

Spring Mvc Rest Webservice jstl form submittion HTTP Status 415 Content type 'application/x-www-form-urlencoded' not supported

I am Using Spring Mvc Rest Webservice with JSTL form submittion.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# page session="false" %>
<html>
<head>
</head>
<body>
<form:form method="POST" action="rest/save" modelAttribute="employee">
<table>
<tr><td>
id &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<form:input type="text" path="id"/>
</td></tr>
<tr><td>
fname <form:input type="text" path="firstName"/>
</td></tr>
<tr><td>
lname <form:input type="text" path="lastName"/>
</td></tr>
<tr><td>
phone <form:input type="text" path="phone"/>
</td></tr>
</table>
<input type="submit" value="submit" >
</form:form>
Here is my controller function that accepts the request.
#RequestMapping(value = EmpRestURIConstants.SAVE_EMP,method = RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String setemployee(#RequestBody Employee employee){
dataServices.setemp(employee);
return "success";
}
This works fine and saves the employee when i use it with ajax submit or with using RESTClient
The Error returns is..
HTTP Status 415: The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded' not supported
How Can i set the Mime type with JSTL form submittion and how can i solve the problem.
Please Somebody help.
When you're posting a form, the data are not sent as JSON, and since you have explicitly set that you're accepting only consumes=MediaType.APPLICATION_JSON_VALUE you get the 415 error. You can have all your cases covered by removing the #RequestBody and the consumes attribute, Spring MVC is smart enough to know what to do in all of your cases (form submition, RESTClient or ajax)
#RequestMapping(value = EmpRestURIConstants.SAVE_EMP,method = RequestMethod.POST)
public #ResponseBody String setemployee(Employee employee){
dataServices.setemp(employee);
return "success";
}

Spring 3 MVC Form not saving data in database

I am trying to run a simple Spring 3 MVC project to save form data but when I submit data the page goes to add.html with empty forms and no data is save in Mysql neither it is shown on the page.
Controller
package com.app.a;
/**
* Handles requests for the application home page.
*/
#Controller
#RequestMapping(value="/")
public class HomeController {
#Autowired
private Personrepo personRepo;
#RequestMapping(method=RequestMethod.GET)
public String showForm(ModelMap model){
List<Person> persons = personRepo.getAll();
model.addAttribute("persons", persons);
Person person = new Person();
person.setId(UUID.randomUUID().toString());
model.addAttribute("person", person);
return "home";
}
#RequestMapping(value="/add", method=RequestMethod.POST)
public ModelAndView add(#ModelAttribute(value="person") Person person,BindingResult result){
ModelAndView mv = new ModelAndView("home");
if(!result.hasErrors()) {
personRepo.add(person);
person = new Person();
person.setId(UUID.randomUUID().toString());
mv.addObject("person", person);
}
mv.addObject("persons", personRepo.getAll());
return mv;
}
#RequestMapping(value="/edit", method=RequestMethod.POST)
public ModelAndView edit(#ModelAttribute(value="person") Person person,BindingResult result) {
ModelAndView mv = new ModelAndView("home");
if(!result.hasErrors()) {
personRepo.edit(person);
person = new Person();
mv.addObject("person", person);
}
mv.addObject("persons", personRepo.getAll());
return mv;
}
#RequestMapping(value="/delete", method=RequestMethod.POST)
public ModelAndView update(#ModelAttribute(value="person") Person person,BindingResult result){
ModelAndView mv = new ModelAndView("home");
if(!result.hasErrors()) {
personRepo.delete(person.getId());
//personRepo.delete(person);
person = new Person();
mv.addObject("person", person);
}
mv.addObject("persons", personRepo.getAll());
return mv;
}
}
Home .jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!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">
</head>
<body>
<table align="center">
<c:forEach items="${persons}" var="person">
<tr>
<td>Welcome:</td>
<td><c:out value="${person.firstName}" /></td>
</tr>
<tr>
<td>Your lastname:</td>
<td><c:out value="${person.lastName}" /></td>
</tr>
</c:forEach>
</table>
<form:form modelAttribute="person" method="post" action="add.html">
<form:hidden path="id" />
<table>
<tr>
<td><form:label path="firstName">First Name:</form:label></td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td><form:label path="lastName">Last Name</form:label></td>
<td><form:input path="lastName" /></td>
</tr>
<tr>
<td><form:label path="money">Money</form:label></td>
<td><form:input path="money" /></td>
</tr>
</table>
<input type="submit" value="Save" />
</form:form>
</body>
</html>
From the looks of it, unless you are doing content negotiation, you don't have a controller method mapped to the URL add.html.
Compare:
<form:form modelAttribute="person" method="post" action="add.html">
and
#RequestMapping(value="/add", method=RequestMethod.POST)
Make it
<form:form modelAttribute="person" method="post" action="add">
and you should be fine.

List all data from database using asp.net mvc 2.0

I'm new to asp.net mvc 2.0.I have a question about listing data from database using asp.net mvc.
Controller
public ActionResult ListEmployee() {
UserModels emp = new UserModels();
emp.EmployeeList = (List<tblEmployee_Employee>)Session["list"];
return View(emp);
}
Model
public class GetEmployee
{
public string name { get; set; }
public string sex { get; set; }
public string email { get; set; }
}
And I have the view page employee.aspx page but I do not know how to write code in this view page.
please help me to solve this problem.
Thanks,
In ASP.NET MVC views need to be strongly typed to the model you are passing to them. So in your case you are passing a UserModels instance to your view. Assuming you already have a master page and you want to display in a table the list of employees you might have something along the lines of:
<%# Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<AppName.Models.UserModels>"
%>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<table>
<thead>
<tr>
<th>Name</th>
<th>Sex</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<% foreach (var employee in Model.EmployeeList) { %>
<tr>
<td><%= Html.Encode(employee.name) %></td>
<td><%= Html.Encode(employee.sex) %></td>
<td><%= Html.Encode(employee.email) %></td>
</tr>
<% } %>
</tbody>
</table>
</asp:Content>
or even better, define a reusable display template that will automaticall be rendered for each item of the EmployeeList collection property (~/Views/Shared/DisplayTemplates/GetEmployee.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<dynamic>"
%>
<tr>
<td><%= Html.DisplayFor(x => x.name) %></td>
<td><%= Html.DisplayFor(x => x.sex) %></td>
<td><%= Html.DisplayFor(x => x.email) %></td>
</tr>
and then in your main view simply reference this template:
<%# Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<AppName.Models.UserModels>"
%>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<table>
<thead>
<tr>
<th>Name</th>
<th>Sex</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<%= Html.EditorFor(x => x.EmployeeList)
</tbody>
</table>
</asp:Content>
Now you no longer need any foreach loops (as ASP.NET MVC will automatically render the display template if the property is a collection property following standard naming conventions) and also you have a reusable display template for your model.