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/*,只有以对应角色成功登录的用户才能进入。

相关推荐
让学习成为一种生活方式3 分钟前
R包下载太慢安装中止的解决策略-R语言003
java·数据库·r语言
晨曦_子画9 分钟前
编程语言之战:AI 之后的 Kotlin 与 Java
android·java·开发语言·人工智能·kotlin
南宫生31 分钟前
贪心算法习题其三【力扣】【算法学习day.20】
java·数据结构·学习·算法·leetcode·贪心算法
Heavydrink1 小时前
HTTP动词与状态码
java
ktkiko111 小时前
Java中的远程方法调用——RPC详解
java·开发语言·rpc
计算机-秋大田1 小时前
基于Spring Boot的船舶监造系统的设计与实现,LW+源码+讲解
java·论文阅读·spring boot·后端·vue
神里大人1 小时前
idea、pycharm等软件的文件名红色怎么变绿色
java·pycharm·intellij-idea
小冉在学习1 小时前
day53 图论章节刷题Part05(并查集理论基础、寻找存在的路径)
java·算法·图论
代码之光_19802 小时前
保障性住房管理:SpringBoot技术优势分析
java·spring boot·后端
ajsbxi2 小时前
苍穹外卖学习记录
java·笔记·后端·学习·nginx·spring·servlet