day52
servlet
综合案例
登录功能
设置欢迎页
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <welcome-file-list> <welcome-file>login.html</welcome-file> </welcome-file-list> </web-app>项目启动直接加载login.html页面
login.html,用户输入自己的用户名和密码,提交后交给mylogin请求
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>login</title> </head> <body> <form action="mylogin" method="post"> username: <input type="text" name="username" placeholder="username"><p /> password: <input type="password" name="password" placeholder="password"><p /> <input type="submit" value="login"><p /> </form> </body> </html>
由mylogin请求对应的servlet来进行处理
package com.saas.servlet; import com.saas.service.IAccountService; import com.saas.service.impl.AccountServiceImpl; 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 java.io.IOException; @WebServlet(urlPatterns = "/mylogin") public class MyLoginServlet extends HttpServlet { private IAccountService ias = new AccountServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); System.out.println("this is my login servlet ."); String username = req.getParameter("username"); String password = req.getParameter("password"); boolean flag = ias.login(username, password); if (flag) { System.out.println("login success"); req.getRequestDispatcher("main.html").forward(req, resp); } else { System.out.println("login fail"); req.getRequestDispatcher("login.html").forward(req, resp); } } }
mylogin所对用的MyLoginServlet会调用IAccountService接口和AccountServiceImpl实现类完成成service中登录方法的校验
package com.saas.service; public interface IAccountService { boolean login(String username, String password); }
AccountServiceImpl是service的实现类,调用dao接口和dao实现类完成dao层的登录方法校验
package com.saas.service.impl; import com.saas.dao.IAccountDao; import com.saas.dao.impl.AccountDaoImpl; import com.saas.service.IAccountService; public class AccountServiceImpl implements IAccountService { private IAccountDao iAccountDao = new AccountDaoImpl(); @Override public boolean login(String username, String password) { return iAccountDao.login(username, password); } }
dao接口
package com.saas.dao; public interface IAccountDao { boolean login(String username, String password); }
dao实现类,使用apache的dbutil工具jar包的queryrunner对象即可完成所有的crud功能
本方法完成登录功能
借助DruidUtil工具类的getDataSource()方法得到一个DataSource对象来创建QueryRunner对象
package com.saas.dao.impl; import com.saas.dao.IAccountDao; import com.saas.entity.Account; import com.saas.util.DruidUtil; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import java.sql.SQLException; public class AccountDaoImpl implements IAccountDao { private QueryRunner qr = new QueryRunner(DruidUtil.getDataSource()); @Override public boolean login(String username, String password) { try { String sql = "select * from account where name = ? and pass = ?"; Account a = qr.query(sql, new BeanHandler<Account>(Account.class), new Object[]{username, password}); return a != null; } catch (SQLException e) { throw new RuntimeException(e); } } }
dao借助工具类完成与数据库的交互,得到一个用户名和密码对应的Account对象,通过Account对象是否为空判断用户是否存在
dao完成用户账户信息的判断后,返回给service,返回给servlet
在servlet中通过返回值动态决定调转到main.html页面还是继续回到login.html页面,最终完成一个登录功能
查询所有学生
main.html页面中有一个查询所有学生的超链接
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>main</title> </head> <body> <h1>this is main page</h1> <a href="stus">show all students</a> </body> </html>
该超链接发送一个地址为stus的请求,该请求交给一个servlet: AllStudentServlet.java
package com.saas.servlet; import com.saas.entity.Student; import com.saas.service.IStudentService; import com.saas.service.impl.StudentServiceImpl; 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 java.io.IOException; import java.io.PrintWriter; import java.util.List; @WebServlet(urlPatterns = "/stus") public class AllStudentServlet extends HttpServlet { private IStudentService iss = new StudentServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); resp.setCharacterEncoding("UTF-8"); req.setCharacterEncoding("UTF-8"); List<Student> list = iss.getAllStudents(); System.out.println(list); PrintWriter out = resp.getWriter(); out.print("<table border='1' align='center' width='80%'>"); out.print("<tr>"); out.print("<td>编号</td>"); out.print("<td>姓名</td>"); out.print("<td>性别</td>"); out.print("<td>年龄</td>"); out.print("<td>成绩</td>"); out.print("<td>管理</td>"); out.print("</tr>"); for (Student s : list) { out.print("<tr>"); out.print("<td>" + s.getSid() + "</td>"); out.print("<td>" + s.getName() + "</td>"); out.print("<td>" + s.getSex() + "</td>"); out.print("<td>" + s.getAge() + "</td>"); out.print("<td>" + s.getScore() + "</td>"); out.print("<td><a href='GetStudentBySidServlet?sid=" + s.getSid() + "'>update</a> <a href='#'>delete</a> </td>"); out.print("</tr>"); } out.print("</table>"); } }
该servlet借助IStudentService的service接口和StudentServiceImpl的service接口的实现类,完成全部学生信息的查询
service接口IStudentService.java
package com.saas.service; import com.saas.entity.Student; import java.util.List; public interface IStudentService { List<Student> getAllStudents(); Student getStudentBySid(int sid); boolean updateStudent(Student student); }
service接口的实现类StudentServiceImpl.java
package com.saas.service.impl; import com.saas.dao.IStudentDao; import com.saas.dao.impl.StudentDaoImpl; import com.saas.entity.Student; import com.saas.service.IStudentService; import java.util.List; public class StudentServiceImpl implements IStudentService { private IStudentDao isd = new StudentDaoImpl(); @Override public List<Student> getAllStudents() { return isd.getAllStudents(); } @Override public Student getStudentBySid(int sid) { return isd.getStudentBySid(sid); } @Override public boolean updateStudent(Student student) { return isd.updateStudent(student) > 0; } }Student的service接口调用Student的dao完成与数据库的交互,并将数据返回
package com.saas.dao; import com.saas.entity.Student; import java.util.List; public interface IStudentDao { List<Student> getAllStudents(); Student getStudentBySid(int sid); int updateStudent(Student student); }package com.saas.dao.impl; import com.saas.dao.IStudentDao; import com.saas.entity.Student; import com.saas.util.DruidUtil; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import java.sql.SQLException; import java.util.List; public class StudentDaoImpl implements IStudentDao{ private QueryRunner qr = new QueryRunner(DruidUtil.getDataSource()); @Override public List<Student> getAllStudents() { try { return qr.query("select * from student", new BeanListHandler<Student>(Student.class)); } catch (SQLException e) { throw new RuntimeException(e); } } @Override public Student getStudentBySid(int sid) { try { return qr.query("select * from student where sid = ?", new BeanHandler<Student>(Student.class), sid); } catch (SQLException e) { throw new RuntimeException(e); } } @Override public int updateStudent(Student student) { try { return qr.update("update student set name = ?, sex = ?, score = ?, cid = ?, age = ? where sid = ? ", student.getName(), student.getSex(), student.getScore(), student.getCid(), student.getAge(), student.getSid()); } catch (SQLException e) { throw new RuntimeException(e); } } }
完成所有学生信息的查询,返回给service,返回给servlet
在servlet中将学生的list借助servlet在页面中以表格方式呈现
查询单个学生对象
在AllStudentServlet这个servlet的表格中,每一个数据的最后放置了一个修改的超链接
<a href='GetStudentBySidServlet?sid=" + s.getSid() + "'>update</a>在这个超链接中,href为GetStudentBySidServlet,那么请求将交给GetStudentBySidServlet地址所对应的sevlet,该请求的最后还有一个问号传参
该请求将交由GetStudentBySidServlet.java的servlet来处理
package com.saas.servlet; import com.saas.entity.Student; import com.saas.service.IStudentService; import com.saas.service.impl.StudentServiceImpl; 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 java.io.IOException; import java.io.PrintWriter; @WebServlet("/GetStudentBySidServlet") public class GetStudentBySidServlet extends HttpServlet { private IStudentService studentService = new StudentServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); resp.setCharacterEncoding("UTF-8"); req.setCharacterEncoding("UTF-8"); System.out.println("this is update student page."); String ssid = req.getParameter("sid"); int sid = ssid == null ? 0 : Integer.parseInt(ssid); Student s = studentService.getStudentBySid(sid); PrintWriter out = resp.getWriter(); out.print("<h1>this is update student page.</h1>"); out.print("<form action='UpdateStudentServlet' method='post'>"); out.print("<input type=\"hidden\" name=\"sid\" value=\"" + s.getSid() + "\"><p />"); out.print("name:<input type=\"text\" name=\"name\" value=\"" + s.getName() + "\"><p />"); out.print("sex:<input type=\"text\" name=\"sex\" value=\"" + s.getSex() + "\"><p />"); out.print("age:<input type=\"text\" name=\"age\" value=\"" + s.getAge() + "\"><p />"); out.print("score:<input type=\"text\" name=\"score\" value=\"" + s.getScore() + "\"><p />"); out.print("cid:<input type=\"text\" name=\"cid\" value=\"" + s.getCid() + "\"><p />"); out.print("<input type=\"submit\" value=\"update\"><p />"); out.print("</form>"); } }
该servlet借助IStudentService对象的getStudentBySid方法,进行用户编号查询用户的操作
该servlet同样调用service以及dao完成数据的查询,得到sid对应的学生对象
得到问号传参传递过来的sid的值,将该sid对应的学生对象以表单方式呈现给用户
修改学生对象
在GetStudentBySidServlet的servlet里面,由form表单将数据库中指定sid对应的学生对象呈现在页面表单中
用户在该表单中修改该学生信息
点击提交按钮,将发送一个新的请求,该请求是form表单中action所对应的UpdateStudentServlet的servlet
所以该表单提交后交给UpdateStudentServlet这个sevlet
package com.saas.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 java.io.IOException; import com.saas.entity.Student; import com.saas.service.IStudentService; import com.saas.service.impl.StudentServiceImpl; @WebServlet(urlPatterns = "/UpdateStudentServlet") public class UpdateStudentServlet extends HttpServlet { private IStudentService istudentService = new StudentServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); int sid = Integer.parseInt(req.getParameter("sid")); String name = req.getParameter("name"); String sex = req.getParameter("sex"); double score = Double.parseDouble(req.getParameter("score")); int cid = Integer.parseInt(req.getParameter("cid")); int age = Integer.parseInt(req.getParameter("age")); Student student = new Student(sid, name, sex, score, cid, age); boolean flag = istudentService.updateStudent(student); if (flag) { resp.getWriter().write("<script>alert('修改成功');location.href='/day51/stus'</script>"); } else { resp.getWriter().write("<script>alert('修改失败');location.href='/day51/stus'</script>"); } } }该servlet收集用户输入的所有信息,将这些所有信息封装为一个Student对象
再将Student对象借助Student的service和dao完成一个修改功能
修改成功后给用户一个修改成功的弹框并跳转到stus所对应的servlet展示最新的学生列表信息
修改失败给用户一个提示,也跳转到stus请求对应的serlvet