Java Bean calling Java function and passing it to

2019-09-12 11:28发布

问题:

hi all I have a LoginServlet that has the functionality to log in a user however I have a jsp page with the styling I'd to use. I am unsure how I can use the functionality from my LoginServlet in my login.jsp

here is the entirety of my code for the LoginServlet, I am aware I have coded to display a page but I need to use this jsp page to display. This is a uni assignment I have been given and it's part of the requirement that we use JSP for display.

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 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.RequestDispatcher;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    private void sendLoginForm(HttpServletResponse response, 
              boolean withErrorMessage) 
              throws ServletException, IOException {

              response.setContentType("text/html"); 
              PrintWriter out = response.getWriter(); 
              out.println("<HTML>"); 
              out.println("<HEAD>"); 
              out.println("<TITLE>Login</TITLE>"); 
              out.println("</HEAD>"); 
              out.println("<BODY>"); 
              out.println("<CENTER>"); 

              if (withErrorMessage) 
                out.println("Login failed. Please try again.<BR>"); 

              out.println("<BR>"); 
              out.println("<BR><H2>Login Page</H2>"); 
              out.println("<BR>"); 
              out.println("<BR>Please enter your user name and password."); 
              out.println("<BR>"); 
              out.println("<BR><FORM METHOD=POST>"); 
              out.println("<TABLE>"); 
              out.println("<TR>"); 
              out.println("<TD>User Name:</TD>"); 
              out.println("<TD><INPUT TYPE=TEXT NAME=uniid></TD>"); 
              out.println("</TR>"); 
              out.println("<TR>"); 
              out.println("<TD>Password:</TD>"); 
              out.println("<TD><INPUT TYPE=PASSWORD NAME=password></TD>"); 
              out.println("</TR>"); 
              out.println("<TR>"); 
              out.println("<TD ALIGN=RIGHT COLSPAN=2>"); 
              out.println("<INPUT TYPE=SUBMIT VALUE=Login></TD>"); 
              out.println("</TR>"); 
              out.println("</TABLE>"); 
              out.println("</FORM>"); 
              out.println("</CENTER>"); 
              out.println("</BODY>"); 
              out.println("</HTML>"); 
            } 


    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        sendLoginForm(response, false); 

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    public void doPost(HttpServletRequest request, 
              HttpServletResponse response) 
              throws ServletException, IOException {  
                String uniid = request.getParameter("uniid"); 
                String password = request.getParameter("password"); 
                if (login(uniid, password)) {
                  /*RequestDispatcher rd = 
                    request.getRequestDispatcher("AnotherServlet"); 
                  rd.forward(request, response); */
                    response.sendRedirect("home_student.jsp"); 

                } 
                else {
                  sendLoginForm(response, true); 
                } 

    }

     boolean login(String uniid, String password) {
            try {
              Class.forName("com.mysql.jdbc.Driver");
              Connection con = 
                DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root",""); 
              System.out.println("got connection"); 

              Statement s = con.createStatement(); 
              String sql = "SELECT uniid FROM user" + 
                " WHERE uniid='" + uniid + "'" + 
                " AND password='" + password + "'"; 
              ResultSet rs = s.executeQuery(sql); 
              if (rs.next()) {
                return true; 
              } 
                rs.close(); 
                s.close(); 
                con.close(); 
            } 
            catch (ClassNotFoundException e) {
              System.out.println(e.toString()); 
            } 
            catch (SQLException e) {
              System.out.println(e.toString()); 
            } 
            catch (Exception e) {
              System.out.println(e.toString()); 
            } 
            return false; 
          }


        }

here is my jsp page

<%@ 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>Mars University Lab System</title>
    <link rel="stylesheet" href="style.css" type="text/css" media="screen">
</head>

<body>
<jsp:include page="header.jsp"/>


<tr>
<td>
</td>
</tr>

<tr>
<td>
<div id = "centrecontent">

<table border="0" cellpadding="2">
<tr>
    <td width="500px" align="center">
    <br>
    <font size="5">Welcome to <i>The Department of <br>Rocket Science</i> Lab System<br></font>
    <br>
    For <b>Students</b> you can enrol in labs<br> and manage the labs you're enrolled in.<br><br>

    For <b>Tutors</b> you can view the labs<br> you're teaching and record attendence.<br><br>

    For <b>Lecturers</b> you can create and<br> manage lab classes, register Tutors and<br> assign those Tutors to labs.<br><br>

    </td>
    <td width="500px">
<table border="0" align="center">
        <tr>
        <td align="center">

        <table border="0"  align="center">
            <tr> <br><br><b>Existing Member? <br>Sign In Here!</b><br>
                <td align="right">
                    <form name ="login" METHOD=POST ACTION="SaveSession.jsp">
                        Username: <input type="text" name="username"/><br />
                        Password: <input type="password" name="pword"/><br />
                        <input type=SUBMIT value="Login" name="Submit" />

                </td>
            </tr>
        </table>

                <br><br><br><br>
    <form name="search_cat_bar" method="get" action="">
    <input type="hidden" name="dff_view" value="grid">
       Search:<input type="text" name="dff_keyword" size="30" maxlength="50"> <br>in 
       <select name="dff_cat1num" size="1">
         <option value="-1">All Subjects
         <option value="-2">--------------
         <option value="101">CSE2ICE
         <option value="193">CSE3PRA
         <option value="193">CSE3PRB
         <option value="193">CSE3WAE
       </select>
       <input type="submit" value="Find">
       </form>

        </td>
</tr>
</table>


</td>
</tr>
</table>

<table>
<tr>
</tr>
</table>

</div>




<jsp:include page="footer.jsp"/>


</body>

</html>

I'd like the login.jsp page to call my LoginServlet for the login functions.

回答1:

You can call servlet by this way: web.xml

<servlet>
        <servlet-name>UserLogin</servlet-name>
        <servlet-class>com.servlet.LoginServlet</servlet-class>//full class path
</servlet>

<servlet-mapping>
        <servlet-name>UserLogin</servlet-name>
        <url-pattern>/servlet/login</url-pattern>
    </servlet-mapping>  

login.jsp

<form name="login" action="<%=request.getContextPath()%>/servlet/login" method="post">

</form>

Servlet: Login check and also you can send just error message to login page and display message like,

res.sendRedirect(req.getContextPath()+"/webpages/login.jsp?login=failed");

And in login.jsp you can retrieve parameter request.getParameter("login") and display proper message



回答2:

  1. add action in the html form tag.
  2. action is LoginServlet URL.


回答3:

It's easier to have the standard way of doing this:

  1. Have jsp page with a form, to receive inputs from the user.
  2. Have a servlet to process the data.
  3. If there is a problem, set an error message and redirect the user to the login page. Otherwise redirect him to the destination.
  4. Do not forget to set your form's action the address of your servlet.