I am a student and I have to develop a rest app using Java Spring, and the app is an online marks register. I have a StudentController class where I implemented a method in Java to show all the subjects which a student has and the grades related to each subject. I have an array list of hash maps that link a subject with the grades related to it. My problem is that I have to display the results from the Hash Maps from inside the list in the Html and even though I tried some things from the internet, it does not work. Can you please help me? Thank you in advance.
Here is the Java method:
#RequestMapping(value = "student")
public ModelAndView showGrades()
{
ModelAndView modelAndView = new ModelAndView();
List<Subject> subjects = subjectRepo.findAll();
Student student = new Student();
Person person = session.getUser();
ArrayList<HashMap<Subject, ArrayList<Integer> >> grades = new ArrayList<HashMap<Subject, ArrayList<Integer> >>();
student.setName(person.getName());
student.setAccount(person.getAccount());
for(int i=0; i<subjects.size(); i++){
HashMap<Subject, ArrayList<Integer> > mappingGrades = new HashMap<Subject, ArrayList<Integer>>();
Random rand = new Random();
ArrayList<Integer> studentGrades = new ArrayList<Integer>();
studentGrades.add(rand.nextInt(10));
studentGrades.add(rand.nextInt(10));
studentGrades.add(rand.nextInt(10));
mappingGrades.put(subjects.get(i), studentGrades);
student.setGrades(mappingGrades);
grades.add(mappingGrades);
}
modelAndView.addObject("grades", grades);
return modelAndView;
}
And here is the HTML code including my try for printing:
<!DOCTYPE html>
<html>
<head>
<!-- Site made with Mobirise Website Builder v4.11.4, https://mobirise.com -->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="generator" content="Mobirise v4.11.4, mobirise.com">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<link rel="shortcut icon" href="assets/images/logo4.png" type="image/x-icon">
<meta name="description" content="">
<title>Student</title>
<link rel="stylesheet" href="assets/web/assets/mobirise-icons/mobirise-icons.css">
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap-grid.min.css">
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap-reboot.min.css">
<link rel="stylesheet" href="assets/tether/tether.min.css">
<link rel="stylesheet" href="assets/dropdown/css/style.css">
<link rel="stylesheet" href="assets/theme/css/style.css">
<link rel="preload" as="style" href="assets/mobirise/css/mbr-additional.css">
<link rel="stylesheet" href="assets/mobirise/css/mbr-additional.css" type="text/css">
</head>
<body>
<section class="header1 cid-rLBDn2JTwv" id="header16-9">
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-10 align-center">
<h1 class="mbr-section-title mbr-bold pb-3 mbr-fonts-style display-1">
GRADES
</h1>
<p class="mbr-text pb-3 mbr-fonts-style display-5">
Subjects and related grades.
</p>
</div>
</div>
</div>
</section>
<section class="engine">bootstrap theme</section>
<section class="services5 cid-rLBDGcNu8T" id="services5-b">
<!---->
<!---->
<!--Overlay-->
<!--Container-->
<div class="container">
<div class="row">
<!--Titles-->
<div class="title pb-5 col-12">
</div>
<!--Card-1-->
<div class="card px-3 col-12">
<div class="card-wrapper media-container-row media-container-row">
<div class="card-box">
<div class="top-line pb-3">
<h4 class="card-title mbr-fonts-style display-5">
<table>
<tbody>
<form action="student" method="showGrades">
<div th:each="map : ${grades}">
<div th:each="mapEntry : ${map}">
<span th:text="${mapEntry.key}"></span> =
<span th:text="${mapEntry.value}"></span>
</div>
</div>
</form>
</tbody>
</table>
</h4>
<p class="mbr-text cost mbr-fonts-style m-0 display-5">
$400
</p>
</div>
<div class="bottom-line">
</div>
</div>
</div>
</div>
<!--Card-2-->
<!--Card-3-->
<!--Card-4-->
<!--Card-5-->
<!--Card-6-->
<!--Card-7-->
<!--Card-8-->
<!--Card-9-->
<!--Card-10-->
<!--Card-11-->
<!--Card-12-->
</div>
</div>
</section>
<script src="assets/web/assets/jquery/jquery.min.js"></script>
<script src="assets/popper/popper.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/tether/tether.min.js"></script>
<script src="assets/smoothscroll/smooth-scroll.js"></script>
<script src="assets/dropdown/js/nav-dropdown.js"></script>
<script src="assets/dropdown/js/navbar-dropdown.js"></script>
<script src="assets/touchswipe/jquery.touch-swipe.min.js"></script>
<script src="assets/theme/js/script.js"></script>
</body>
</html>
In the code you supplied the value of mapEntry.key is a Subject object and the value of mapEntry.value is an ArrayList. You need to tell thymeleaf how to output those objects. If Subject has a proper toString method it will work as you expect but an ArrayList will not print properly. You need to use another nested each statement or you need to join it into a single string.
Related
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.
I have a html page where I use jQuery to load page content from a spring boot application
here is the project structure
I m using zuul as proxy I m confident about the Zuul Eureka configuration on my project
When I try to access my root project page (facturation.html) by calling in browser for localhost:9999/facturation I'm getting the following exception
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "root folder where all thymeleaf files/facturation.html")
Caused by: java.io.FileNotFoundException: ClassLoader resource "root folder where all thymeleaf files/facturation.html" could not be resolved
at org.thymeleaf.templateresource.ClassLoaderTemplateResource.reader(ClassLoaderTemplateResource.java:130) ~[thymeleaf-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:223) ~[thymeleaf-3.0.6.RELEASE.jar:3.0.6.RELEASE]
java.io.FileNotFoundException: ClassLoader resource "root folder where all thymeleaf files/facturation.html" could not be resolved
My spring controller is as below
#Controller
public class LandingController {
private static final Logger log = LoggerFactory.getLogger(LandingController.class);
#Autowired
private AppClientFeign appClientFeign;
#Autowired
private UserClientFeign userClientFeign;
#RequestMapping("/")
String home(Model model,Principal principal) {
List<Menu> appMenus = appClientFeign.getAppMenus("facturation");
model.addAttribute("applications", appClientFeign.getApps());
model.addAttribute("applicationsHistory", appClientFeign.getAppsHistory(principal.getName()));
model.addAttribute("currentUser", userClientFeign.getUserDetails(principal.getName()));
if(log.isDebugEnabled()) {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append(appMenus);
stringBuilder2.append("");
log.debug(stringBuilder2.toString());
}
model.addAttribute("menuV", appMenus);
model.addAttribute("addClientObject", AddClientDTO.builder().build());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" hello world ****************** ---------------------- ************************ \n \n \n");
stringBuilder.append(appClientFeign.getApps());
if(log.isDebugEnabled())log.debug(stringBuilder.toString());
return "facturation";
}
#RequestMapping("/html/{page}")
String resolveHTML(Model model,Principal principal,#PathVariable String page) {
List<Menu> appMenus = appClientFeign.getAppMenus("facturation");
model.addAttribute("applications", appClientFeign.getApps());
model.addAttribute("applicationsHistory", appClientFeign.getAppsHistory(principal.getName()));
model.addAttribute("currentUser", userClientFeign.getUserDetails(principal.getName()));
if(log.isDebugEnabled()) {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append(appMenus);
stringBuilder2.append("");
log.debug(stringBuilder2.toString());
}
model.addAttribute("menuV", appMenus);
model.addAttribute("addClientObject", AddClientDTO.builder().build());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" hello world ****************** ---------------------- ************************ \n \n \n");
stringBuilder.append(appClientFeign.getApps());
if(log.isDebugEnabled())log.debug(stringBuilder.toString());
return page;
}
#RequestMapping("/html/{folder}/{page}")
String resolveHTML(Model model,Principal principal,#PathVariable String page,#PathVariable String folder) {
List<Menu> appMenus = appClientFeign.getAppMenus("facturation");
model.addAttribute("applications", appClientFeign.getApps());
model.addAttribute("applicationsHistory", appClientFeign.getAppsHistory(principal.getName()));
model.addAttribute("currentUser", userClientFeign.getUserDetails(principal.getName()));
if(log.isDebugEnabled()) {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append(appMenus);
stringBuilder2.append("");
log.debug(stringBuilder2.toString());
}
model.addAttribute("menuV", appMenus);
model.addAttribute("addClientObject", AddClientDTO.builder().build());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" hello world ****************** ---------------------- ************************ \n \n \n");
stringBuilder.append(appClientFeign.getApps());
if(log.isDebugEnabled())log.debug(stringBuilder.toString());
return folder+"/"+page;
}
}
My facturation.htl page is
<!DOCTYPE HTML>
<html lang="fr">
<head>
<meta charset="UTF-8"/>
<title>Facturation - MDS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/loader.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/main.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/facturation.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/chart.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/menus.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/grid.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/tab.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/notify.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/print.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/check.js"></script>
<script onloadstart="loadAdditionalData()" src="http://localhost:9999/MDS-WEB-RESSOURCE/js/facturationLoader.js"></script>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/main.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/facturation.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/chart.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/grid.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/tab.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/notify.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/menus.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/dropdown.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/check.css"/>
</head>
<body>
<div id="overlay" class="overlay">
<div class="form-container">
</div>
</div>
<div style="height: 100%;">
<div id="header" class="header">
</div>
<div id="menu0" class="menu-V">
</div>
<div class="container">
<div id="menu0-func0-panel" class="main-panel" style="display: block;">
</div>
<div id="menu0-func1-panel" class="main-panel">
</div>
<div id="menu0-func2-panel" class="main-panel">
</div>
<div id="menu0-func3-panel" class="main-panel">
</div>
</div>
</div>
</body>
</html>
finally loader.js is as below
$(document).ready(function() {
$("#header").load("http://"+document.location.host+"/facturation/html/facturation-header");
$("#menu0").load("http://"+document.location.host+"/facturation/html/facturation-menu0");
$("#menu0-func0-panel").load("http://"+document.location.host+"/facturation/html/facturation-menu0-func0-panel", function() {
var option={
parent: "#stat-container",
type: "Pie",
labels: ['FACTURES EN ATTENTE', 'FACTURES EN RETARD (- DE 30 JOURS)', 'FACTURES EN RETARD (+ DE 30 JOURS)'],
data: [20, 15, 10],
colors: ["#0ae1ff", "#067180", "#dd4d40"],
canvasWidth: 250,
canvasHeight: 250,
legendType: "value",
legendPosition: "bottom",
legendUnit: "DZD",
overlay: false
};
chart(option);
});
$("#menu0-func1-panel").load("http://"+document.location.host+"/facturation/html/facturation-menu0-func1-panel");
$("#menu0-func2-panel").load("http://"+document.location.host+"/facturation/html/facturation-menu0-func2-panel");
$("#menu0-func3-panel").load("http://"+document.location.host+"/facturation/html/facturation-menu0-func3-panel");
});
to be honest, I don't have the slightest clue why I m getting this, nor an idea about what should I do or try.
NB: I m using zuul and eureka as mentioned, my service is named facturation that why I'm adding facturation after zuul address so he knows which service to contact
using this question I configured thymeleaf to get my pages from the classpath
I am trying to validate the login and password of the user, in that if not enter the login fields and password will appear a message in the screen "Please fill in the fields of login or password" or if the user type the wrong username or password will appear an "Incorrect Login or Password" screen message but it does not show the messages.
Why does not it show the message on the jsp page?
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String vazio="Por favor preencha os campos de login ou senha";
String incorretos="Login ou senha incorretos";
String login = request.getParameter("login");
String senha = request.getParameter("senha");
Cliente cli= new Cliente();
LoginDAO login2= new LoginDAO();
Cliente login_validacao=login2.validacaoLogin(login,senha);
if(login_validacao.getLogin()==null && login_validacao.getSenha()==null){
request.setAttribute("vazio", vazio);
}
else if(login_validacao.getLogin().equals(request.getParameter("login"))
& login_validacao.getSenha().equals((request.getParameter("senha")))){
RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
else{
request.setAttribute("incorreto", incorretos);
}
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="js/jquery-1.12.0.min.js" type="text/javascript"></script>
<script src="js/jquery.maskedinput.js" type="text/javascript"></script>
<script src="js/jquery.maskedinput.min.js" type="text/javascript">
</script>
<script src="bootstrap/bootstrap.min.js" type="text/javascript">
</script>
<script src="bootstrap/bootstrap.js" type="text/javascript"></script>
<link rel="stylesheet" href="bootstrap/bootstrap.css">
<link rel="stylesheet" href="css/css.css" type="text/css">
<link rel="stylesheet" href="css/font-awesome.min.css" type="text/css"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-
awesome.min.css" rel="stylesheet">
<title>JSP Page</title>
</head>
<body>
<div class="login-form">
<div class="row">
<div class="col-6 col-md-4"></div>
<div class="col-6 col-md-4">
<h2 id="AcesseConta"><span>Acesse sua Conta</span></h2>
<label for="vazio_resposta">${vazio}</label>
<label for="validacao">${incorreto}</label>
</div>
</div>
<div class="row">
<div class="col-6 col-md-4"></div>
<div class="col-6 col-md-4">
Login:<input type="text" id="login" name="login" ><br/><br/>
Senha:<input type="text" id="senha" name="senha" ><br/>
Não é cadastrado?Cadastre-se<br/><br/>
</div>
</div>
<div class="row">
<div class="col-6 col-md-4"></div>
<div class="col-6 col-md-4">
<div id="teste"></div>
<button type="button" onclick="login()" >Entrar</button> <button
type="button" onclick="" >Esqueceu a Senha?</button>
</div>
</div>
</div>
</body>
</html>
Instead of validating HTML Form Using Controller/Servlet You Can use 'REQUIRED' tag in html as follow.
Login:<input type="text" id="login" name="login" Required><br/><br/>
Senha:<input type="text" id="senha" name="senha" Required><br/>
And Displaying message on JSP from servlet use below code
for Servlet
if(login_validacao.getLogin()==null && login_validacao.getSenha()==null)
{
response.sendRedirect("login.jsp?vazio=" + URLEncoder.encode(vazio, "UTF-8"));
}
else if(login_validacao.getLogin().equals(request.getParameter("login"))
& login_validacao.getSenha().equals((request.getParameter("senha"))))
{
RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
else
{
response.sendRedirect("login.jsp?incorretos=" + URLEncoder.encode(incorretos, "UTF-8"));
}
FOR JSP
<c:if test="${!empty vazio}">
<p style="color:red;" align="center">${param.vazio}</p>
</c:if>
In my web application, I have a home page where the options available to the user are placed in a fixed sidebar in the top of the screen, and each one of this options are opened inside of a tag <div> in this same page.
My problem is: when this content is a form, and I submit it to the server, after the processing, the output page isn't opened in this <div>, but in the entire navigation space. What I want is a way of capture this return and display it in the same <div> it was originated.
the code for my home page is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../assets/ico/favicon.ico">
<title>HorarioLivre</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="navbar-fixed-top.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body onload="close_page()">
<!-- Fixed navbar -->
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">HorarioLivre</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>Evento</li>
<li>Lista Horarios</li>
<li>Cadastra Horarios</li>
<li>Usuarios</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
${usuario.nome} <b class="caret"></b>
<ul class="dropdown-menu">
<li>Perfil</li>
<li>Configurações</li>
<li>Sair</li>
</ul>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container">
<div class="page-header">
<h1></h1>
</div>
<div class="panel panel-default" id="results">
<div class="panel-heading">
<div align="right"><button type="button" class="btn btn-lg btn-danger" onclick="close_page()">Fechar</button></div>
</div>
<div class="panel-body" id="content">
Panel content
</div>
</div>
</div> <!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
function load_page(url){
$('#results').css("display", "block");
$('#content').load(url);
$('#container').draggable();
}
function close_page(){
$('#results').css("display", "none");
$('#content').empty();
}
</script>
</body>
</html>
I am using Spring, and the pages linked here are handled by Controller. By example,the page "cadastra_evento.html" is:
<%# 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">
<title>Lista de Eventos</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="alert alert-info">
<strong>Eventos</strong> Segue a lista de eventos cadastrados.
</div>
<div class="container">
<div class="row">
<div class="col-md-3">Nome</div>
<div class="col-md-3">Descrição</div>
<div class="col-md-3">Periodo</div>
<div class="col-md-3">Duração</div>
</div>
<c:forEach var="item" items="${lista}">
<div class="row">
<div class="col-md-3"><c:out value="${item.nome}"/></div>
<div class="col-md-3"><c:out value="${item.descricao}"/></div>
<div class="col-md-3"><c:out value="${item.data_inicial}"/> - <c:out value="${item.data_final}"/></div>
<div class="col-md-3"><c:out value="${item.duracao}"/></div>
</div>
</c:forEach>
</div>
<div class="alert alert-info">
<strong>Novo</strong> Cadastre um novo evento.
</div>
<form method="post" action="cad_evento.html">
<input type="text" name="nome" placeholder="Nome" size=20 maxlength=40> <br/>
<input type="text" name="descricao" placeholder="Descrição" size=30 maxlength=100> <br/>
<h3>Periodo da Data</h3>
inicio: <input name="data_inicial" placeholder="DD-MM-AAAA" required pattern="\d{2}-\d{2}-\d{4}" /> <br/>
final: <input name="data_final" placeholder="DD-MM-AAAA" required pattern="\d{2}-\d{2}-\d{4}" /> <br/>
<h3>Periodo do Horário</h3>
inicio: <input name="hora_inicial" placeholder="HH:MM:SS" required pattern="\d{2}:\d{2}:\d{2}" /> <br/>
final: <input name="hora_final" placeholder="HH:MM:SS" required pattern="\d{2}:\d{2}:\d{2}" /> <br/>
<input type="text" name="duracao" placeholder="duração" size=20 maxlength=2> <br/>
<button type="submit" class="btn btn-lg btn-primary">Cadastrar</button>
</form>
</body>
</html>
To finish, the page "cad_evento.html" used as action for the form above, is handled by method of same name from Controller:
#RequestMapping(value="/cad_evento", method=RequestMethod.POST)
public ModelAndView cadastra_evento(#RequestParam("nome") String nome, #RequestParam("descricao") String descricao, #RequestParam("data_inicial") String data_inicial, #RequestParam("hora_inicial") String hora_inicial, #RequestParam("data_final") String data_final, #RequestParam("hora_final") String hora_final, #RequestParam("duracao") int duracao) {
if(sessao != null)
{
if(sessao.getUsuario().temAutorizacao("cad_evento"))
{
Date d_inicio = new Date(Date.parse(data_inicial));
Date d_final = new Date(Date.parse(data_final));
Time h_inicio = new Time(Time.parse(hora_inicial));
Time h_final = new Time(Time.parse(hora_final));
EventoDAO evento = new EventoDAO(nome, descricao, d_inicio, d_final, h_inicio, h_final, duracao, sessao.getUsuario());
int saida = evento.cadastra();
if(saida == 0)
{
ModelAndView mav = new ModelAndView();
mav.addObject("message", "Erro ao cadastrar o evento");
return mav;
}
else
{
ModelAndView mav = new ModelAndView();
mav.setViewName("/listagem_evento");
return mav;
}
}
else
{
ModelAndView mav = new ModelAndView();
mav.addObject("message", "Usuário sem permissão de acesso");
return mav;
}
}
else
{
ModelAndView mav = new ModelAndView();
mav.setViewName("/usuario_login_page");
return mav;
}
}
Someone have any thoughts about how to do that?
Well, spring mvc just open new page with a content you set in ModelAndView. If you want to load somthing just in some part of page ( in this case ) there pure javascript / jquery ajax is needed. So steps needed here:
Add javascript which will do ajax request to controller
Controller need to return JSON ( #ResponseBody can help you )
You have to do some DOM manipulation using javascript/jquery to put JSON answer to your div.
I am adding a parameter in the url of the page of I was trying to go but in the generated url it is not being shown, why is that?
Here's my jsp.
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sj" uri="/struts-jquery-tags"%>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<sj:head ajaxhistory = "true" ajaxcache="true" />
<script>
</script>
</head>
<body>
<h5>Struts Jquery Ajax Integration</h5>
<div id="resultContent"></div>
<noscript>Please Turn On Javascript to make the full use of this site</noscript>
<h4>Choose A task</h4>
<ul>
<s:url value="views/ajaxvalidation.jsp" var="ajaxvalidation" >
<s:param name="menuId" value="1"/>
</s:url>
<li><sj:a targets="resultContent" href="%{ajaxvalidation}">Ajax Validation</sj:a></li>
</ul>
<div>
<h6>Play A Music while You Navigate</h6>
<audio src="x.mp3" controls>Your browser does not support the
audio element.
</audio>
</div>
</body>
</html>
The URL That is being shown is this
http://localhost:8090/HelloStruts2/#resultContent=_sj_action_anchor_860825673resultContent
Where is the menuId parameter that I have added in the url?
I do not know if this will make a difference but I am using this plugin for jquery.
struts2-jquery
Generated HTML
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="/HelloStruts2/struts/js/base/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="/HelloStruts2/struts/js/base/jquery.ui.core.min.js?s2j=3.5.0"></script>
<script type="text/javascript" src="/HelloStruts2/struts/js/plugins/jquery.subscribe.min.js"></script>
<script type="text/javascript" src="/HelloStruts2/struts/js/plugins/jquery.ba-bbq.min.js"></script>
<script type="text/javascript" src="/HelloStruts2/struts/js/struts2/jquery.struts2.min.js?s2j=3.5.0"></script>
<script type="text/javascript">
$(function() {
jQuery.struts2_jquery.version="3.5.0";
jQuery.scriptPath = "/HelloStruts2/struts/";
jQuery.struts2_jquery.ajaxhistory = true;
jQuery.ajaxSettings.traditional = true;
jQuery.ajaxSetup ({
cache: false
});
jQuery.struts2_jquery.require("js/struts2/jquery.ui.struts2.min.js");
jQuery(window).trigger('hashchange');
});
</script>
<link id="jquery_theme_link" rel="stylesheet" href="/HelloStruts2/struts/themes/smoothness/jquery-ui.css?s2j=3.5.0" type="text/css"/>
<script>
</script>
</head>
<body>
<h5>Struts Jquery Ajax Integration By Kyel</h5>
<div id="resultContent"></div>
<noscript>Please Turn On Javascript to make the full use of this site</noscript>
<h4>Choose A task</h4>
<ul>
<li><a id="anchor_2068827505" href="javascript:void(0)">Ajax Validation</a>
<script type='text/javascript'>
jQuery(document).ready(function () {
var options_anchor_2068827505 = {};
options_anchor_2068827505.jqueryaction = "anchor";
options_anchor_2068827505.id = "anchor_2068827505";
options_anchor_2068827505.targets = "resultContent";
options_anchor_2068827505.href = "views/ajaxvalidation.jsp";
options_anchor_2068827505.hrefparameter = "menuId=1";
jQuery.struts2_jquery.bind(jQuery('#anchor_2068827505'),options_anchor_2068827505);
});
</script></li>
<li><a id="anchor_1381525763" href="javascript:void(0)">Thank you JSP</a>
<script type='text/javascript'>
jQuery(document).ready(function () {
var options_anchor_1381525763 = {};
options_anchor_1381525763.jqueryaction = "anchor";
options_anchor_1381525763.id = "anchor_1381525763";
options_anchor_1381525763.targets = "resultContent";
options_anchor_1381525763.href = "views/thankyou.jsp";
options_anchor_1381525763.hrefparameter = "menuId=2";
jQuery.struts2_jquery.bind(jQuery('#anchor_1381525763'),options_anchor_1381525763);
});
</script></li>
</ul>
<div>
<h6>Play A Music while You Navigate</h6>
<audio src="x.mp3" controls>Your browser does not support the
audio element.
</audio>
</div>
</body>
Use action tag and use nested param tag see below code .
<s:url id="login" action="admin/showProfile" var="profileUrl">
<s:param name="user">Rais</s:param>
</s:url>
<a href='<s:property value="#profileUrl"/>'>
<s:property value="#profileUrl"/></a>