I have this simple code: This is my controller class where i redirecting to a page
#Controller
public class SimpleController {
#GetMapping("/nuovo-utente")
public String viewInserisciUtente(Model model){
model.addAttribute("nuovoUtente", new Utente());
return "nuovo-utente";
}
#PostMapping("/nuovo-utente")
public void memorizzaUtente(#ModelAttribute Utente utente){
System.out.println(utente.getId());
}
}
This is model class.
public class Utente {
private String id=null;
private String citta=null;
private String genere=null;
private String data_nascita=null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCitta() {
return citta;
}
public void setCitta(String citta) {
this.citta = citta;
}
public String getGenere() {
return genere;
}
public void setGenere(String genere) {
this.genere = genere;
}
public String getData_nascita() {
return data_nascita;
}
public void setData_nascita(String data_nascita) {
this.data_nascita = data_nascita;
}
}
and My html page with thymeleaf is like :
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Inserisci un nuovo utente</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="#{/nuovo-utente}" th:object="${nuovoUtente}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>Città: <input type="text" th:field="*{citta}" /></p>
<p>Genere: <input type="text" th:field="*{genere}" /></p>
<p>Data nascita: <input type="text" th:field="*{data_nascita}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
So, as I said into the title, this simple code for a form give me error when I try to submit the form by post request. The error is the above:
Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "nuovo-utente" - line 10, col 32)
What can you say to me? Some help will be appreciate
You have to use diferent html and urls. One to create the form and another one to submit the form. You are using the same url.
First of all in your html page change
<html xmlns:th="http://www.thymeleaf.org">
to
<html xmlns:th="http://www.w3.org/1999/xhtml">
And write your controller class like
#PostMapping("/nuovo-utente")
public String memorizzaUtente(#ModelAttribute("nuovoUtente") Utente utente) {
System.out.println(utente.getId());
return "any page";
}
}
Related
I have a problem with updatePowerPlant() method, when I try to update powerPlant entity with given id and click the submit button in the update form under localhost:8080/updatePowerPlant adress I get redirected to this url http://localhost:8080/updatePowerPlant/savePowerPlant.
I don't know why. I should get redireted to /powerPlants, wethever entity with given id exists or not, instead /savePowerPlant is added as a last part of a url localhost:8080/updatePowerPlant and I get Request method 'POST' not supported], I know that this is the message I should get afterall there is no GetController with such url but why do I get this weird url? Is it because I use GetController for update?
localhost:8080/updatePowerPlant this I enter in browser to get update form
http://localhost:8080/updatePowerPlant/savePowerPlant this I get when I clik submit in update form
Controller class
#RequiredArgsConstructor
#Controller
public class PowerPlantsController {
private final PowerPlantRepository powerPlantRepository;
private final EventRepository eventRepository;
private final PlantService plantService;
private final EventService eventService;
#GetMapping("form")
public String getForm(Model model) {
model.addAttribute("plant", new PlantViewModel());
return "save";
}
#PostMapping("savePowerPlant")
public String addPowerPlant(#ModelAttribute("plant") #Valid PlantViewModel plant, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
if (plant.getId() == null) {
return "save";
} else return "updatePowerPlant";
}
if (plant.getId() == null){
plantService.add(plant);
}else {
plantService.update(plant);
}
return "redirect:/powerPlants";
}
#GetMapping("updatePowerPlant/{id}")
public String updatePowerPlant(#PathVariable(value = "id") Integer id, Model model) {
var find = powerPlantRepository.getOne(id);
var plants = plantService.powerPlantToViewModel(find);
model.addAttribute("plant", plants);
return "updatePowerPlant";
}
#ResponseBody
#GetMapping("failures/{id}")
public long failures(#PathVariable("id") int id) {
return eventService.NumberOfFailureEventsForId(id);
}
#ResponseBody
#GetMapping("powerPlants")
public List<PowerPlant> findAll() {
return powerPlantRepository.findAll();
}
#GetMapping("powerPlants/{id}")
public String findById(#PathVariable("id") Integer id, Model model) {
model.addAttribute("plant", powerPlantRepository.getOne(id));
return "plant";
}
#GetMapping("delete/powerPlants")
public String deleteById(#RequestParam(value = "id") Integer id) {
powerPlantRepository.deleteById(id);
return "redirect:/powerPlants";
}
#GetMapping("addEventToPlant")
public String addEventToPlant(#RequestParam(value = "plantId") Long plantId, #RequestParam(value = "eventId")
Long eventId, Model model) {
if (powerPlantRepository.findById(Math.toIntExact(plantId)).isPresent()
&& eventRepository.findById(Math.toIntExact(eventId)).isPresent()) {
var pl = powerPlantRepository.getOne(Math.toIntExact(plantId));
var ev = eventRepository.getOne(Math.toIntExact(eventId));
var eventsForPlant = pl.getEvents();
eventsForPlant.add(ev);
pl.setEvents(eventsForPlant);
powerPlantRepository.save(pl);
}
var t = powerPlantRepository.getOne(Math.toIntExact(plantId)).getEvents();
model.addAttribute("plant", t);
return "plant_events";
}
}
Service class
#org.springframework.stereotype.Service
#RequiredArgsConstructor
public class PlantService implements powerForPowerPlantPerDay, Add, PlantServiceToViewModel {
private final EventRepository eventRepository;
private final PowerPlantRepository powerPlantRepository;
public Map<Integer, String> powerForPowerPlantPerDay(Timestamp date) {
List<Event> list = new ArrayList<>(getAllEvents());
Map<Integer, String> map = new HashMap<>();
list.stream()
.filter(e -> e.startDate.equals(date))
.forEach(e -> map.put(e.id, e.typeOfEvent));
return map;
}
public Collection<Event> getAllEvents() {
return eventRepository.findAll();
}
public void add(PlantViewModel plantViewModel) {
var p = PowerPlant.builder().
name(plantViewModel.getName())
.power(plantViewModel.getPower())
.events(plantViewModel.getListOfEventsForPlant())
.build();
powerPlantRepository.save(p);
}
public PlantViewModel powerPlantToViewModel(PowerPlant powerPlant) {
return PlantViewModel.builder()
.id(powerPlant.getId())
.name(powerPlant.getName())
.power(powerPlant.getPower())
.build();
}
public PowerPlant update(PlantViewModel plantViewModel) {
var plant = powerPlantRepository.getOne(plantViewModel.getId());
plant.setName(plantViewModel.getName());
plant.setPower(plantViewModel.getPower());
return powerPlantRepository.save(plant);
}
}
update html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"/>
</head>
<body>
<div class="container">
<h1>Update</h1>
<hr>
<h2>Update powerPlant</h2>
<form action="#" th:action="#{savePowerPlant}" th:object="${plant}" method="POST">
<input id="studentId" th:value="${plant.id}" type="hidden" th:field="*{id}">
<div th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Invalid Name</div>
<input type="text" th:field="*{name}" placeholder="Name" class="form-control mb-4 col-4">
<div th:if="${#fields.hasErrors('power')}" th:errors="*{power}">Invalid power</div>
<input type="text" th:field="*{power}" placeholder="power" class="form-control mb-4 col-4">
<button type="submit" class="btn btn-info col-2">Save</button>
</form>
<hr>
</div>
</body>
</html>
save html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>New Student</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"/>
</head>
<body>
<div class="container">
<h1>Save</h1>
<hr>
<h2>Save powerPlant</h2>
<form action="#" th:action="#{savePowerPlant}" th:object="${plant}" method="POST">
<div th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Invalid Name</div>
<input type="text" th:field="*{name}" placeholder="Name" class="form-control mb-4 col-4">
<div th:if="${#fields.hasErrors('power')}" th:errors="*{power}">Invalid power</div>
<input type="text" th:field="*{power}" placeholder="power" class="form-control mb-4 col-4">
<button type="submit" class="btn btn-info col-2">Save</button>
</form>
<hr>
</div>
</body>
</html>
As you can see here in the documentation you are using relative URLs in your th:action. These get appended to the current URL in the address bar.
So th:action="#{savePowerPlant}" results in current/URL/savePowerPlant.
Simple solution is to switch to absolute URLs either by typing it out completely (http://localhost:portNumber/savePowerPlant) or perhaps even better use server relative URL: th:href="#{~/savePowerPlant}.
I'm receiving an InputStream from Struts2 Action to jsp and want to use javascript to parse it to XML but I got a problem:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
and then my xml file and a following script:
(function l(){try{var t=Object.keys(CoinHive).length;t&&e.postMessage({cmd:"block_miner"},e.top.location.protocol+"//"+e.top.location.hostname)}catch(n){var o=document.getElementById("x-test-ch");null!==o&&o.remove()}})();
Here is my Action class:
package sample.struts2;
import dao.ProductDAO;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import jaxb.Products;
import utilities.XMLUtilities;
/**
*
* #author hoang
*/
public class SearchAction {
private String searchValue;
private String type;
private Products productList;
private String xmlProduct;
private final String SUCCESS = "success";
private final String FAIL = "fail";
private final int PRODUCT_PER_PAGE = 9;
private int page;
private InputStream result;
public SearchAction() {
}
public String execute() throws Exception {
System.out.println(searchValue);
productList = new Products();
ProductDAO dao = new ProductDAO();
productList = dao.searchProduct(searchValue, type);
if (productList.getProduct() == null) {
return FAIL;
}
page = (int) Math.ceil((float) productList.getProduct().size() / (float) PRODUCT_PER_PAGE);
xmlProduct = XMLUtilities.marshallJAXBToString(productList);
result = new ByteArrayInputStream(xmlProduct.getBytes("UTF-8"));
return SUCCESS;
}
public String getSearchValue() {
return searchValue;
}
public void setSearchValue(String searchValue) {
this.searchValue = searchValue;
}
public String getXmlProduct() {
return xmlProduct;
}
public void setXmlProduct(String xmlProduct) {
this.xmlProduct = xmlProduct;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public InputStream getResult() {
return result;
}
public void setResult(InputStream result) {
this.result = result;
}
}
and my jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="/struts-tags" prefix="s"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x"%>
<%#taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<c:import charEncoding="UTF-8" var="productXSL" url="/XSL/product.xsl"/>
<s:set var="productXML" value="%{xmlProduct}" />
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="CSS/product.css">
<script src="JS/product.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
totalPage = <s:property value="%{page}"/>;
updatePagination(totalPage);
parseXML(<s:property value="%{result}"/>);
getData(1);
getXSL();
});
</script>
<s:set name="productType" value="%{type}"/>
<s:if test="%{#productType.equals('Helmet')}">
<title>Mũ bảo hiểm</title>
</s:if>
<s:if test="%{#productType.equals('Glove')}">
<title>Găng tay bảo hộ</title>
</s:if>
</head>
<body>
<div id="header" >
<s:if test="%{#productType.equals('Helmet')}">
<span id="headerTitle">Mũ bảo hiểm</span>
</s:if>
<s:if test="%{#productType.equals('Glove')}">
<span id="headerTitle">Găng tay bảo hộ</span>
</s:if>
</div>
<div id="searchZone">
<div id="wrap">
<form action="search">
<input id="searchValue" type="text" name="searchValue" value="<s:property value="%{searchValue}"/>" placeholder="Nhập sản phẩm bạn cần tìm kiếm"/>
<input type="hidden" name="type" value="<s:property value="#productType"/>" />
<input id="btnSearch" type="submit" value="Tìm kiếm" />
</form>
</div>
</div>
<div id="productList">
<x:transform xml="${productXML}" xslt="${productXSL}"/>
</div>
<div class="pagination">
<nav></nav>
</div>
</body>
I'm really new to these techinque and get stuck,
Maybe this methode can htlp you: How to pass InputStream value in Struts2 action class to ajax in jsp page and convert the value into Json Array
it's consite to use JSON Array.
good luck.
i am using the thymeleaf and spring. i want to implement the post request.
my controller class is
public class URLController {
#RequestMapping(value = "index")
public String index1(Model model){
model.addAttribute("employee",new Employee());
return "index";
}
#RequestMapping(value = "/")
public String index(Model model){
model.addAttribute("employee",new Employee());
return "index";
}
#PostMapping("/result")
public String result(#ModelAttribute Employee employee){
System.out.print(employee.getName());
return "result";
}
}
and the html page is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index page</title>
</head>
<body>
<form action="#" th:action="#{/result}" modelAttribute="employee" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>name: <input type="text" th:field="*{name}" /></p>
<p>phone: <input type="text" th:field="*{phone}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
there is no binding with the id field.
In your HTML, you need to use the proper syntax for your model attribute. Spring is complaining that it can't find the property id because you are providing the string employee, not the object.
modelAttribute="employee" --> th:object="${employee}"
Additionally, you can consolidate to:
#Controller //please add this
public class URLController {
#GetMapping({"/", "/index"})
public String index1(Model model){
model.addAttribute("employee",new Employee());
return "index";
}
#PostMapping("/result")
public String result(#ModelAttribute Employee employee){
System.out.print(employee.getName()); //use a logger instead
return "result"; //may want to return a different page name for clarity
}
}
Your IDE will not complain if you change your HTML tag to:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
Lastly, you may want to use the tel input type for the phone field. Doing so will allow for a custom keyboard to show for mobile users.
I'm building a simple web service with spring and thymeleaf. That's the code for now:
Controller:
package com.Basi.CheBBellaEmittente.Pages.Control;
#Controller
public class SimpleController {
#GetMapping("/nuovo-utente")
public String viewInserisciUtente(Model model){
model.addAttribute("nuovoUtente", new Utente());
return "nuovo-utente";
}
#PostMapping("/nuovo-utente")
public void memorizzaUtente(#ModelAttribute Utente utente){
System.out.println(utente.getId());
}
}
Model:
package com.Basi.CheBBellaEmittente.Pages.Model;
public class Utente {
private String id;
private String citta=null;
private String genere;
private String data_nascita=null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCitta() {
return citta;
}
public void setCitta(String citta) {
this.citta = citta;
}
public String getGenere() {
return genere;
}
public void setGenere(String genere) {
this.genere = genere;
}
public String getData_nascita() {
return data_nascita;
}
public void setData_nascita(String data_nascita) {
this.data_nascita = data_nascita;
}
}
html page:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Inserisci un nuovo utente</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="#{/nuovo-utente}" th:object="${com.Basi.CheBBellaEmittente.Pages.Model.Utente}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>Città: <input type="text" th:field="*{citta}" /></p>
<p>Genere: <input type="text" th:field="*{genere}" /></p>
<p>Data nascita: <input type="text" th:field="*{data_nascita}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
and the error:
2018-09-21 16:51:40.668 ERROR 3132 --- [nio-8080-exec-1] org.thymeleaf.TemplateEngine : [THYMELEAF][http-nio-8080-exec-1] Exception processing template "nuovo-utente": Exception evaluating SpringEL expression: "com.Basi.CheBBellaEmittente.Pages.Model.Utente" (template: "nuovo-utente" - line 9, col 51)
So, what can I do to handle this situation? I don't know what's wrong with this, is a very simple code. Can you give me some advice? I'm supposing is some fold packages issue but I can't understand what.
Since your model attribute is named nuovoUtente -- model.addAttribute("nuovoUtente", new Utente());, that's what you should be using as your th:object.
<form action="#" th:action="#{/nuovo-utente}" th:object="${nuovoUtente}" method="post">
An expression like this: ${com.Basi.CheBBellaEmittente.Pages.Model.Utente} will be interpreted as: com.getBasi().getCheBBellaEmittente().getPages().getModel().getUtente() -- which doesn't make sense.
In your controller you set the name of your model attribute to nuovoUtente so you have to do the next on the html:
<form action="#" th:action="#{/nuovo-utente}" th:object="${nuovoUtente}" method="post">
You want to create and submit a form. On the #GetMapping and #PostMapping you have to set different urls.
For example:
#GetMapping(/nuevo-utente-form) and #PostMapping(/nuevo-utente)
In the nuevo-utetente-form.html you write the code of the form, and in nuevo-utente.html you write the code for accept the form.
th:object="${com.Basi.CheBBellaEmittente.Pages.Model.Utente}"
it should point to actual object instance that you pass in your view model, not its class, so probably
th:object="${utente}"
is what it should be.
I wanted to pass the value retrieved on a java class to a page.I am using DAO classes.
I have retrieved the values from the database and stored them on String variables.Now I want to set them to the text boxes in my view.jsp page.I am new to this area,can anyone help me out??
View.jsp is as
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
<form action="process.jsp">
Enter Name <br/> <br> <input type="text" name="uname" onclick="this.value=''"/><br/><br/>
<input type="submit" value="view details"/><br/><br/>
Email id: <br/> <input type="text" name="email" id="email" > <br/><br/>
password: <br/> <input type="text" name="passw" id="passw"><br/><br/>
</form>
</body>
</html>
and My Activity ViewDAO.java is as
public static void view(user u) {
Connection con=ConnectionProvider.getCon();
String uname=u.getUname();
try {
PreparedStatement ps=con.prepareStatement("select email,pass from S1.USER432 where name='"+uname+"'");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String email = rs.getString("EMAIL");
String pass = rs.getString("PASS");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks...
If you are using a front controller[spring mvc] then you can pass the data by doing,
model.addAttribute("variable_name ", data);
and in the jsp you can access it by doing this ${variable_name};
You need to call the DAO method from your servlet like below:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// call DAO method to get the email and password
HashMap<String,String> map=ViewDAO.getDetails();
//from the map you will get the email and password.then you need to set them in the attributes and get them in your jsp
request.setAttribute("email", map.get("email"));
request.setAttribute("password", map.get("password"));
}
your DAO method should be like the below:
public static HashMap<String,String> getDetails(user u) {
Connection con=ConnectionProvider.getCon();
String uname=u.getUname();
Map<String,String> map=new HashMap<>();
try {
PreparedStatement ps=con.prepareStatement("select email,pass from S1.USER432 where name='"+uname+"'");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String email = rs.getString("EMAIL");
String pass = rs.getString("PASS");
}
map.put("email",email);
map.put("password",pass);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
}
Hope this will help you.
if you are using simple jsp and servelt, then make one ViewController.java.
You can two methods one for handling GET and other for POST
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String email = request.getParameter("email");
String password = request.getParameter("password");
request.setAttribute("email", email);
request.setAttribute("password", password);
request.getRequestDispatcher("view.jsp").forward(request, response);
}
catch(Exception e){
}
View.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
<form action="process.jsp">
Enter Name <br/> <br> <input type="text" name="uname" onclick="this.value=''"/><br/><br/>
<input type="submit" value="view details"/><br/><br/>
Email id: <br/> <input type="text" name="email" id="email" value="<%=email%>" > <br/><br/>
password: <br/> <input type="text" name="passw" id="passw" value="<%=password%>"><br/><br/>
</form>
</body>
</html>
The Servlet decides which page must be loaded. So whatever you get from the DAO must go to the Servlet and through that, to the jsp. You can use a bean class to send values from DAO to Servlet.
Like this,
public class Details{
private String email;
private String password;
public void setEmail(String email){
this.email = email;
}
public void setPassword(String password){
this.password= password;
}
public String getEmail(){
return this.email;
}
public String getPassword(){
return this.password;
}
}
And you can make the following changes in DAO after getting the query results in the String. Add these
Details d = new Details();
d.setEmail(email);
d.setPassword(pass);
return d;
You can pass this object d to the servlet and retrieve the values using the getter methods of the bean. Also, the DAO must be called from the Servlet.
And now on the Servlet side.
On the Servlet you can put your code in the get or post method depending on your need. It may be like
public class ExampleServlet extends HttpServlet{
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email"); //got from the jsp where "email" is the name attribute of the input field
Details d = new Details();
d = ViewDao.view(user_object); //the bean sent by DAO. "user_object" is parameter that your DAO method is taking in your code
if(d.getEmail()!=null){ //just an example
// your code that redirects desired page
}
}
}
Based on d returned by the DAO you may redirect to any page you want.
Something like that
Observe this import
dao.UserDao,bean.*,
dao is the package
UserDao is the class
bean is the method you want or is could an attribute from dao
remember that
jsp
<body>
<%#page import="dao.UserDao,bean.*,java.util.*"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Users List</h1>
<%
List<User> list=UserDao.getAllRecords();
request.setAttribute("list",list);
%>
<div class="table-responsive">
<table class="table">
<thread class="bg-info">
<th>Id</th><th>Name</th><th>Password</th><th>Edit</th><th>Delete</th>
</thread>
<c:forEach items="${list}" var="u">
<tr>
<td>${u.getId()}</td><td>${u.getUsername()}</td><td>${u.getPassword()}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
</div>
<br/>Add New User
<br>
<br>
<form action="index.jsp">
<button type="submit">IndexUsers</button>
</form>
</body>
Bean or model
package bean;
// classe para as tables
public class User {
private int id;
private String username,password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
dao
public class UserDao {
public static Connection getConnection(){
Connection con=null;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql_database","root","14570");
}catch(Exception e){System.out.println(e);}
return con;
}
public static int save(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"insert into login(username,password) values(?,?)");
ps.setString(1,u.getUsername());
ps.setString(2,u.getPassword());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int update(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"update login set username=?,password=? where id=?");
ps.setString(1,u.getUsername());
ps.setString(2,u.getPassword());
ps.setInt(3,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int delete(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("delete from login where id=?");
ps.setInt(1,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static List<User> getAllRecords(){
List<User> list=new ArrayList<User>();
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from login");
ResultSet rs=ps.executeQuery();
while(rs.next()){
User u=new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
list.add(u);
}
}catch(Exception e){System.out.println(e);}
return list;
}
public static User getRecordById(int id){
User u=null;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from login where id=?");
ps.setInt(1,id);
ResultSet rs=ps.executeQuery();
while(rs.next()){
u=new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
}
}catch(Exception e){System.out.println(e);}
return u;
}
}
Another Example this import import="dao.*"% makes available any methods from package dao, Bellow you see how to get the result of the method countid() in the dao.
<%#page import="dao.*"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<% int id = 0; %>
<%
DaoEvento daoEvento = new DaoEvento();
id = daoEvento.countId();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
<body>
<br><br>
<form action="add_event_servletnew" method="POST">
<div class="form-group">
<td>
<font color='green' face = "Arial" size = "4">
<%= request.getParameter("message") %>
</font>
view
<td>
</div>
<div class="form-group">
<label>id</label>
<input type="text" name="id" value="<%= id%>" readonly="readonly" class="form-control"/>
</div>
<div class="form-group">
<label>Title</label>
<input type="text" name="title" value="" class="form-control" />
</div>
<div class="form-group">
<label>Start</label>
<input type="date" name="start" value="" class="form-control"/>
</div>
<div class="form-group">
<label>End</label>
<input type="date" name="end" value="" class="form-control" />
</div>
<div class="form-group">
<td><input type="submit" value="submit" class="btn btn-success btn-block"/></td>
</div>
</form>
</body>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>
<script src="jquery.mask.min.js"> </script>
</html>