Как сделать несколько зависимых выпадающих списков в сервлете JSP через MySQL - PullRequest
0 голосов
/ 23 марта 2019

Я хотел создать несколько зависимых выпадающих списков, включая страну и город в сервлете jsp через mysql.

Я сделал некоторый код, основанный на листинге страны, но я не знаю, как сделать подплату в соответствии с выбранным названием страны. Как я могу это сделать?

Вот мои коды, которые я написал до сих пор.

Страна (Pojo)

public class Country{
    private int countryId;
    private String name;
    @OneToMany(mappedBy="country", cascade=CascadeType.ALL)
    private List<State> states;

    public Country(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Штат

public class State{
    private int id;
    private String name;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "countryId", nullable = false)
    private Country country;

    public State(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

CountryDao класс, перечисляющий страну

public class CountryDao {
    String databaseURL = "jdbc:mysql://localhost:3306/bookstoredb";
    String user = "root";
    String password = "pass";

    public List<Country> list() throws SQLException {
        List<Country> listCountry = new ArrayList<>();

        try (Connection connection = DriverManager.getConnection(databaseURL, user, password)) {
            String sql = "SELECT * FROM country ORDER BY name";
            Statement statement = connection.createStatement();
            ResultSet result = statement.executeQuery(sql);

            while (result.next()) {
                int id = result.getInt("country_id");
                String name = result.getString("name");
                Country country = new Country(id, name);

                listCountry.add(country );
            }          

        } catch (SQLException ex) {
            ex.printStackTrace();
            throw ex;
        }      

        return listCountry;
    }
}

StateDao

public class StateDao {
    String databaseURL = "jdbc:mysql://localhost:3306/bookstoredb";
    String user = "root";
    String password = "pass";

    public List<State> list(int countryId) throws SQLException {
        List<State> listState = new ArrayList<>();

        try (Connection connection = DriverManager.getConnection(databaseURL, user, password)) {
            String sql = "SELECT * FROM STATE WHERE countryId=?";
            PrepareStatement statement = connection.prepareStatement();
            statement.getInt(1,countryId);
            ResultSet result = statement.executeQuery();

            while (result.next()) {
                int id = result.getInt("state_id");
                String name = result.getString("name");
                State state = new State(id, name);

                listState.add(state);
            }          

        } catch (SQLException ex) {
            ex.printStackTrace();
            throw ex;
        }      

        return listState;
    }
} 

FormServlet

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

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        CountryDao dao = new CountryDao();

        try {

            List<Country> listCountry= dao.list();
            request.setAttribute("listCountry", listCountry);

            RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
            dispatcher.forward(request, response);

        } catch (SQLException e) {
            e.printStackTrace();
            throw new ServletException(e);
        }
    }
}

JSP Page

<form action="FormServlet" method="post">
        Select a Country:&nbsp;
        <select name="category">
            <c:forEach items="${listCountry}" var="country">
                <option value="${country.id}"
                    <c:if test="${country.id eq selectedcountryId}">selected="selected"</c:if>
                    >
                    ${country.name}
                </option>
            </c:forEach>
        </select>
        <br/><br/>
        <input type="submit" value="Submit" />
</form>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...