I'm having trouble with passing servlet variables to jsp.
Of course, I also have the web.xml set for the servlet already
<servlet>
<servlet-name>databaseServlet</servlet-name>
<servlet-class>Servlet.databaseServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>databaseServlet</servlet-name>
<url-pattern>/dbServlet</url-pattern>
</servlet-mapping>
The result is all of the name, owner, species and sex values are null. Can someone help me with this? Thanks
P.S: I also tried to use request.getSession().setAttribute in the servlet, didn't work either
P.P.S: So if I make the following changes:
databaseServlet.java
package Servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
@SuppressWarnings("serial")
public class databaseServlet extends HttpServlet {
private Connection conn;
private Statement statement;
String name;
String owner;
String species;
String sex;
String birth;
String death;
public void init(ServletConfig config) throws ServletException {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost/STUDENTS",
"root",
"");
statement = conn.createStatement();
String sql = "SELECT name, owner, species, sex, birth, death FROM pet";
ResultSet rs = statement.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
name = rs.getString("name");
owner = rs.getString("owner");
species = rs.getString("species");
sex = rs.getString("sex");
birth = rs.getString("birth");
death = rs.getString("death");
}
rs.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("NAME", "Hello");
System.out.println(name);
request.setAttribute("OWNER",owner);
request.setAttribute("SPECIES",species);
request.setAttribute("SEX", sex);
RequestDispatcher dispatcher=getServletConfig().getServletContext().getRequestDispatcher("/dbServlet.jsp");
dispatcher.forward(request, response);
}
}
and this is my new jsp:
<body>
Name="${databaseServlet.NAME}"
Owner="${databaseServlet.OWNER}"
Species="<%= request.getAttribute("SPECIES") %>"
Sex="<%= request.getSession().getAttribute("SEX") %>"
</body>
both Name and Owner returns empty string, while Species and Sex still returns NULL
basically what I'm trying to do is to access MySQL database to retrieve variables from a table, and display it using JSP
Make sure that you have valid values for
name
,owner
,species
andsex
when setting request attribute insidedoPost
method.Use EL syntax like
Do not write scriptlets in JSP, because scriptlets shouldn't be used in JSPs for more than a decade. Learn the JSP EL, the JSTL, and use servlet for the Java code. How to avoid Java Code in JSP-Files?