将其插入 JSP 顶部以识别会话中的用户
if (session!=null && request.getSession().getAttribute("loggedin") != null) {
if (request.getSession().getAttribute("role").equals("STUDENT")) {
response.sendRedirect("index.jsp");
return;
}
}else{
response.sendRedirect("index.jsp");
return;
}%>
<% if (request.getSession().getAttribute("loggedin") == null) {
response.sendRedirect("index.jsp");
return;
}
StudentDTO dto = (StudentDTO) request.getSession().getAttribute("user");
然后在 JSP 中插入以下代码以将新数据发布到 servlet
<form method="POST" action="EditUserServlet">
<div class="form-submit">
My Information
<div class="submit-section">
<div class="form-row">
<div class="x">
<label>Name</label>
<input type="text" class="form-control" value="<%= dto.getName()%>" name="name">
</div>
<div class="x">
<label>Email</label>
<input type="email" class="form-control" value="<%= dto.getEmail()%>" name="email">
</div>
<div class="form-group x">
<button class="btn" type="submit">Save Changes</button>
</div>
</div>
</div>
</form>
在 EditUserServlet
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
StudentDB db = new StudentDB();
StudentDTO dto = db.getStudentByID(((StudentDTO) request.getSession().getAttribute("user")).getId());
dto.setName(request.getParameter("name"));
dto.setEmail(request.getParameter("email"));
db.updateStudent(dto);
request.getSession().setAttribute("user", dto);
在 StudentDB java 文件中插入这个以通过 Id 查找学生,然后更新学生 sql 文件
public StudentDTO getStudentByID(int id) {
StudentDTO obj = null;
String query = "Select * from students where id=?";
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = conn.prepareStatement(query);
pst.setInt(1,id);
rs = pst.executeQuery();
if (rs != null) {
if (rs.next()) {
obj = new StudentDTO();
obj.setId(rs.getInt(1));
obj.setName(rs.getString(2));
obj.setEmail(rs.getString(3));
obj.setPassword(rs.getString(4));
} catch (SQLException ex) {
Logger.getLogger(StudentDB.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(StudentDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
public boolean updateStudent(StudentDTO obj)
{
int affectedRows = 0;
String query = "update `student` set name=? , email=lower(?) where id=?";
PreparedStatement pst = null;
try {
pst = conn.prepareStatement(query);
pst.setString(1,obj.getName());
pst.setString(2,obj.getEmail());
pst.setInt(10, obj.getId());
System.out.println(pst);
affectedRows = pst.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(StudentDB.class.getName()).log(Level.SEVERE, null, ex);
}
return affectedRows > 0;
}