通过session会话将信息在页面与servlet,和不同页面之间的传递
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
@WebServlet("/Addagent")
public class Addagent extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
String type=(String)session.getAttribute("type");
String id=(String)session.getAttribute("id");
String agentid = req.getParameter("agentid");
String password = req.getParameter("password");
String agentname = req.getParameter("agentname");
String agentadress = req.getParameter("agentadress");
String phone = req.getParameter("phone");
Agentdata data=new Agentdata(agentid,password,agentname,agentadress,phone);
Agentdao dao=new Agentdao();
try {
if(dao.addagent(data)){
req.setAttribute("success","新增成功");
req.getSession().setAttribute("type",type);
req.getSession().setAttribute("id",id);
resp.sendRedirect("user.jsp");
}
else{
req.setAttribute("error","新增失败");
req.getRequestDispatcher("addagent.jsp").forward(req, resp);
}
} catch (SQLException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
public boolean addagent(Agentdata data) throws SQLException, ClassNotFoundException {
String sql="insert into agent values(?,?,?,?,?)";
try(Connection conn=getConnection(); PreparedStatement pstmt=conn.prepareStatement(sql)){
pstmt.setString(1, data.getAgentid());
pstmt.setString(2, data.getPassword());
pstmt.setString(3, data.getAgentname());
pstmt.setString(4, data.getAgentaddress());
pstmt.setString(5, data.getPhone());
return pstmt.executeUpdate()>0;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>新增房产经纪人</title>
</head>
<body>
<form action="Addagent" method="post">
<label for="agentid">工号:</label>
<input type="text" name="agentid" id="agentid"></input><br>
<label for="password">密码:</label>
<input type="password" name="password" id="password"></input><br></br>
<label for="agentname">房产经纪人姓名:</label>
<input type="text" name="agentname" id="agentname"><br></br>
<label for="agentaddress">家庭住址</label>
<input type="text" name="aggentaddress" id="agentaddress"><br></br>
<label for="phone">手机号码:</label>
<input type="text" name="phone" id="phone"><br></br>
<input type="submit" value="增加">
</form>
<%
String type = (String) session.getAttribute("type");
String id = (String) session.getAttribute("id");
session.setAttribute("type",type);
session.setAttribute("id",id);
%>
</body>
</html>