I'm pretty much new to Java EE programming, and I'm supposed to do some exercises (to finish my school pretty soon) about it.
My problem might be very simple, but I haven't found an answer whatsoever.
In one exercise, I'm supposed to be able to log in to a java/jsp/mysql-type of service.
Login.htm
<html>
<head>
<title>Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<h3>Login</h3>
<form name="login" method="post" action="ServletLogin">
<table>
<tr>
<td>Email:</td>
<td><input name="email" type="text" id="email"></td>
</tr>
<tr>
<td>Salasana</td>
<td><input name="password" type="password" id="password"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="Submit" value="Log in;">
</td>
</tr>
</table>
</form>
</body>
</html>
Pretty standard login, yes. When passing the form, it should go to a ServletLogin.java to initiate the login-sequence.
Instead I'm getting this from Glassfish:
HTTP Status 500 - Internal Server Error
type Exception report
messageInternal Server Error
descriptionThe server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.1 logs.
GlassFish Server Open Source Edition 4.1
In the ServletLogin.java, our tutor has left a note that the whole project should include a MySQL driver library to avoid NullPointerException.
My question is, how do I do that with Netbeans? Netbeans tells me I already have on installed, but apparently it either isn't or it doesn't work.
Here is ServletLogin.java code:
/*
* Remember to install a MYSQL driver library
* or the file will alert
* NullPointerException.
*/
package Servlets; //the package in which the Servlet is part of.
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
#WebServlet(name = "ServletLogin", urlPatterns = {"/ServletLogin"})
public class ServletLogin extends HttpServlet {
Connection conn = null;
/**
* Initializes the servlet.
*/
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
//Connect to database with database-class
try {
conn = Classes.SQL.openConnection();
}
catch (Exception e) {
System.out.println("Cannot connect to database " + e);
}
}
/**
* Destroys the servlet.
*/
#Override
public void destroy() {
//Closing the database connection
try {
conn.close();
} catch ( SQLException se ) {
System.out.println("Exception " + se);
}
}
//Everything is done in doPost method.
//This Servlet does not use doGet() or ProcessRequest()
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
/*Unless there is a session, one is created.
It is used to check if the user has logged in.*/
HttpSession session = request.getSession(true);
//Reading the parameters from login form.
String email = request.getParameter("email");
String password = request.getParameter("password");
out.print(email);
//Created login_ok and set it to false by default.
boolean login_ok = false;
try {
//let's create a Statement with which the sql can be run with.
Statement stmt = conn.createStatement();
//Run SQL and save it to ResultSet rs.
ResultSet rs = stmt.executeQuery("SELECT email, password FROM clients");
//Go trough the results with while loop and next-method, which returns the value true, until we've reached last result.
while(rs.next())
{
//Reading the data
String email2 = rs.getString("email");
String salasana2 = rs.getString("password);
//If user input has been found from database,
//login_ok becomes true and looping ends.
if(email.compareTo(email2) == 0 && password.compareTo(password2) == 0)
{
login_ok = true;
break;
}
}
//If login_ok is true, save info about logging to session and guide the user to Clients.jsp
if( login_ok == true )
{
//session is informed about login
session.setAttribute("login", "ok");
//Debugging printed to console.
System.out.println("Login ok");
//Proceeding to clients
response.sendRedirect("clients.jsp");
//Return stops the servlet run.
return;
}
//Login false -> redirected to login page.
else {
response.sendRedirect("login.htm");
}
}
catch(SQLException se){
out.println("Error: " + se);
}
out.close();
}
}
Am I missing something, like in imports or?
I've installed mysql-connector-java-5.1.23-bin.jar and set it into multiple different places, with same result. All I need now is to be able to even see if the code works, but NullPointerException prevents me from doing so.
Adding the mysql-connector-java-5.1.23-bin.jar through Project Properties -> Libraries on Netbeans 8.0.2 doesn't seem to solve it, either.
Registered MySQL to GlassFish, still goes for NullPointerException.
Go to Services Tab
Select Databases
Right click and select Register MYSQL driver
Right Click libraries in project and select MYSQL from add Libraries
Related
I am developing a small sql servlet application that takes in a SQL command from a text area in an html page, sends the command to a servlet that makes an sql connection and puts in the resultset into an arraylist. I have all of that down, and i can print column names to the browser in the java servlet class. One thing i need to do is print the results into a table using a JSP page. The JSP page will look just like the html page we first used. I can not figure out how i am going to get the arraylist from the servlet to the JSP page to be displayed to the user.
Here is the HTML page:
<html>
<head>
<title>WebApp</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="background-color:blue;">
<center>
<font color="white">
<h1> Welcome to the Project 4 Remote Database Management System</h1>
<hr>
You are connected to the Project4 database. <br>Please enter any valid SQL query or update statement.<br>
If no query/update command is given the Execute button will display all supplier information in the database. <br>All execution results will appear below.
<br>
<br>
<form action="NewServlet" method="post">
<textarea rows="10" cols="60"name="command"></textarea>
<br>
<button type="submit">Execute Query</button>
<button type="submit">Clear Command</button>
</form>
<hr>
<h1>Database Results</h1>
</font>
</body>
</html>
and here is the servlet code:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
/**
*
* #author KJ4CC
*/
public class NewServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
Connection connection;
Vector<String> columnNames = new Vector<String>();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String command = request.getParameter("command");
out.println("<!DOCTYPE html>");
out.println("<html>");
sqlConnection(command);
//prints out column names into the browser.
out.println(columnNames);
}
}
public void sqlConnection(String command){
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/project3";
String user = "root";
String pass = "Brandy?1994";
ResultSet rs;
try {
Class.forName(driver);
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
try {
connection = DriverManager.getConnection(url,user,pass);
} catch (SQLException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
Statement stmt;
try {
stmt = connection.createStatement();
rs = stmt.executeQuery(command);
int colNum = rs.getMetaData().getColumnCount();
for (int i = 0; i < colNum; i++) {
columnNames.add(rs.getMetaData().getColumnLabel(i+1));
}
} catch (SQLException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Here is the start of the JSP page:
<html>
<head>
<title>WebApp</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="background-color:blue;">
<center>
<font color="white">
<h1> Welcome to the Project 4 Remote Database Management System</h1>
<hr>
You are connected to the Project4 database. <br>Please enter any valid SQL query or update statement.<br>
If no query/update command is given the Execute button will display all supplier information in the database. <br>All execution results will appear below.
<br>
<br>
<form action="NewServlet" method="post">
<textarea rows="10" cols="60"name="command"></textarea>
<br>
<button type="submit">Execute Query</button>
<button type="submit">Clear Command</button>
</form>
<hr>
<h1>Database Results</h1>
<%
DO TABLE STUFF HERE TO OUTPUT SQL RESULTS
%>
</font>
</body>
</html>
I think i will create a javaBean to store the arrays so that the JSP page can access the column arraylist. Then use a for loop to iterate through the array list so that i can create the table columns. how could i link the JSP page to the servlet so that if can get the information needed?
I have to do the sql connection in the servlet and cannnot make the connection in the JSP page.
In your servlet method, set attribute in page context as below
HttpServletRequest req = (HttpServletRequest)request;
.... // find out what to put
req.getPageContext.setAttribute('some', objectYouFound);
In your jsp, use el to access the variable:
${some}
In the servlet, store the data in a request attribute:
request.setAttribute("rows", rows);
In the JSP, use the JSTL to loop over the rows:
<c:forEach var="row" value="${rows}">
...
</c:forEach>
Do NOT use Java scriptlets in your JSP.
You have few issues with your current code:
(1) A single servlet instance will be shared across all request threads, so you should NOT create the instance variables for a servlet class i.e.,
Connection connection;
Vector<String> columnNames = new Vector<String>();
These two variables should be created inside your processRequest() method so that they will be local to each request thread.
(2) You are ONLY querying the META DATA of the table, so you can display only column names, but if you wanted to fetch the data as well, you need to use resultSetObj.hasNext() and then use next() method like below:
while (rs.hasNext())
{
String X = rs.getString("empno");
//Retrieve all data
//add to a bean object
//add to list
}
//Now return the list which contains the data
You can look at here for a good example.
(3) Use the request.setAttribute to set the results to the request object and then you can retrieve to the next JSP (results) page.
This question already has answers here:
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
(13 answers)
Closed 6 years ago.
I wrote a login web and it can't work well. It may be some problem of MySQL connecting.
Here is the code. It's simple. There are ServletLogin.java and a index.jsp.
ServletLogin.java
package Login;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.*;
public class ServletLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
private String name;
private String pass;
public ServletLogin() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String printout = "";
this.name = request.getParameter("username");
this.pass = request.getParameter("password");
if (name == "" || name == null || name.length() > 20) {
try {
printout = "20字以内ユーザネームを再入力ください";
request.setAttribute("message", printout);
response.sendRedirect("index.jsp");
return;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
if (pass == "" || pass == null || pass.length() > 20) {
try {
printout = "20字以内のパスワードを再入力ください";
request.setAttribute("message", printout);
response.sendRedirect("index.jsp");
return;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
// database driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
// TODO: handle exception
System.out.println("Class not Found Exception");
}
// create url
String url = "jdbc:mysql://localhost:3306/databasedemo";
try {
Connection conn = DriverManager.getConnection(url,"root","");
Statement stmt = conn.createStatement();
String sql = "select * from userinfo where username='"+name+"' and password= '"+pass+"'";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
if (this.name.equals(rs.getString(1))||this.pass.equals(rs.getString(2))) {
response.sendRedirect("success.jsp");
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>ログイン</title>
<script type="text/javascript">
function changeImg()
{
document.getElementById("validateCodeImg").src="${pageContext.request.contextPath}/CheckCodeImage?" + Math.random();
}
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/ServletLogin">
<table border="0" align="center">
<tr height="30"></tr>
<tr align="center">
<td colspan="2"><font size="20">JAVA WEB</font></td>
</tr>
<tr height="30"></tr>
<tr height="50">
<td>ユーザネーム</td>
<td><input type="text" name="username" placeholder="ユーザネームを入力してください"></td>
</tr>
<tr height="50">
<td>パスワード</td>
<td><input type="password" name="password" placeholder="パスワードを入力してください"></td>
</tr>
<tr height="50">
<td><img alt="認めない" src="${pageContext.request.contextPath}/CheckCodeImage"
id="validateCodeImg" onclick="changeImg()">
</td>
<td><input type="text" name="checkcode" placeholder="右側の文字を入力してください"></td>
</tr>
<tr height="50">
<td colspan="2" align="center">
<input type="submit" name="login" value="ログイン">
</td>
</tr>
</table>
</form>
</body>
</html>
And here is my database called databasedemo.
+--------+----------+----------+
| userid | username | password |
+--------+----------+----------+
| 1 | Jack | 123456 |
| 2 | Mary | 654321 |
+--------+----------+----------+
I think I am stucked with command in ServletLogin.java. I was supposed to submit the form and it would turn to ServletLogin.java and do the command.
If the username and the password are null, recording to the code in Servlet.java, it will go back to index.jsp. And it went very well.
But if the username and the password are the same as it in my database, it should have to go to the page success.jsp. But when I run it, it shows nothing. Seems it has not been submitted and do the command in Servletlogin.java. and the Url shows http://localhost:8080/LoginDemo/ServletLogin?username=Jack&password=123456&checkcode=Axww&login=%E3%83%AD%E3%82%B0%E3%82%A4%E3%83%B3
I'm so confused of it. I think I have problem about connecting to MySQL. But I don't know how to fix it. Please help me about it...
UPDATE
I have solved my problem!
When I run the code, the Exception shows Class not Found Exception java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/databasedemo. This is a exception of jdbc Driver.
When this exception shows, there's four reason:
Wrong URL. Please check the right code: Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/XX","root","XXXX"
Wrong Driver declaration, the right one is :com.mysql.jdbc.Driver
mysql-connector-java-5.1.40.jar must be the same version as your MySQL.
mysql-connector-java-5.1.40.jar has been put to the wrong position. The right position is to copy it in WEB-INF file.
As for me, I put .jar in the wrong position. And When I copy it in the file WEB-INF, my code run well. I hope this will help someone. And my code above is a simple webpage of login. I will continue to complete this java project.
And Thanks for everyone answered my question. #Ravi Kumar pointed out one of my mistakes, and I corrected it. It's a big mistake of me using MySQL.
My best guess is your query
select * from userinfo where username='"+name+"' and password= '"+pass+"'"
This basically select 1 | Jack | 123456
Now rs.getString(1)=1 ie id and rs.getString(2) is Jack ie. username
Instead use
rs.getString("username");
rs.getString("password");
You may also like to change your query to
select username,password from userinfo where username='"+name+"' and password= '"+pass+"'"
in order to make it work with existing code
There can be two possibilities as below:
1) You are seeing nothing in UI because there is nothing(no text content) in your success.jsp file.
You need to add some text as below in success.jsp page.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Error page</title>
</head>
<body>
<p>Success!!!</p>
</body>
I guess you are not getting any exception in both UI and Server console.
2) You need to traverse through the resultSetObject in order to fetch correct username and password values.
So, replace your below code:
if (rs.next()) {
if (this.name.equals(rs.getString(1))||this.pass.equals(rs.getString(2))) {
response.sendRedirect("success.jsp");
}
}
With ,
while(rs.next()){
if(this.name.equals(rs.getString(1))||this.pass.equals(rs.getString(2))) {
response.sendRedirect("success.jsp");
}
}
I'm implementing MVC using JSP and JDBC. I have imported a database class file to my JSP file and I would like to show the data of a DB table. I don't know how I should return the ResultSet from the Java class to the JSP page and embed it in HTML.
How can I achieve this?
In a well designed MVC approach, the JSP file should not contain any line of Java code and the servlet class should not contain any line of JDBC code.
Assuming that you want to show a list of products in a webshop, the following code needs to be created.
A Product class representing a real world entity of a product, it should be just a Javabean.
public class Product {
private Long id;
private String name;
private String description;
private BigDecimal price;
// Add/generate getters/setters/c'tors/equals/hashcode boilerplate.
}
A DAO class which does all the nasty JDBC work and returns a nice List<Product>.
public class ProductDAO {
private DataSource dataSource;
public ProductDAO(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<Product> list() throws SQLException {
List<Product> products = new ArrayList<Product>();
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT id, name, description, price FROM product");
ResultSet resultSet = statement.executeQuery();
) {
while (resultSet.next()) {
Product product = new Product();
product.setId(resultSet.getLong("id"));
product.setName(resultSet.getString("name"));
product.setDescription(resultSet.getString("description"));
product.setPrice(resultSet.getBigDecimal("price"));
products.add(product);
}
}
return products;
}
}
A servlet class which obtains the list and puts it in the request scope.
#WebServlet("/products")
public class ProductsServlet extends HttpServlet {
#Resource(name="jdbc/YourDB") // For Tomcat, define as <Resource> in context.xml and declare as <resource-ref> in web.xml.
private DataSource dataSource;
private ProductDAO productDAO;
#Override
public void init() {
productDAO = new ProductDAO(dataSource);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Product> products = productDAO.list();
request.setAttribute("products", products); // Will be available as ${products} in JSP
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Cannot obtain products from DB", e);
}
}
}
Finally a JSP file in /WEB-INF/products.jsp which uses JSTL <c:forEach> to iterate over List<Product> which is made available in EL by ${products}, and uses JSTL <c:out> to escape string properties in order to avoid XSS holes when it concerns user-controlled input.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/format" prefix="fmt" %>
...
<table>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.id}</td>
<td><c:out value="${product.name}" /></td>
<td><c:out value="${product.description}" /></td>
<td><fmt:formatNumber value="${product.price}" type="currency" currencyCode="USD" /></td>
</tr>
</c:forEach>
</table>
To get it to work, just call the servlet by its URL. Provided that the servlet is annotated #WebServlet("/products") or mapped in web.xml with <url-pattern>/products</url-pattern>, then you can call it by http://example.com/contextname/products
See also:
How to avoid Java code in JSP files?
doGet and doPost in Servlets
How should I connect to JDBC database / datasource in a servlet based application?
Design Patterns web based applications
RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()
How to map a ResultSet with unknown amount of columns to a List and display it in a HTML table?
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
MVC, in a web application context, doesn't consist in using a class from a JSP. It consists in using the following model :
browser sends a request to a web server
the web server is configured so that the request is handled by a servlet or a filter (the controller : Java code, not JSP code)
The servlet/filter usually dispatches the request to a specific class (called an Action, the specific part of the controller), based on configuration/annotations
The action executes the business logic (i.e. fetch the data from the database in your example : the model)
The action forwards the request to a JSP. The role of the JSP is only to generate HTML code (i.e. display your data : the view)
Since the JSP usually uses JSP tags (the JSTL, for example) and the JSP expression language, and since JSP tags and the EL are designed to get information from JavaBeans, you'd better have your data available in the form of JavaBeans or collections of JavaBeans.
The role of the controller (the action class) is thus to fetch the data, to create JavaBean instances containing the data, in a suitable format for the JSP, to put them in request attributes, and then to dispatch to the JSP. The JSP will then iterate through the JavaBean instances and display what they contain.
You should not implement the MVC framework yourself. Use existing ones (Stripes, Struts, etc.)
I don't know how should I return the ResultSet from the class file to the JSP page
Well, you don't.
The point of MVC is to separate your model ( the M DB info in this case ) from your view ( V a jsp, in this case ) in such a way you can change the view without braking to application.
To do this you might use an intermediate object to represent your data ( usually called DTO - after Data Transfer Object -, don't know how they call it these days ), and other object to fetch it ( usually a DAO ).
So basically you have your JSP file, get the request parameters, and then invoke a method from the DAO. The dao, internally has the means to connect to the db and fetch the data and builds a collections of DTO's which are returned to the JSP for rendering.
Something like this extremely simplified ( and insecure ) code:
Employee.java
class Employee {
String name;
int emplid;
}
EmployeeDAO.java
class EmployeeDAO {
... method to connect
etc.
List<Employee> getAllNamed( String name ) {
String query = "SELECT name, emplid FROM employee where name like ?";
ResultSet rs = preparedStatement.executeQuery etc etc.
List<Employee> results = ....
while( rs.hasNext() ) {
results.add( new Employee( rs.getString("name"), rs.getInt("emplid")));
}
// close resources etc
return results;
}
}
employee.jsp
<%
request.setAttribute("employees", dao.getAllNamed( request.getParameter("name") );
%>
<table>
<c:forEach items="${employees}" var="employee">
<tr><td>${employee.emplid}</td><td>${employee.name}</td></tr>
</c:forEach>
</table>
I hope this give you a better idea.
I have a problem. I don't understand clearly the code. I have a similar problem with my code.
I have created database SQL and filled up. Then I want to implement a MainServlet (code below) that richieve data from database and in a different jsp page, I want to insert that data in section like h1, h2 ecc... I must use the ${} sintax but I don't know how do that.
Briefly, In jsp file (code below, I MUST USE ${} SINTAX) I want to "call" MainServlet and there I want to richieve data from database and view in jsp file.
I hope I have explained correctly, thank you very much!
MainServlet.java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MainServlet
*/
#WebServlet({ "/MainServlet" })
public class MainServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String PATH_JSP = "/WEB-INF/";
/**
* #see HttpServlet#HttpServlet()
*/
public MainServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* #see Servlet#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String doveAndare = request.getParameter("azione");
if(doveAndare==null)
doveAndare = "index";
try {
String driverString = "com.mysql.cj.jdbc.Driver";
Class.forName(driverString);
String connString = "jdbc:mysql://localhost:3306/ldd_jewels?user=root&password=";
Connection conn = DriverManager.getConnection(connString);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM JEWEL");
while (rs.next() == true) {
System.out.println(rs.getString("Category") + "\t" + rs.getString("Name"));
/* I try that but does not work
request.setAttribute("name", rs.getString("Name"));
javax.servlet.RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/widering_male.jsp");
dispatcher.forward(request, response); */
}
stmt.close();
conn.close();
} catch(Exception e) {
e.printStackTrace();
}
request.getRequestDispatcher(PATH_JSP+doveAndare+".jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
doublerow.jsp
<section id="portfolio-details" class="portfolio-details">
<div class="container">
<div class="row gy-4">
<div class="col-lg-8">
<div class="portfolio-details-slider swiper">
<div class="swiper-wrapper align-items-center">
<div class="swiper-slide">
<img src="assets/img/jewels/doublerow_1.jpg" alt="" />
</div>
<div class="swiper-slide">
<img src="assets/img/jewels/doublerow_2.jpg" alt="" />
</div>
<div class="swiper-slide">
<img src="assets/img/jewels/doublerow_3.jpg" alt="" />
</div>
</div>
<div class="swiper-pagination"></div>
</div>
</div>
<div class="col-lg-4">
<div class="portfolio-info">
<h3>Product details</h3>
<ul>
<li><strong>Code</strong>: 1S3D5</li>
<li><strong>Category</strong>: Bracelets</li>
<li><strong>Name</strong>: Double Row Hinged Bangle</li>
<li><strong>Gender</strong>: Female</li>
<li><strong>Material</strong>: Yellow gold</li>
<li><strong>Size</strong>: 121mm</li>
<li><strong>Price</strong>: €5500</li>
</ul>
</div>
<div class="portfolio-description">
<h2>Description of product</h2>
<p>
The entwined ends of Tiffany Knot’s signature motif symbolize
the power of connections between people. Balancing strength
and elegance, each Tiffany Knot design is a complex feat of
craftsmanship. This bangle is crafted with yellow gold and
polished by hand for high shine. Wear on its own or partnered
with classic silhouettes for an unexpected pairing.
</p>
</div>
</div>
</div>
</div>
</section>
This is my database:
I want to insert each jewel in different pages (each jewel have a jsp file)
You can use the <c:forEach > tag
you can find a detailed example in the following link example use
I think it will be better for you to contain the data of the table into a collection such as list and return the list from the Java class and reuse this collection in the JSP.
I'm implementing MVC using JSP and JDBC. I have imported a database class file to my JSP file and I would like to show the data of a DB table. I don't know how I should return the ResultSet from the Java class to the JSP page and embed it in HTML.
How can I achieve this?
In a well designed MVC approach, the JSP file should not contain any line of Java code and the servlet class should not contain any line of JDBC code.
Assuming that you want to show a list of products in a webshop, the following code needs to be created.
A Product class representing a real world entity of a product, it should be just a Javabean.
public class Product {
private Long id;
private String name;
private String description;
private BigDecimal price;
// Add/generate getters/setters/c'tors/equals/hashcode boilerplate.
}
A DAO class which does all the nasty JDBC work and returns a nice List<Product>.
public class ProductDAO {
private DataSource dataSource;
public ProductDAO(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<Product> list() throws SQLException {
List<Product> products = new ArrayList<Product>();
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT id, name, description, price FROM product");
ResultSet resultSet = statement.executeQuery();
) {
while (resultSet.next()) {
Product product = new Product();
product.setId(resultSet.getLong("id"));
product.setName(resultSet.getString("name"));
product.setDescription(resultSet.getString("description"));
product.setPrice(resultSet.getBigDecimal("price"));
products.add(product);
}
}
return products;
}
}
A servlet class which obtains the list and puts it in the request scope.
#WebServlet("/products")
public class ProductsServlet extends HttpServlet {
#Resource(name="jdbc/YourDB") // For Tomcat, define as <Resource> in context.xml and declare as <resource-ref> in web.xml.
private DataSource dataSource;
private ProductDAO productDAO;
#Override
public void init() {
productDAO = new ProductDAO(dataSource);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Product> products = productDAO.list();
request.setAttribute("products", products); // Will be available as ${products} in JSP
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Cannot obtain products from DB", e);
}
}
}
Finally a JSP file in /WEB-INF/products.jsp which uses JSTL <c:forEach> to iterate over List<Product> which is made available in EL by ${products}, and uses JSTL <c:out> to escape string properties in order to avoid XSS holes when it concerns user-controlled input.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/format" prefix="fmt" %>
...
<table>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.id}</td>
<td><c:out value="${product.name}" /></td>
<td><c:out value="${product.description}" /></td>
<td><fmt:formatNumber value="${product.price}" type="currency" currencyCode="USD" /></td>
</tr>
</c:forEach>
</table>
To get it to work, just call the servlet by its URL. Provided that the servlet is annotated #WebServlet("/products") or mapped in web.xml with <url-pattern>/products</url-pattern>, then you can call it by http://example.com/contextname/products
See also:
How to avoid Java code in JSP files?
doGet and doPost in Servlets
How should I connect to JDBC database / datasource in a servlet based application?
Design Patterns web based applications
RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()
How to map a ResultSet with unknown amount of columns to a List and display it in a HTML table?
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
MVC, in a web application context, doesn't consist in using a class from a JSP. It consists in using the following model :
browser sends a request to a web server
the web server is configured so that the request is handled by a servlet or a filter (the controller : Java code, not JSP code)
The servlet/filter usually dispatches the request to a specific class (called an Action, the specific part of the controller), based on configuration/annotations
The action executes the business logic (i.e. fetch the data from the database in your example : the model)
The action forwards the request to a JSP. The role of the JSP is only to generate HTML code (i.e. display your data : the view)
Since the JSP usually uses JSP tags (the JSTL, for example) and the JSP expression language, and since JSP tags and the EL are designed to get information from JavaBeans, you'd better have your data available in the form of JavaBeans or collections of JavaBeans.
The role of the controller (the action class) is thus to fetch the data, to create JavaBean instances containing the data, in a suitable format for the JSP, to put them in request attributes, and then to dispatch to the JSP. The JSP will then iterate through the JavaBean instances and display what they contain.
You should not implement the MVC framework yourself. Use existing ones (Stripes, Struts, etc.)
I don't know how should I return the ResultSet from the class file to the JSP page
Well, you don't.
The point of MVC is to separate your model ( the M DB info in this case ) from your view ( V a jsp, in this case ) in such a way you can change the view without braking to application.
To do this you might use an intermediate object to represent your data ( usually called DTO - after Data Transfer Object -, don't know how they call it these days ), and other object to fetch it ( usually a DAO ).
So basically you have your JSP file, get the request parameters, and then invoke a method from the DAO. The dao, internally has the means to connect to the db and fetch the data and builds a collections of DTO's which are returned to the JSP for rendering.
Something like this extremely simplified ( and insecure ) code:
Employee.java
class Employee {
String name;
int emplid;
}
EmployeeDAO.java
class EmployeeDAO {
... method to connect
etc.
List<Employee> getAllNamed( String name ) {
String query = "SELECT name, emplid FROM employee where name like ?";
ResultSet rs = preparedStatement.executeQuery etc etc.
List<Employee> results = ....
while( rs.hasNext() ) {
results.add( new Employee( rs.getString("name"), rs.getInt("emplid")));
}
// close resources etc
return results;
}
}
employee.jsp
<%
request.setAttribute("employees", dao.getAllNamed( request.getParameter("name") );
%>
<table>
<c:forEach items="${employees}" var="employee">
<tr><td>${employee.emplid}</td><td>${employee.name}</td></tr>
</c:forEach>
</table>
I hope this give you a better idea.
I have a problem. I don't understand clearly the code. I have a similar problem with my code.
I have created database SQL and filled up. Then I want to implement a MainServlet (code below) that richieve data from database and in a different jsp page, I want to insert that data in section like h1, h2 ecc... I must use the ${} sintax but I don't know how do that.
Briefly, In jsp file (code below, I MUST USE ${} SINTAX) I want to "call" MainServlet and there I want to richieve data from database and view in jsp file.
I hope I have explained correctly, thank you very much!
MainServlet.java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MainServlet
*/
#WebServlet({ "/MainServlet" })
public class MainServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String PATH_JSP = "/WEB-INF/";
/**
* #see HttpServlet#HttpServlet()
*/
public MainServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* #see Servlet#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String doveAndare = request.getParameter("azione");
if(doveAndare==null)
doveAndare = "index";
try {
String driverString = "com.mysql.cj.jdbc.Driver";
Class.forName(driverString);
String connString = "jdbc:mysql://localhost:3306/ldd_jewels?user=root&password=";
Connection conn = DriverManager.getConnection(connString);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM JEWEL");
while (rs.next() == true) {
System.out.println(rs.getString("Category") + "\t" + rs.getString("Name"));
/* I try that but does not work
request.setAttribute("name", rs.getString("Name"));
javax.servlet.RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/widering_male.jsp");
dispatcher.forward(request, response); */
}
stmt.close();
conn.close();
} catch(Exception e) {
e.printStackTrace();
}
request.getRequestDispatcher(PATH_JSP+doveAndare+".jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
doublerow.jsp
<section id="portfolio-details" class="portfolio-details">
<div class="container">
<div class="row gy-4">
<div class="col-lg-8">
<div class="portfolio-details-slider swiper">
<div class="swiper-wrapper align-items-center">
<div class="swiper-slide">
<img src="assets/img/jewels/doublerow_1.jpg" alt="" />
</div>
<div class="swiper-slide">
<img src="assets/img/jewels/doublerow_2.jpg" alt="" />
</div>
<div class="swiper-slide">
<img src="assets/img/jewels/doublerow_3.jpg" alt="" />
</div>
</div>
<div class="swiper-pagination"></div>
</div>
</div>
<div class="col-lg-4">
<div class="portfolio-info">
<h3>Product details</h3>
<ul>
<li><strong>Code</strong>: 1S3D5</li>
<li><strong>Category</strong>: Bracelets</li>
<li><strong>Name</strong>: Double Row Hinged Bangle</li>
<li><strong>Gender</strong>: Female</li>
<li><strong>Material</strong>: Yellow gold</li>
<li><strong>Size</strong>: 121mm</li>
<li><strong>Price</strong>: €5500</li>
</ul>
</div>
<div class="portfolio-description">
<h2>Description of product</h2>
<p>
The entwined ends of Tiffany Knot’s signature motif symbolize
the power of connections between people. Balancing strength
and elegance, each Tiffany Knot design is a complex feat of
craftsmanship. This bangle is crafted with yellow gold and
polished by hand for high shine. Wear on its own or partnered
with classic silhouettes for an unexpected pairing.
</p>
</div>
</div>
</div>
</div>
</section>
This is my database:
I want to insert each jewel in different pages (each jewel have a jsp file)
You can use the <c:forEach > tag
you can find a detailed example in the following link example use
I think it will be better for you to contain the data of the table into a collection such as list and return the list from the Java class and reuse this collection in the JSP.
I am newbie here. I have an assignment that requires to connect mysql, servlet and java (because i want to separate java code and html code. Previously, i combined the codes to make it easier and was rejected)
So, basically, in mySql i write this,
create table login2 (username varchar (30), password varchar(30), designation varchar(10));
insert into login2 values('lala','123','A');
and i create loginDisp.java in the servlet using eclipse. This is my command
package Servlet;
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class loginDisp extends HttpServlet {
public void service(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
// String username=request.getParameter("Username");
// String password=request.getParameter("Password");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>Servlet JDBC</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection
("url/tablename","uname","pssword");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM login2");
// displaying records
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print("\t\t\t");
out.print(rs.getObject(2).toString());
out.print("<br>");
}
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
out.close();
}
}
When i execute, it is well displayed. Hence, i started to make the Login.jsp as i want to make a text.box for user to insert username and password. This is my code
<%# 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>
<body>
<center>
<div class="wrapper">
<br>
<br>
<h2>Doctor</h2>
<form name="form1" method="post" action="loginDisp" > <!-- onsubmit="return validateForm()" -->
<table width="326" border="1" align="center">
<center> <tr>
<th width="138" scope="row">Username</th>
<td width="142"><input type="text" name="Username"></td>
</tr>
</center>
<tr>
<th height="31" style="width: 162px;"><span class="style2">Password</span>
</th>
<td width="142"><input type="password" name="Password"></td>
</tr>
<tr>
</tr>
</table>
<p align="center">
<input type="submit" name="Submit" value="Submit">
</p> ${message}
</form>
</div>
</center>
</body>
</body>
</html>
and I get the data from mySQL displayed. I add another log.java in servlet because i thought when we need a data fetched from jsp to databased and displayed when be called. This is code in log.java
package Servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class log extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Get username and password from the JSP page
String username=request.getParameter("Username");
String password=request.getParameter("Password");
//Print the above got values in console
System.out.println("The username is" +username);
System.out.println("\nand the password is" +password);
}
}
The username and password inserted in login.jsp does not inserted automatically in mySQL, hence when i try to executed loginDisp.java , it will display only the data i inserted manually in mySQL.
You can not use the java file name as action this is defined in the web.xml file and there is servlet mapping and you can use
<servlet>
<servlet-name>log</servlet-name>
<servlet-class>loginDisplay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>log</servlet-name>
<url-pattern>/loginDisplay</url-pattern>
</servlet-mapping>
and now you can use the action = "loginDisplay" in the action tag and by using this
I hope you did not face the problem of 404 error.
You entered a wrong action in form.
Since form's action attribute takes the path of the servlet you should give the relavent mapping specified in web.xml
action="loginDisplay.java"
should be action="/loginDisplay"
<form name="form1" method="post" action="loginDisplay.java" onsubmit="return validateForm()">
It should be
<form name="form1" method="post" action="/loginDisplay" onsubmit="return validateForm()">
If /loginDisplay is not the exact mapping in your web.xml check the web.xml file and see the mapping for loginDisplay and give that path as action.
A quick example
Create a new package (called dao or model) where you put your logic to access to the DB.
Then create a Java Bean Object where store the results of your DB and instanciate your class of the logic in the servlet, then access to the properties of the Bean and show it in the WEB.
package model:
class DaoAccess (methods to connect with DB)
class Login (properties of the table with getXXX and setXXX of each one)
package Servlet.
class loginDisplay:
public class loginDisplay extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>loginDisplay</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
DaoAccess dao = new DaoAccess();
List<Login> list = dao.readAll();
for(Login obj: list){
out.write(obj.getName());
out.write(obj.getPassword());
}
out.close();
}
}