javaEE11(servlet课后习题1,3(将思路实现一下))

1. 在第5 章课后习题2 基础上,基于jsp+servlet+javabean 实现学生表的增删改查。

数据处理交给Servlet

java 复制代码
package servlet;



import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;



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 dao.StudentDao;

import entity.Student;



/**

 * Servlet implementation class StudentServlet

 */

@WebServlet("/studentServlet")

public class StudentServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    StudentDao studentDao=new StudentDao();

      

    /**

     * @see HttpServlet#HttpServlet()

     */

    public StudentServlet() {

        super();

        // TODO Auto-generated constructor stub

    }



    /**

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // TODO Auto-generated method stub

        this.doPost(request, response);

    }



    /**

     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // TODO Auto-generated method stub

        request.setCharacterEncoding("UTF-8");

        String  op=request.getParameter("op");

        if("add".equals(op)) {

             Student student=new Student(request.getParameter("sno"),request.getParameter("sname"),request.getParameter("sex"));

                try{

                studentDao.add(student);

                List<Student> studentList = studentDao.query();

                   //request.setAttribute("studentList",studentList);

                    //request.getRequestDispatcher("query.jsp").forward(request,response);

                response.sendRedirect("/web1/studentServlet?op=query");

             

                }

                catch(Exception e){

               

                response.setContentType("text/html;charset=UTF-8");

                PrintWriter out=response.getWriter();

                    out.print("<script>alert('学号不唯一')</script>");

                }

        }

        else if("update".equals(op)) {

            Student student=new Student();

            student.setId(Integer.parseInt(request.getParameter("id")));

            student.setSno(request.getParameter("sno"));

            student.setSname(request.getParameter("sname"));

            student.setSex(request.getParameter("sex"));

            try{studentDao.update(student);

            List<Student> studentList = studentDao.query();

            request.setAttribute("studentList",studentList);

            request.getRequestDispatcher("query.jsp").forward(request,response);

            }

            catch(Exception e){

                response.setContentType("text/html;charset=UTF-8");

            PrintWriter out=response.getWriter();

                out.print("<script>alert('更新失败,学号不唯一')</script>");

            }

        }

        else if("query".equals(op)) {

            List<Student> studentList;

            try {

                studentList = studentDao.query();

                request.setAttribute("studentList",studentList);

                request.getRequestDispatcher("/query.jsp").forward(request,response);

            } catch (Exception e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

           

           

        }

        else if("delete".equals(op)) {

            try {

                studentDao.delete(Integer.parseInt(request.getParameter("id")));

                List<Student> studentList = studentDao.query();

                request.setAttribute("studentList",studentList);

                request.getRequestDispatcher("query.jsp").forward(request,response);

            } catch (NumberFormatException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            } catch (Exception e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

        }

       

    }



}

jsp 只负责显示

java 复制代码
<%@ page  pageEncoding="UTF-8" import="java.util.*,entity.*,dao.*"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>

<head>

<style>

  body{

      text-align:center;

  }

  th,td{

  border:2px solid gray;

  text-align:center;

  padding:3px 10px;

  }

  table{

  border-collapse:collapse;

  margin:10px auto;

  }



  #form1{

  padding:20px;

  display:none;

  position:fixed;

  top:50%;

  left:50%;

  width:300px;

  height:200px;

  z-index:1000;

  margin-left:-200px;

  margin-top:-200px;

   background: #88f;

  }

 </style>



</head>



<body>

  <h3><a href="javascript:add()">添加记录</a></h3>

 <h2>学生信息</h2>

   <table>

   <tr><th>学号</th><th>姓名</th><th>性别</th><th>修改</th><th>删除</th></tr>

  <c:forEach items="${studentList}" var="student" varStatus="st">

  <tr>

   

   <td>${student.sno}</td>

   <td>${student.sname}</td>

   <td>${student.sex}</td>

     <td><a href="javascript:update(${student.id},'${student.sno}','${student.sname}','${student.sex}')">修改</a></td>

   <td><a href="${pageContext.request.contextPath}/studentServlet?op=delete&id=${student.id}" onclick="return confirm('确实要删除吗?')">删除</a></td>   

  </tr>

 </c:forEach>

 </table>

 <form method="post" id="form1" action="${pageContext.request.contextPath}/studentServlet">

学号<input type="text" name="sno" id="sno"/><br><br>

 姓名<input type="text" name="sname" id="sname"/><br><br>

性别<input type="radio" name="sex" value="男" checked/>男<input type="radio" name="sex" value="女" />女<br><br>

 <input type="hidden" name="op" value="" id="op"/>

 <input type="hidden" name="id" id="id"/>

 <input type="submit" value="" id="bt"/>

 <input type="reset" value="重置"/>

  <input type="button" value="关闭" onclick="document.getElementById('form1').style.display='none';"/>

 </form>

 <br>

 <script>

 function add(){

     document.getElementById("bt").value="添加";

     document.getElementById("op").value="add";

     document.getElementById("form1").style.display="block";

     //document.getElementById('form1').action='query.jsp';

     

 }

 function update(id,sno,sname,sex){

     document.getElementById("bt").value="修改";

     document.getElementById("op").value="update";

     document.getElementById("id").value=id;

     document.getElementById("sno").value=sno;

     document.getElementById("sname").value=sname;

     var sexs=document.getElementsByName("sex");

     if(sex=='男'){

         sexs[0].checked=true;sexs[1].checked=false;

     }

     else{

         sexs[0].checked=false;sexs[1].checked=true;

     }

     document.getElementById("form1").style.display="block";

    //document.getElementById('form1').action='query.jsp';

     

 }

 </script>

</body>

</html>
  1. 使用过滤器实现多角色登录检验
  1. 分别建立admin、teacher、student三个目录,里面放置各自主页面。
  2. 登录页面
java 复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

<form>

userid<input type="text"/>

userpwd<input type="text"/>

admin<input type="radio" name="role" value="admin">

teacher<input type="radio" name="role" value="teacher">

student<input type="radio" name="role" value="student">

<input type="submit" value="login"/>

</form>

<%

String role=request.getParameter("role");

if(role!=null){

    session.setAttribute("role",role);

    response.sendRedirect("/zdw/"+role+"/index.jsp");

}

%>

</body>

</html>
  1. 完成登录功能的servlet,登录成功在session中存入用户名和角色名。
java 复制代码
package servlet;



import java.io.IOException;



import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;



public class servletdenglu extends HttpServlet{

      public servletdenglu(){

        super();

    }

   

    protected void doGet(HttpServletRequest request,HttpServletResponse response)

            throws ServletException,IOException{

   

    }

   

    protected void doPost(HttpServletRequest request,HttpServletResponse response)

            throws ServletException,IOException{

        doGet(request, response);

        request.setCharacterEncoding("utf-8");

        response.setContentType("text/html;charset=utf-8");

        HttpSession session=request.getSession();

        String shenfen=request.getParameter("role");

        String username=request.getParameter("userid");

        if(shenfen.equals("admin")&&username!=null) {

                  session.setAttribute("Name",username);

            response.sendRedirect("/zdw/"+shenfen+"/index.jsp");

        }else if(shenfen.equals("teacher")&&username!=null){

            session.setAttribute("Name",username);

            response.sendRedirect("/zdw/"+shenfen+"/index.jsp");

        }else if(shenfen.equals("student")&&username!=null) {

            session.setAttribute("Name",username);

            response.sendRedirect("/zdw/"+shenfen+"/index.jsp");

        }

       

       

       

       

    }



}

(4)建立三个过滤器,分别拦截admin/*,teacher/*,student/*,只有以对应角色成功登录的用户才能进入。

相关推荐
天天扭码12 分钟前
五天SpringCloud计划——DAY2之单体架构和微服务架构的选择和转换原则
java·spring cloud·微服务·架构
程序猿进阶13 分钟前
堆外内存泄露排查经历
java·jvm·后端·面试·性能优化·oom·内存泄露
FIN技术铺17 分钟前
Spring Boot框架Starter组件整理
java·spring boot·后端
小曲程序24 分钟前
vue3 封装request请求
java·前端·typescript·vue
陈王卜42 分钟前
django+boostrap实现发布博客权限控制
java·前端·django
小码的头发丝、42 分钟前
Spring Boot 注解
java·spring boot
java亮小白19971 小时前
Spring循环依赖如何解决的?
java·后端·spring
飞滕人生TYF1 小时前
java Queue 详解
java·队列
武子康1 小时前
大数据-230 离线数仓 - ODS层的构建 Hive处理 UDF 与 SerDe 处理 与 当前总结
java·大数据·数据仓库·hive·hadoop·sql·hdfs
武子康1 小时前
大数据-231 离线数仓 - DWS 层、ADS 层的创建 Hive 执行脚本
java·大数据·数据仓库·hive·hadoop·mysql