Java JSP-更改SQL数据库中的值

Java JSP-更改SQL数据库中的值,java,jsp,jdbc,Java,Jsp,Jdbc,我有一个表,可以在其中显示数据库中的项目。在第一个ResultSet中,我创建了一个下拉菜单,让您选择是否希望该项可用。但是,因为我在第一个结果集rs中创建了它,所以我不能在第二个结果集rs1中使用它。这方面的问题是: if (request.getParameter(rs1.getString("naziv") + "polje").equals("Nedostupno")) 下面是全部代码: 普里卡兹·奥鲁日亚 普里卡兹·奥鲁贾 首先,我将把您的代码拆分为servlet和JSP,并向您展

我有一个表,可以在其中显示数据库中的项目。在第一个ResultSet中,我创建了一个下拉菜单,让您选择是否希望该项可用。但是,因为我在第一个结果集rs中创建了它,所以我不能在第二个结果集rs1中使用它。这方面的问题是:

if (request.getParameter(rs1.getString("naziv") + "polje").equals("Nedostupno"))
下面是全部代码:


普里卡兹·奥鲁日亚
普里卡兹·奥鲁贾

首先,我将把您的代码拆分为servlet和JSP,并向您展示为什么这是一种更好的方法

您的视图(假设称为“foo.jsp”):


普里卡兹·奥鲁日亚
普里卡兹·奥鲁贾

管理员

Naziv

Opis

Cena

Dostupnost

${oruzje.naziv} ${oruzje.opis} ${oruzje.cena}

多斯图普诺 内杜普诺

这假设您有一个支持映射到数据库表的实体:

public class Oruzje {
    private int id;
    private String naziv;
    private String opis;
    private String cena;
    private String dostupnost;
    //propers getters and setters for your fields
}
现在,您的Servlet:

//yes, a Servlet can map directly to your JSP
//there's no problem using this approach
@WebServlet("/foo.jsp")
public class OruzjeServlet extends HttpServlet {
    //I won't go far with more classes
    //nor with other improvements to the code
    //I'll write the basic stuff here in Servlet

    //this method should be in an utility class
    //to provide reusability
    private void closeResource(Closeable resource) {
        try {
            if (resource != null) {
                resource.close();
            }
        } catch (IOException e) {
            //silent exception
        }
    }

