Issue
here is the picture of html page now i want that entered should appear when i enter register button.The file is connected to mysql and the entered data is shown whenever i register.Here is the link to picture.
https://i.stack.imgur.com/aTRfP.png
Here is the code of java file.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String email = request.getParameter("email");
String pass = request.getParameter("pass");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection conn=DriverManager.getConnection
("jdbc:mysql://localhost:3306/form","root","xxxx");
PreparedStatement ps=conn.prepareStatement
("insert into Student values(?,?,?)");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
int i=ps.executeUpdate();
if(i>0)
{
out.println("you are successfully regitered");
}
String query = "SELECT * FROM student";
// create the java statement
Statement st = conn.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next())
{
rs.getString("name");
rs.getString("email");
rs.getString("pass");
// print the results
System.out.format("%s, %s, %s\n", name, email, pass);
System.out.print("name: " + name);
System.out.print(", email: " + email);
System.out.print(", pass: " + pass);
}
st.close();
}
catch(Exception se)
{
se.printStackTrace();
}
}
I have tried adding the links of the html pages in the println function but that doesn't work so please suggest.
Solution
As I understand, you want to show a confirmation message when data is successfully added. When you make a call to a url, a request is created with all the headers and parameters and sent to the server. In your case, the servlet container catches it and processes it and sends the response back.
Writing to the response can be done by:
PrintWriter out = response.getWriter();
out.println("message to return");
However, this does not show the message in the webpage. You have to do that explicitly. You can do it in 2 ways. 1 using ajax. 2 using jsp.
USING AJAX Make an ajax call to the url and process the response in a way that you want. Using libraries like jQuery make it easy.
USING JSP
In the doGet()
or doPost()
methods, add this line in the end
request.setAttribute("message", "my message");
request.getRequestDispatcher(URL).forward(request, response);
This redirects to the specified URL
with the attribute set. Usually, it is a jsp page where you read the attribute and display it however you want.
Answered By - Vj-