我在將servlet變量傳遞給jsp時遇到了問題。Servlet JSP getparameter getattribute返回null
當然,我也有web.xml文件中的Servlet已經
<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>
結果是所有的名稱,所有者,品種和性別值爲null。有人可以幫我弄這個嗎?由於
PS:我還試圖用request.getSession()的setAttribute在servlet,沒工作,要麼
PPS。所以,如果我做如下修改:
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);
}
}
,這是我的新的jsp:
<body>
Name="${databaseServlet.NAME}"
Owner="${databaseServlet.OWNER}"
Species="<%= request.getAttribute("SPECIES") %>"
Sex="<%= request.getSession().getAttribute("SEX") %>"
</body>
兩個名稱和所有者,則返回空字符串,而物種和性別仍然返回NULL
基本上就是我想要做的是訪問MySQL數據庫從表中檢索的變量,並使用JSP
顯示它
檢查您的瀏覽器是否接受cookie – SpringLearner
您在哪裏設置servlet中的值屬性? –
我添加了更多的細節到我的java servlet,基本上所有4個變量都是從連接到MySQL數據庫,但我不確定如何實際顯示這些變量的值到JSP – Mantracker