    //this method should also be in an utility class
    //and should recover the connection from a DataSource
    //instead of creating the physical connection everytime
    private Connection getConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager
                .getConnection("jdbc:mysql://localhost:3306/CS230-Projekat", "root", "123");
        } catch (Exception e) {
            //this should be splitted for better handling
            //but I leave this up to you
            //handle the exception
            //very basic handling
            e.printStacktrace();
        }
    }

    //this method should be in a proper DAO class
    //reusing a connection for execution of multiple statements
    private List<Oruzje> getOruzjeList(Connection con) {
        List<Oruzje> oruzjeList = new ArrayList<Oruzje>();
        Statement statement = null;
        ResultSet rs = null;
        try {
            statement = connection.createStatement();
            String sql = "SELECT * FROM oruzje";
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()) {
                Oruzje oruzje = new Oruzje();
                oruzje.setId(rs.getInt("id")); //use the real column
                oruzje.setNaziv(rs.getString("naziv"));
                oruzje.setOpis(rs.getString("opis"));
                oruzje.setCena(rs.getString("cena"));
                oruzje.setDostupnost(rs.getString("dostupnost"));
                oruzjeList.add(oruzje);
            }
        } catch (SQLException e) {
            //again, handle the exception
            e.printStacktrace();
        } finally {
            closeResource(rs);
            closeResource(statement);
        }
        return oruzjeList;
    }

    //this method will be executed when a client (browser)
    //tries to enter to your foo.jsp page
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        Connection con = getConnection();
        List<Oruzje> oruzjeList = getOruzjeList(con);
        closeResource(con);
        //setting the oruzjeList variable as attribute
        //this will feed the ${oruzjeList} used in the
        //<c:forEach>
        request.setAttribute("oruzjeList", oruzjeList);
        //now, forward the view to the right view (JSP)
        //it is not a redirect
        request.getRequestDispatcher("/foo.jsp").forward(request, response);
    }

    //this method will be executed when user selects "Apply"
    //option in the view (the JSP)
    //because you stated that the method to submit the <form>
    //is POST
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        //now, we just retrieve the necessary parameters and process the data
        //sent from the form
        Connection con = getConnection();
        List<Oruzje> oruzjeList = getOruzjeList(con);

        //each ? is a parameter in the query
        //starting at index 1
        String updateSql = "UPDATE oruzje SET dostupnost = ? WHERE id = ?";
        PreparedStatement pstmt = con.prepareStatement();
        for(Oruzje oruzje : oruzjeList) {
            //this is where the static part of the name becomes handy
            String theId = request.getParameter("hidId_" + oruzje.getId());
            String theDostupnost = request.getParameter("polje_" + oruzje.getId());
            //I'll avoid basic validation like
            //if (theId == null || "".equals(theId))
            //right to the update!

            //setting the first parameter: dostupnost = ?
            pstmt.setString(1, theDostupnost);
            //setting the second parameter: ID = ?
            //since it's an int, parsing the String to int
            pstmt.setInt(2, Integer.parseInt(theId));
            //perform the update for the current ID and Dostupnost
            pstmt.execute();
        }
        //at the end, closing the resources
        closeResource(pstmt);

        //this is cumbersome but just to make sure
        //the data was updated successfully
        oruzjeList = getOruzjeList(con);
        closeResource(con);
        //similar to the doGet, we will forward to the view
        request.getRequestDispatcher("/foo.jsp").forward(request, response);
    }
}
//是的,Servlet可以直接映射到JSP
//使用这种方法没有问题
@WebServlet(“/foo.jsp”)
公共类OruzjeServlet扩展了HttpServlet{
//我不会再上更多的课了
//也不需要对代码进行其他改进
//我将在这里用Servlet编写基本内容
//此方法应位于实用程序类中
//提供可重用性
私有void closeResource(可关闭资源){
试一试{
if(资源!=null){
resource.close();
}
}捕获(IOE异常){
//沉默的例外
}
}
//此方法也应位于实用程序类中
//并且应该从数据源恢复连接
//而不是每次都创建物理连接
私有连接getConnection(){
试一试{
Class.forName(“com.mysql.jdbc.Driver”);
连接=驱动器管理器
.getConnection(“jdbc:mysql://localhost:3306/CS230-Projekat“、”root“、”123”);
}捕获(例外e){
//应将其分开,以便更好地处理
//但我让你来决定
//处理异常
//非常基本的处理
e、 printStacktrace();
}
}
//此方法应位于适当的DAO类中
//重用连接以执行多个语句
私有列表getoruzzelist(连接con){
List oruzjeList=新建ArrayList();
Statement=null;
结果集rs=null;
试一试{
statement=connection.createStatement();
字符串sql=“从oruzje中选择*”;
ResultSet rs=语句.executeQuery(sql);
while(rs.next()){
Oruzje Oruzje=新的Oruzje();
oruzje.setId(rs.getInt(“id”);//使用实列
oruzje.setNaziv(rs.getString(“naziv”));
oruzje.setOpis(rs.getString(“opis”));
oruzje.setCena(rs.getString(“cena”);
oruzje.setDostupnost(rs.getString(“dostupnost”);
oruzjeList.add(oruzje);
}
}捕获(SQLE异常){
//同样,处理异常
e、 printStacktrace();
}最后{
资源(rs);
资源(报表);
}
返回oruzjeList;
}
//当客户端(浏览器)启动时,将执行此方法
//尝试进入foo.jsp页面
public void doGet(HttpServletRequest请求、HttpServletResponse响应)
抛出ServletException、IOException{
Connection con=getConnection();
List oruzjeList=getOruzjeList(con);
封闭资源(con);
//将oruzjeList变量设置为属性
//这将为中使用的${oruzjeList}提供数据
//
setAttribute(“oruzzelist”,oruzzelist);
//现在,将视图转发到右视图(JSP)
//这不是重定向
request.getRequestDispatcher(“/foo.jsp”).forward(请求,响应);
}
//当用户选择“应用”时,将执行此方法
//视图中的选项(JSP)
//因为您声明了提交
//是邮政
public void doPost(HttpServletRequest请求、HttpServletResponse响应)
抛出ServletException、IOException{
//现在,我们只需检索必要的参数并处理数据
//从表格中发送
Connection con=getConnection();
List oruzjeList=getOruzjeList(con);
//each?是查询中的一个参数
//从索引1开始
String updateSql=“UPDATE oruzje SET dostupnost=?其中id=?”;
PreparedStatement pstmt=con.prepareStatement();
用于(Oruzje Oruzje:oruzjeList){
//这就是名称的静态部分变得方便的地方
String theId=request.getParameter(“hidId_u3;”+oruzje.getId());
串绳