index.jsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<h1>
<font color=orange ><center> Authentification </font> </h1>
<form name"loginform" action="login" method="post">
<p> Enter your ID: <input type="text" name="id"><br>
<input type="submit">
</form>
</body>
</html>
Authentification.java:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
int IdUser = Integer.valueOf(request.getParameter("id"));
session.setAttribute("ide", IdUser);
try {
if(auth.authen(IdUser)){
session=request.getSession();
request.getRequestDispatcher("acceuil.jsp").forward(request, response);
System.out.println("found");}
else{
request.getRequestDispatcher("index.jsp").forward(request, response);
System.out.println("not found");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
acceuil.jsp: Where I want to display IdUser
<% Integer idUser = (Integer)session.getAttribute("IdUser"); %>
<!--some HTML code-->
<div id="corps"><h1>
Welcome <%=idUser%> </h1></div>
So what I want to have is after the user enter's his id and if the id is found in the database(this operation works) there would be a message ncluding the user's id. the get.Attribute doesn't return a value instead in my page the result is "Welcome NULL".
You saved the attribute in session with name "ide" but try to recover it with name "IdUser". Use the same attribute name in both places.
Related
I am working on a Login and registration form. I have successfully created the Login and Registration form and linked them together. Now I created a separate page for admin where I want to display my database. But I am not able to move to the admin page. Whenever i input my admin credentials it always shows a blank page. I am a newbie both to Java and stackoverflow so I dont know how to ask proper questions. I pasted all my code here. My main problem is in Login.java . I am using eclipse and tomcat 8.5.
Things I have tried till now:-
1) RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/admin.jsp");
rd.forward(request, response);
2)HttpServletResponse.sendRedirect("/WEB-INF/admin.jsp")
3)response.sendRedirect("WEB_INF/admin.jsp");
Registeration.java
public class Registeration extends HttpServlet {
private static final long serialVersionUID = 1L;
public Registeration(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException{
try {
String usernam = request.getParameter("usernam");
String password = request.getParameter("password");
String age = request.getParameter("age");
String gender = request.getParameter("gender");
String event = request.getParameter("event");
String sql = "insert into
registeration(usernam,password,age,gender,event) values(?,?,?,?,?)";
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/portal",
"root", "");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,usernam);
ps.setString(2,password);
ps.setString(3,age);
ps.setString(4,gender);
ps.setString(5,event);
ps.executeUpdate();
PrintWriter out = response.getWriter();
out.println("You have successfully registered!");
out.flush();
RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
rd.include(request, response);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
Registeration.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=UTF-8">
<title>JSP Page</title>
<style>
img {
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<img src="unilogo.PNG" style="width:40%">
<body>
<div align="center">
<form action="Registeration" method="POST">
User Name:<input type="text" name="usernam" required="required">
<br>
Password : <input type="password" name="password"
required="required"><br>
Age : <input type="text" name="age" required="required" /><br>
Gender : <select name="gender">
<option>Male</option>
<option>Female</option>
<option>Transgender</option>
</select><br>
Event : <select name="event" multiple="multiple">
<option>Mr.Tanwar Body Building</option>
<option>Fashion Show</option>
<option>Dance</option>
<option>Singing</option>
<option>Coding</option>
</select><br>
<input type="submit" value="REGISTER" />
<input type="reset" value="RESET" /><br>
<a href="${pageContext.request.contextPath}/login.jsp">Click
here
to go to the login page</a>
</form>
</div>
</body>
</html>
Login.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=UTF-8">
<title>Login Page</title>
</head>
<body>
<div align="center">
<form action="Login" method="POST">
User Name:<input type="text" name="usernam" required="required">
<br>
Password : <input type="password" name="password"
required="required"><br>
<input type="submit" value="Login" />
<input type="reset" value="RESET" /><br>
<a
href="${pageContext.request.contextPath}/registeration.jsp">Click here
to
go to the Registration page</a>
</form>
</div>
</body>
</html>
Login.java
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
try {
String usernam = request.getParameter("usernam");
String password = request.getParameter("password");
String dbName = null;
String dbPassword = null;
String sql = "select * from registeration where usernam =
? and password = ?";
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/portal",
"root",
"");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,usernam);
ps.setString(2,password);
ResultSet rs = ps.executeQuery();
PrintWriter out = response.getWriter();
while(rs.next()){
dbName = rs.getString(2);
dbPassword = rs.getString("password");
if(usernam.equals("admin") &&
password.equals("password")){
RequestDispatcher rd =
request.getRequestDispatcher("/WEB-INF/admin.jsp");
rd.forward(request, response);
}
if(usernam.equals(dbName) &&
password.equals(dbPassword)) {
out.println("You have successfully logged
in!");
out.println("Age:"+rs.getString(4)+"
Gender:"+rs.getString(5)+" Event:"+rs.getString(6));
}
else {
RequestDispatcher rd =
request.getRequestDispatcher("/WEB-INF/registeration.jsp");
rd.forward(request, response);
}
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"
version="3.1">
<display-name>Registeration</display-name>
<servlet>
<servlet-name>reg</servlet-name>
<servlet-class>jdbc.registeration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>reg</servlet-name>
<url-pattern>/regServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>jdbc.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
My login page is supposed to redirect me to admin.jsp when i enter my admin details. But all i get is a blank page. My url after entering admin details"http://localhost:8080/Registeration/Login". I am getting the required output when enter the login id which are stored in DB.
Hello, im working on a project in the university, and im stuck on an error.
Im working on a mypage feature, where you can update your old password, when you are looged in. The problem is that ChangepasswordServlet is not doing what it is supposed to do.
Here you can see my servlet, the problem is probably somewhere in the IF sentence. (Manager=Entitymanager)
#WebServlet(name = "ChangePasswordServlet", urlPatterns = {"/ChangePassword"})
public class ChangePasswordServlet extends HttpServlet {
#EJB
UserManagerLocal manager;
private void changePassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
String loggedInUsersUsername = request.getRemoteUser();
/* PrintWriter writer = response.getWriter(); */
User userFromTheDB = manager.getUser(loggedInUsersUsername);
String oldPasswordFromDB = userFromTheDB.getPassword();
String oldPasswordFromForm = (String) request.getAttribute("theOldPW");
;
String newPasswordFromForm = (String) request.getAttribute("theNewPW");
String newPasswordToCheckFromForm = (String) request.getAttribute("theNewPWCheck");
try {
if (oldPasswordFromDB.toLowerCase().equals(oldPasswordFromForm.toLowerCase()) && newPasswordFromForm.toLowerCase().equals(newPasswordToCheckFromForm.toLowerCase())) {
userFromTheDB.setPassword(newPasswordFromForm);
manager.updateUser(userFromTheDB);
response.sendRedirect("/Slit/MyPage/PasswordSucsess.jsp");
} else {
response.sendRedirect("Slit/Error/error.jsp");
}
}
catch (NullPointerException en) {
PrintWriter print = response.getWriter();
print.println("nullpointeryes");
print.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
changePassword(request, response);
}
#Override
protected void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
changePassword(request, response);
}
so
Here is my JSP with the form
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<head>
<title>Her kan du endre ditt nåværende passord</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css"
href="/Slit/Templates/CSS/MainPageTemplate.css">
</head>
<body>
<title>Slit</title>
<div>
<div class="form">
<form method="post" action="/Slit/ChangePassword">
<input type="Password" name="theOldPW" placeholder="Gammelt
Password"/>
<input type="Password" name ="theNewPW" placeholder="Nytt
Password"/>
<input type="Password" name ="theNewPWCheck" placeholder=" Nytt
Password på nytt"/>
<input type="submit" name="ByttePassord" value="Trykk her for å bytte
passord!"/>
</form>
</div>
</div>
</body>
</html>
</head>
<body>
</body>
So im getting nullpointer after i have filled in the form with the old and the new password.
If im running the code now, im getting the "nullpointeryes" error.
Edit:
This is the console error after filling in the form:
12:39:37,194 INFO [stdout] (default task-12) Hibernate: select
user0_.username as username2_3_0_, user0_.fName as fName3_3_0_, user0_.lName
as lName4_3_0_, user0_.password as password5_3_0_, user0_.DTYPE as
DTYPE1_3_0_ from User user0_ where user0_.username=?
Thanks for any answers
After hours i figured that i used get.attribute instead of parameter :/
String newPasswordFromForm = (String) request.getParameter("theNewPW");
String newPasswordToCheckFromForm = (String)
request.Paramter("theNewPWCheck");
I am trying to log a json response from my servlet in my ajax call. Now, here is the thing, I tried experimenting with logging string response in my ajax and things seemed to work fine but then I try to log the json response, I see nothing in my console. I am wondering if I am missing out on something.I tried calling my servlet from POSTMAN and I got the proper json response.
HomeServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Map<String, String> options = new LinkedHashMap<>();
String text = "some text";
PrintWriter out = response.getWriter();
response.setContentType("text/html");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/apiprovider","root","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from apiinfo");
// out.println("<table border=1 width=50% height=50%>");
// out.println("<tr><th>EmpId</th><th>EmpName</th><th>Salary</th><tr>");
while (rs.next()) {
String n = rs.getString("apiname");
String nm = rs.getString("apiendpoint");
options.put("value1", n);
options.put("value2", nm);
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
// out.println("<tr><td>" + n + "</td><td>" + nm + "</td><td>" + s + "</td></tr>");
}
// out.println("</table>");
// out.println("</html></body>");
con.close();
}
catch (Exception e) {
out.println("error");
}
}
Home.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>
<div id="ajaxresponse">
</div>
<form>
API Name:<br>
<input type="text" id = "apiname" name="apiname">
API ENDPOINT:<br>
<input type="text" id ="apiendpoint" name="apiendpoint">
<br>
API VERSION:<br>
<input type="text" id="apiversion" name="apiversion">
ACCESSIBLE:<br>
<input type="checkbox" name="source" value="internet"> Internet<br>
<input type="checkbox" name="source" value="vpn"> VPN<br>
<!--
<br><br>
<input type="submit" formaction="Home" method="post" value="Submit"> -->
<br>
<input type="submit" id="check" name="check" value="Check">
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
console.log("I was clicked");
$.get("HomeServlet", function(responseText) {
console.log("response",responseText);
// Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
</script>
</body>
</html>
You will need to write a callback, this will be fired when your ajax call completes, try like below
function success(data) {
console.log( data );
}
function failure(err) {
console.error( err );
}
ajax( "http://some.url.1", success, failure );
I am new to Ajax, Jquery, JSON stuff. I have created one login page in jsp servlet technology. On login page, when user presses submit button, data gets collected in JSON and transferred to controller through AJAX. Now, in controller if on some condition, login name found to be correct, then it should use RequestDispatcher to dispatch it to success page. However if condition not satisfied, then it should write the message in JSON object and return it as content type json. Now the problem is that I am able receive JSON data on controller, but not able to redirect on success and also not able to show alert box to user if he entered wrong data. Below are the files:
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
function validateAndSet()
{
var jsonRequest = {};
var login_name = $.trim($('#loginName').val());
var password = $.trim($('#password').val());
if(login_name=='' || login_name.length==0 ){
alert("Please enter login name.");
$('#loginName').focus();
return false;
}
if(password=='' || password.length==0 ){
alert("Please enter password.");
$('#password').focus();
return false;
}
jsonRequest["login_name"] = login_name;
jsonRequest["password"] = password;
return jsonRequest;
}
</script>
</head>
<body>
<jsp:include page="commonResources/Header.jsp">
<jsp:param value="none" name="headerMenu"/>
</jsp:include>
<script>
$(document).ready(function(){
$("#but").click(function(){
var formData=validateAndSet();
var strUrl="rwcntrlr.do?action=loginForm";
$.post(strUrl, {jsonData: JSON.stringify(formData)},function(response){
response = jQuery.parseJSON( response);
if(response.status=='NOT OK')
{
alert("not ok");
}
else{
alert('OK');
}
});
});
});
</script>
<br><br>
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<div class="container-fluid">
<div class="panel panel-default" id="p1">
<div class="panel-heading"><h3>Login</h3></div>
<div class="panel-body">
<center>
<table>
<tr>
<td height="50">LoginName:</td><td height="50"><input type="text" id="loginName" name="loginName"/></td>
</tr>
<tr>
<td height="20">Password:</td><td height="20"><input type="password" id="password" name="password"/></td>
</tr>
<tr><td height="50" colspan="2" align="right"><input type="submit" id="but" name="subBut" value="Go>" /></td></tr>
</table>
</center>
</div>
</div>
</div>
</div>
<div class="col-sm-4"></div>
</div>
</body>
</html>
controller servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String formName=request.getParameter("action");
if(formName.equalsIgnoreCase("loginForm")){
String strJSONData = request.getParameter("jsonData");
System.out.println(strJSONData);// data received correctly...
JSONObject jsonResponse = new JSONObject();
try{
JSONObject requestedJSONObject = new JSONObject(strJSONData);
String login_name = requestedJSONObject.getString("login_name");
String password = requestedJSONObject.getString("password");
if(login_name.equalsIgnoreCase("u2")){
RequestDispatcher rd=request.getRequestDispatcher("employeeSection/employeeDailySheet.jsp");
response.setContentType("text/html");
rd.forward(request, response);
}
else{
jsonResponse.put("status", "NOT OK");
response.setContentType("application/json");
response.getWriter().write(jsonResponse.toString());
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
When I presses submit button on login.jsp, nothing happens. No console error is shown. What should I do to resolve this problem.
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>