Java Web 应用:使用 Servlet 和数据库操作机器人信息
这段代码展示了一个简单的 Java Web 应用,使用 Servlet 和数据库来管理机器人信息。
@WebServlet({"/welcome"})
public class Robot extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String action = req.getParameter("action");
if ("addRobot".equals(action)) {
RobotInfo robot = new RobotInfo();
robot.setNAME(req.getParameter('robotname'));
robot.setweight(req.getParameter('robotweight'));
robot.setsize(req.getParameter('robotsize'));
PreparedStatement pstmt = null;
DBConnected dbc = null;
String sql = "INSERT INTO `javawebdb`.`robot` (`ID`, `NAME`, `WEIGHT`, `SIZE`, `IMAGE`) VALUES (NULL,?,?,?,NULL)";
try {
dbc = new DBConnected();
pstmt = dbc.getConnection().prepareStatement(sql);
pstmt.setString(1, robot.getNAME());
pstmt.setString(2, robot.getweight());
pstmt.setString(3, robot.getsize());
int rs = pstmt.executeUpdate();
pstmt.close();
res.sendRedirect("./welcome.jsp");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
dbc.close();
}
} else if ("deleteRobot".equals(action)) {
RobotInfo robot = new RobotInfo();
String ID = req.getParameter('robotID');
PreparedStatement pstmt = null;
DBConnected dbc = null;
String sql = "DELETE FROM Robot WHERE id = ?";
;
try {
dbc = new DBConnected();
pstmt = dbc.getConnection().prepareStatement(sql);
pstmt.setString(1, ID);
int rs = pstmt.executeUpdate();
pstmt.close();
res.sendRedirect("./welcome.jsp");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
dbc.close();
}
} else if ("changeRobot".equals(action)) {
RobotInfo robot = new RobotInfo();
String ID = req.getParameter('robotID1');
robot.setNAME(req.getParameter('robotname1'));
robot.setweight(req.getParameter('robotweight1'));
robot.setsize(req.getParameter('robotsize1'));
PreparedStatement pstmt = null;
DBConnected dbc = null;
String sql = "UPDATE Robot SET NAME = ?, WEIGHT = ?, SIZE=? WHERE id =?";
;
try {
dbc = new DBConnected();
pstmt = dbc.getConnection().prepareStatement(sql);
pstmt.setString(1, robot.getNAME());
pstmt.setString(2, robot.getweight());
pstmt.setString(3, robot.getsize());
pstmt.setString(4, ID);
int rs = pstmt.executeUpdate();
pstmt.close();
res.sendRedirect("./welcome.jsp");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
dbc.close();
}
}
}
}
这段代码中的增加操作是如何通过req.getParameter获取机器人参数的内容:在增加机器人操作中,通过req.getParameter方法来获取机器人的参数。具体代码如下:
RobotInfo robot = new RobotInfo();
robot.setNAME(req.getParameter('robotname'));
robot.setweight(req.getParameter('robotweight'));
robot.setsize(req.getParameter('robotsize'));
这里使用req.getParameter方法来获取表单中对应的参数值,然后通过setXXX方法将参数值设置到RobotInfo对象中。其中XXX表示RobotInfo对象的属性名,如setNAME表示设置机器人名称。
原文地址: https://www.cveoy.top/t/topic/pcOZ 著作权归作者所有。请勿转载和采集!