Retrieving data with JSP (JSTL) from a Java MVC an

2019-03-06 13:58发布

This question already has an answer here:

I'm new to Servlets and MVC web programming. So far I have developed a basic CRUD project and would like to add a search function. I would like to use a JSP file to communicate with the servlets and use the tag ( I'm having trouble wording the question, but I hope my code below will clear it up).

Part of My DAO

public List<Courses> getAllCourses() {
    // TODO Auto-generated method stub
    List<Courses> courseList = new ArrayList<Courses>();
    try {
        Statement statement = conn.createStatement();
        ResultSet resultSet = statement.executeQuery( "select * from courses" );
        while( resultSet.next() ) {
            Courses course = new Courses();
            course.setCourseid( resultSet.getInt( "courseid" ) );
            course.setCoursename( resultSet.getString( "coursename" ) );
            course.setFaculty( resultSet.getString( "faculty" ) );
            course.setCourseSpecification( resultSet.getString( "courseSpecification" ) );
            course.setDuration( resultSet.getInt( "duration" ) );
            courseList.add(course);
        }
        resultSet.close();
        statement.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return courseList;
}

public void findCourse(Courses course) {

try { Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery( "select * from courses where coursename=?" );
while( resultSet.next() ) {
Courses course1 = new Courses();
course1.setCourseid( resultSet.getInt( "courseid" ) );
course1.setCoursename( resultSet.getString( "coursename" ) );
course1.setFaculty( resultSet.getString( "faculty" ) );
course1.setCourseSpecification(resultSet.getString("courseSpecification"));
course1.setDuration( resultSet.getInt( "duration" ) );

}
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return;
}

Servelet

@WebServlet(name = "GetStudent", urlPatterns = {"/GetStudent"})
public class FindCourse extends HttpServlet {

private static final long serialVersionUID = 1L;
  @EJB private CourseDao courseDAO;


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Courses course = new Courses();
    String coursename = request.getParameter("coursename");   

    Courses course1= courseDAO.getCourse(course, coursename);
    request.setAttribute("Courses", course1);
    request.getRequestDispatcher("findCourse.jsp").forward(request, response);
}


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

}

JSP

<form action="FindCourse" method="GET">
<input type="text" name="coursename" />
<c:forEach var="course" items="${courses}">
<td><a href="${pageContext.request.contextPath}/FindCoursecoursename=${course.coursename}">${course.coursename}</a></td>

I would love a good explanation of this code as most of it is taken from tutorials etc and I am very kean to learn. So I would like the form to take user input and retrieve the courses which match the query and display the course or possibly courses if more than one course match the name. At the moment I'm getting "resource not found" errors.

As a side question, if I'm allowed, what is the form of the data between the view and the controller? Is there a way of regulating it or forcing it to take JSON/XML? How could I make this simple MVC into a RESTFUL service? I don't expect complex answers just some pointers in the right direction. Overall I have found this very enjoyable and challenging. Thank you.

1条回答
Viruses.
2楼-- · 2019-03-06 14:18

The servlet is the heart of your web application . It functions as the controller where user (http) requests are being processed and response is generated and sent back to the user (usually in the form of a JSP page but could also be an image, a pdf document, a JSON response or any other content corresponding to a predefined http MIME type).

Jsp pages basically serve two purposes: 1) They present the response content to the user and 2) They allow the user to input information that is sent to the server (and then either stored there or used for filtering so as to create different responses). A JSP page should normally not be abused and business logic should be placed into the servlet while the JSP page should only have a minimum JAVA code (this usually means that you will use JSTL and EL (Expression lanhuage) and try to avoid scriptlets as much as possible)

The model in your web application is the data you're working on. An example would be a simple POJO (e.g. Courses) which contains all the fields (and corresponding getters/setters methods) that the Course table has. Typically, the controller will through a DAO (or some other means) access this model and make changes to it.

Regarding data format, JSP is rendered on the server, so normal Java objects can be used between the servlet (controller) and JSP pages. Of course, when you send data via a HTML form (as part of a JSP page), the form data will, by default, be sent in application/x-www-form-urlencoded format. (this would be the enctype attribute of the form element). If you're using a file upload as part of the form , you will have to set data format to multipart/form-data. (as far as I know, a browser should support only these two formats on input)

Now, when you're not using a browser and want to create a REST web service, you will have to do the serialization/deserialization manually. This will involve creating a HTTP client and making HTTP requests (GET/POST) against the URL of the REST service. The actual data will have to be serialized (as JSON, XML, application-x-www-form-urlencoded etc) and attached to the request. The response will have to be deserialized.

As far as user input processing is concerned, you should do something like

//servlet
String courseName = request.getParameter("coursename"); //get the argument
//and then modify the sql query
ResultSet resultSet = statement.executeQuery( "select * from courses where coursename='"+courseName+"'";

Note that it would be much better to use a PreparedStatement than a Statement (because a PreparedStatement is faster and more secure (against sql injection attacks)

As for the error, post the entire stack trace.

查看更多
登录 后发表回答