简体   繁体   中英

Using jsp page instead of java servlet

I have created a login page using HTML page and Java Servlet class. However I am wondering if it is possible to have a JSP instead of the Java file? So essential use this code in the Java class into a JSP page and still have the same functionality?

<form action="Lognn" method="post"> 

<input  type="text" name="name"/>
<input type="text"name="pass"/>

Java class

 Public class Login extends HttpServlet {


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        String name = request.getParameter("name");
        String pass = request.getParameter("pass");
        MyDb1 db = new MyDb1();
      Connection con = db.getCon();
      Statement stmt = con.createStatement();
     ResultSet rs = stmt.executeQuery("select uid,name,pass from register where email = '"+name+"' and  pass = '"+pass+"'");

     while ((rs.next())) {

        String uid = rs.getString("uid");

         //out.println("User id"+uid);
          HttpSession session=request.getSession();  
          session.setAttribute("name",uid);
          response.sendRedirect("http://localhost:8080/Final/userprofile.jsp");  

} 


} catch (SQLException ex) {
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);

      }

Generally, each JSP is translated and compiled to a servlet, and a lot of things you can do with servlets you can do with JSP.

You can change your form action="Lognn" method="post" to form action="Lognn.jsp" method="post", then

in Lognn.jsp you can read your input parameters from html like <%= request.getParameter("name")%>, then

in Lognn.jsp you can connect to a database directly or you can use EJB

and finally you can give html output back from the same JSP.

It formally will work without servlet, but in CATALINA_HOME/WORk directory a servlet will be internally created and compiled from your JSP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM