<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@page import="com.util.SQLConn"%> <%@page import="java.sql.*" %> <%@page import="java.sql.Statement" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <html> <body> <% // 获取前端数据 String username = request.getParameter("username"); String usernum = request.getParameter("usernum"); String userpwd = request.getParameter("userpwd"); // 执行数据库操作 Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; int count = 0; try { conn = SQLConn.openDB(); String sql = "INSERT INTO User_ZC(UserID, Name, Code, Power) VALUES (?, ?, ?, ?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, usernum); pstmt.setString(2, username); pstmt.setString(3, userpwd); pstmt.setInt(4, 1); count = pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { SQLConn.closeDB(conn, pstmt, rs); } // 根据执行结果进行相应的操作 if (count > 0) { request.getRequestDispatcher("ZCS.jsp").forward(request,response); } else { request.getRequestDispatcher("ZCB.jsp").forward(request,response); } %> </body> </html>,优化代码
时间: 2024-01-29 10:03:53 浏览: 98
首先,需要对代码进行分层,将数据库操作和前端数据获取分离。然后可以使用 try-with-resources 语句来代替传统的 try-catch-finally 语句,避免代码冗余。最后,可以将 SQL 语句提取为常量,方便代码维护。
优化后的代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="com.util.SQLConn"%>
<%@page import="java.sql.*" %>
<%@page import="java.sql.Statement" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<body>
<%-- 获取前端数据 --%>
<%
String username = request.getParameter("username");
String usernum = request.getParameter("usernum");
String userpwd = request.getParameter("userpwd");
%>
<%-- 执行数据库操作 --%>
<%
int count = 0;
try (Connection conn = SQLConn.openDB();
PreparedStatement pstmt = conn.prepareStatement(INSERT_SQL)) {
pstmt.setString(1, usernum);
pstmt.setString(2, username);
pstmt.setString(3, userpwd);
pstmt.setInt(4, 1);
count = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
%>
<%-- 根据执行结果进行相应的操作 --%>
<%
if (count > 0) {
request.getRequestDispatcher("ZCS.jsp").forward(request, response);
} else {
request.getRequestDispatcher("ZCB.jsp").forward(request, response);
}
%>
<%-- SQL 语句常量 --%>
<%
private static final String INSERT_SQL = "INSERT INTO User_ZC(UserID, Name, Code, Power) VALUES (?, ?, ?, ?)";
%>
</body>
</html>
阅读全文