添加用户功能
AddServlet
package Servlet; import Bean.User; import Dao.UserDao; 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.xml.crypto.Data; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @WebServlet("/AddServlet") public class AddServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); PrintWriter out=response.getWriter(); //获取参数值 String name=request.getParameter("username"); String password=request.getParameter("password"); String email=request.getParameter("email"); String birthday=request.getParameter("birthday"); //数据封装成User-----bean对象 User user=new User(); user.setName(name); user.setPassword(password); user.setEmail(email); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); Date d= null; try{ d=format.parse(birthday); }catch (ParseException e){ e.printStackTrace(); } user.setBirthday(d);//需要将String类型的birthday转换成Date //添加进数据库 boolean f=new UserDao().insert(user); if (f){ out.print("添加成功!"); }else{ out.print("添加失败!"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
add.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2021/4/22 Time: 8:43 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="/AddServlet" method="post"> 用户名:<input type="text" name="username"><br> 密码:<input type="password" name="password"><br> 邮箱:<input type="text" name="email"><br> 出生日期:<input type="date" name="birthday"><br> <input type="submit" value="提交"> </form> </body> </html>