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.
Related
I tried to create POST request to send my form to the Spring server, but I'm only getting this error:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'form' available as request attribute
My controller content:
// Form post handler
#PostMapping("/")
public String home(#ModelAttribute Form form, BindingResult bindingResult, Model model) {
Gson g = new Gson();
Form form_new = g.fromJson(JavaWebApplication.runtimeJsonContent, Form.class);
model.addAttribute("form", form);
model.addAttribute("ip", form.IP);
model.addAttribute("gateway", form.Gateway);
model.addAttribute("port", form.Port);
model.addAttribute("IncomingConnections", form.IncomingConnections);
return "index";
}
Here is my Form model:
public class Form {
public String IP;
public String Gateway;
public int Port;
public boolean IncomingConnections;
public int QoSEnable = 0;
public Form(){}
public Form(String IP, String gateway, int port, boolean incomingConnections) {
this.IP = IP;
this.Gateway = gateway;
this.Port = port;
this.IncomingConnections = incomingConnections;
this.QoSEnable = 0; // Assert that 0 is default
ExportToJson(this);
}
public Form(String IP, String gateway, int port, boolean incomingConnections, int qosEnable) {
this.IP = IP;
this.Gateway = gateway;
this.Port = port;
this.IncomingConnections = incomingConnections;
this.QoSEnable = qosEnable;
ExportToJson(this);
}
}
And my index.html webpage bound on / :
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" th:href="#{./styles/main.css}">
<title>Document</title>
</head>
<body>
<form method="post" action="#" th:action="#{/}" th:object="${form}">
<div id="container">
<img src="https://kable-swiatlowodowe.net.pl/wp-content/uploads/2017/08/mikrotik.png" width="20%" style="margin-bottom: 5%;">
<br>
<div id="input-el">
<div class="input-element"><input type="text" placeholder="IP" name="IP" th:value="${ip}" th:field="*{IP}" id="input-element-ip"></div>
<div class="input-element"><input type="text" placeholder="Gateway" th:value="${gateway}" th:field="*{Gateway}" name="Gateway" id="input-element-gateway"></div>
<div class="input-element"><input type="number" placeholder="Port" th:value="${port}" th:field="*{Port}" name="Port" id="input-element-port"></div>
</div>
<div id="checkbox-el">
Incoming connections:<br>
<label><input type="checkbox" th:checked="${IncomingConnections}" th:field="*{IncomingConnections}" name="conections" id="conections-el">Allow</label>
</div>
QoS Mode<br>
<label><input type="radio" name="qos-mode-el" id="input-radio-game-first" checked>Game First</label>
<label><input type="radio" name="qos-mode-el" id="input-radio-multimedia-first">Multimedia First</label>
<button type="submit">Save</button>
</div>
</form>
</body>
</html>
Sample Postman request:
Response for this request:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./styles/main.css">
<title>Document</title>
</head>
<body>
<form method="post">
<div id="container">
<img src="https://kable-swiatlowodowe.net.pl/wp-content/uploads/2017/08/mikrotik.png" width="20%" style="margin-bottom: 5%;">
<br>
<div id="input-el">
<div class="input-element">
<input type="text" placeholder="IP" name="IP" value="" id="input-element-ip"></div>
<div class="input-element">
<input type="text" placeholder="Gateway" value=""name="Gateway" id="input-element-gateway"></div>
<div class="input-element">
<input type="number" placeholder="Port" value="0" name="Port" id="input-element-port"></div>
</div>
<div id="checkbox-el">
Incoming connections:<br>
<label><input type="checkbox" name="conections" id="conections-el">Allow</label>
</div>
QoS Mode<br>
<label><input type="radio" name="qos-mode-el" id="input-radio-game-first" checked>Game First</label>
<label><input type="radio" name="qos-mode-el" id="input-radio-multimedia-first">Multimedia First</label>
<button type="submit">Save</button>
</div>
</form>
</body>
</html>
Each value content is clear
Any idea how to make this binding work correctly?
you are not passing the form object to your thymeleaf template
Do this -
#GETMapping("/")
public String getHome(Model model){
model.addAttribute("form", new Form());
return "index";
}
This will return a Form object to your thymleaf and then it can process the data in your code --
<form method="post" action="#" th:action="#{/}" th:object="${form}">
// This will now receive form object
</form>
I have problem with paginate, I use grails 2.4.4
This my index.gsp:
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title></title>
</head>
<body>
<div>
<g:paginate controller="user" action="index" total="${userTotal}"/>
</div>
</body>
</html>
This is my controller:
class UserController {
def index() {
List<User> users = User.findAll()
render(view: "index", model: [users: users, userTotal: 4])
}
}
In the console I don't have any error and in my page I see nothing.
Array users isn't empty, I checked.
render(view: "index", model: [users: users, userTotal: 4])
You have hardcoded userTotal to be 4. The paginate tag defaults to 10 items per page, so pagination is not required.
If you are concerned about pagination then User.findAll() is probably a bad idea because it will return all of the data.
Default scaffolding will do something like this which is a better idea...
Controller action:
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
respond userService.list(params), model:[userCount: userService.count()]
}
GORM Data Service:
import grails.gorm.services.Service
#Service(User)
interface UserService {
User get(Serializable id)
List<User> list(Map args)
Long count()
void delete(Serializable id)
User save(User user)
}
The relevant GSP:
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main" />
<g:set var="entityName" value="${message(code: 'user.label', default: 'User')}" />
<title><g:message code="default.list.label" args="[entityName]" /></title>
</head>
<body>
<g:message code="default.link.skip.label" default="Skip to content…"/>
<div class="nav" role="navigation">
<ul>
<li><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></li>
<li><g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link></li>
</ul>
</div>
<div id="list-user" class="content scaffold-list" role="main">
<h1><g:message code="default.list.label" args="[entityName]" /></h1>
<g:if test="${flash.message}">
<div class="message" role="status">${flash.message}</div>
</g:if>
<f:table collection="${userList}" />
<div class="pagination">
<g:paginate total="${userCount ?: 0}" />
</div>
</div>
</body>
</html>
If you really don't want to use a service (highly recommended that you do) then you could change the controller to do something like this...
params.max = Math.min(max ?: 10, 100)
respond User.list(params), model:[userCount: User.count()]
It is my solution:
gsp:
<div class="content scaffold-list">
<g:form controller="user" action="index">
<label>Input user's name:</label>
<div class="form-group">
<g:textField name="userName"/>
<g:submitButton name="search"/>
</div>
<g:each var="user" in="${users}">
<p>User with name: ${user.name}</p>
</g:each>
</g:form>
<div class="pagination">
<g:paginate controller="user" action="index"
max="5" total="${userCount}"/>
</div>
</div>
controller:
def index(String userName) {
initUsersAndPokemons()
PagedResultList users = fourthService.findUsersByName(
userName,
params.int('max', 5),
params.int('offset', 0))
[users: users, userCount: users.getTotalCount()]
}
service:
PagedResultList findUsersByName(String userName, int max, int offset) {
BuildableCriteria bc = User.createCriteria()
bc.list(max: max, offset: offset) {
like('name',userName)
}
}
i'm have problem with load page by id. I'm creating simple forum in Spring and when i created topic i got page like this /topic/10 (10 is id topic) and nextly i want to add inscription to this topic so after click button submit should be /inscription/topic/10 (10 is id topic). Now is the problem, when i click button i got Error 405 but when i take this line and write by hand or copy address and paste it again then i got inscription page. Where is problem? Its can be thymeleaf or spring request?
Code is below
#Controller
#RequestMapping("/inscription/")
public class InscriptionController {
private InscriptionService inscriptionService;
private TopicService topicService;
#Autowired
private InscriptionController(InscriptionService inscriptionService, TopicService topicService) {
this.inscriptionService = inscriptionService;
this.topicService = topicService;
}
#GetMapping("topic/{id}")
public String in2(#ModelAttribute("inscription") Inscription inscription, #PathVariable Long id, Model model) {
Topic topic = topicService.findOne(id);
model.addAttribute("inscription", inscription);
return "inscription";
}
Thymeleaf - here when i press button New Message should be go to inscription/topic/id
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Create new topic</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-light" style="background-color: #969bd9;">
<span class="navbar-brand">Create new topic</span>
</nav>
<div class = "container">
<div class = "row">
<div class = "col-md6 col-md-offset-3">
<form th:action="#{/inscription/topic/{id}(id = ${topic.id})}" th:object="${inscription}" method="post">
<h5>
<a th:href="#{/topic/{id}(id = topic.id)}"></a>
<span th:text="${topic.title}"></span>
</h5>
<div class="col s10">
<div class="row">
<div class="col s11">
Stworzony
<p th:text="${topic.createdAt} ? ${#calendars.format(topic.createdAt, 'HH:mm dd MMMM yyyy')}"></p>
<p th:utext="${#strings.replace(topic.text,T(java.lang.System).getProperty('line.separator'),'<br />')}"></p>
<div class="divider"></div>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">New message</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
405 error means "Method Not Allowed". When you click the submit button, your form will perform the POST method, which doesn't have the corresponding mapping in your controller. You should add POST mapping to your controller or change the form method to GET.
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.
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.