JavaWeb学习.华清远见

登录增删改查

配置xml
<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.30</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

实现登录

1.连接数据库
2.配置界面
在jsp中,可以使用heml标签,也可以嵌套java语言(用<% %>)
其中运用el表达式(${变量} ${reques对象中保存的key} )

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
<%
    // ***  获取cookie
    Cookie[] cookies = request.getCookies();
    if(cookies != null){
        for(Cookie cookie : cookies){
            if(cookie.getName().equals("name")){
                // **  把cookie的value值,获取出来,设置到request对象中
                request.setAttribute("name" , cookie.getValue());
            }
            if(cookie.getName().equals("password")){
                // **  把cookie的value值,获取出来,设置到request对象中
                request.setAttribute("pwd" , cookie.getValue());
            }
        }
    }
    session.invalidate();//在登录界面,表示之前的登录信息需要删除,设置session无效
%>
<form action="<%=request.getContextPath()%>/login">
    <label>用户名:</label>
    <input type="text" name="name" value="${name}">
    <br>
    <label>密码:</label>
    <input type="password" name="password" value="${pwd}">
    <br>
    <input type="checkbox" name="save" value="1" checked>是否记住密码?
    <br>
    <input type="submit" value="登录">
    <input type="reset" value="重置">
</form>
</body>
</html>

在这里插入图片描述

3.根据数据库创建用户实体类
4.编写dao类,根据用户名和密码查询数据库中数据是否匹配

public class UserDao {
    Connection conn;
    PreparedStatement pst;
    ResultSet rs;
    public User getUserByNameAndPwd(String name,String pwd){
        conn= DBUtil.getConn();
        String sql="select * from user where u_name=? and u_password=?";
        try {
            pst=conn.prepareStatement(sql);
            pst.setString(1,name);
            pst.setString(2,pwd);
            rs=pst.executeQuery();
            if (rs.next()){
                User user = new User();
                user.setuId(rs.getInt(1));
                user.setuName(rs.getString(2));
                user.setuPassword(rs.getString(3));
                user.setrId(rs.getInt(4));
                return user;
            }
        }catch (SQLException e){
            System.out.println("查询用户错误"+e);
        }finally {
            DBUtil.getClose(conn,pst,rs);
        }
        return null;
    }
}

5.创建service类实现功能
6.servlet类,实现从界面获取数据并响应
设置cookie保存用户名与密码,实现保存密码功能
设置session保存登陆的用户,实现只有登录才能使用功能

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        //获取参数
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String save = req.getParameter("save");
        UserService userService = new UserService();
        User user = userService.getUser(name, password);
        //判断
        if (user!=null){
            //成功
            HttpSession session = req.getSession();
            session.setAttribute("loginuser",user);
            if ("1".equals(save)){
                //保存
                Cookie cookie = new Cookie("name", name);
                Cookie cookie1 = new Cookie("password", password);
                resp.addCookie(cookie);
                resp.addCookie(cookie1);
            }else {
                //不需要保存
                Cookie[] cookies = req.getCookies();
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("name") || cookie.getName().equals("password")){
                        cookie.setMaxAge(0);
                        resp.addCookie(cookie);
                    }
                }
            }
            resp.sendRedirect(req.getContextPath()+"/list.do");
        }else {
            //不正确
            Cookie[] cookies = req.getCookies();
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("name") || cookie.getName().equals("password")){
                    cookie.setMaxAge(0);
                    resp.addCookie(cookie);
                }
            }
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
            HttpSession session = req.getSession();
            session.removeAttribute("loginuser");
        }
    }
}

实现增删改查

1.设计界面
①查询

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>显示学校</title>
</head>
<body>
<a href="<%=request.getContextPath()%>/addSchool.jsp">添加学校</a>
<hr>
<h2>显示学校列表</h2>
<table border="1">
    <tr>
        <th>学校编号</th>
        <th>学校名字</th>
        <th>学校地址</th>
        <th>建校日期</th>
        <th>总人数</th>
        <th>占地面积</th>
        <th>操作</th>
    </tr>
    <c:forEach items="${schools}" var="itschool">
        <tr>
            <td>${itschool.scCode}</td>
            <td>${itschool.scName}</td>
            <td>${itschool.scAddress}</td>
            <td>${itschool.scBirth}</td>
            <td>${itschool.scTotal}</td>
            <td>${itschool.scArea}</td>
            <td>
                <a href="<%=request.getContextPath()%>/toUpdate.do?scCode=${itschool.scCode}">修改</a>
                <a href="<%=request.getContextPath()%>/delete.do?scCode=${itschool.scCode}">删除</a>
            </td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

在这里插入图片描述
②增加

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加学校</title>
</head>
<body>
<a href="<%=request.getContextPath()%>/list.do">查看学校</a>
<hr>
<h3>添加学校</h3>
<form action="<%=request.getContextPath()%>/add.do" method="get">
    <label>学校名字</label>
    <input type="text" name="scName">
    <br>
    <label>学校地址</label>
    <input type="text" name="scAddress">
    <br>
    <label>建校日期</label>
    <input type="datetime" name="scBirth">
    <br>
    <label>总人数</label>
    <input type="text" name="scTotal">
    <br>
    <label>占地面积</label>
    <input type="text" name="scArea">
    <br>
    <input type="submit" value="添加">
    <input type="reset" value="重置">
</form>
</body>
</html>

在这里插入图片描述
③改

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>修改学校</title>
</head>
<body>
<a href="<%=request.getContextPath()%>/list.do">查看学校</a>
<hr>
<h3>修改学校</h3>
<form action="<%=request.getContextPath()%>/update.do" method="get">
    <input type="hidden" name="scCode" value="${school.scCode}">
    <label>学校名字</label>
    <input type="text" name="scName" value="${school.scName}">
    <br>
    <label>学校地址</label>
    <input type="text" name="scAddress" value="${school.scAddress}">
    <br>
    <label>建校日期</label>
    <input type="datetime" name="scBirth" value="${school.scBirth}">
    <br>
    <label>总人数</label>
    <input type="text" name="scTotal" value="${school.scTotal}">
    <br>
    <label>占地面积</label>
    <input type="text" name="scArea" value="${school.scArea}">
    <br>
    <input type="submit" value="修改">
    <input type="reset" value="重置">
</form>
</body>
</html>

在这里插入图片描述
2.根据数据库实现学校实体类
3.实现dao命令

public class SchoolDao {
    Connection conn;
    PreparedStatement pst;
    ResultSet rs;
    //查
    public List<School> getSchools(){
        conn= DBUtil.getConn();
        String sql="select * from school ";
        List<School> list = new ArrayList<>();
        try {
            pst=conn.prepareStatement(sql);
            rs=pst.executeQuery();
            while (rs.next()){
                School school = new School();
                school.setScCode(rs.getInt(1));
                school.setScName(rs.getString(2));
                school.setScAddress(rs.getString(3));
                school.setScBirth(rs.getTimestamp(4));
                school.setScTotal(rs.getInt(5));
                school.setScArea(rs.getDouble(6));
                list.add(school);
            }
            return list;
        }catch (SQLException e){
            System.out.println("查询错误"+e);
        }finally {
            DBUtil.getClose(conn,pst,rs);
        }
        return null;
    }
    //根据主键查找
    public School getSchool(int scCode){
        conn= DBUtil.getConn();
        String sql="select * from school where sc_code="+scCode;
        try {
            pst=conn.prepareStatement(sql);
            rs=pst.executeQuery();
            School school = new School();
            if (rs.next()){
                school.setScCode(rs.getInt(1));
                school.setScName(rs.getString(2));
                school.setScAddress(rs.getString(3));
                school.setScBirth(rs.getTimestamp(4));
                school.setScTotal(rs.getInt(5));
                school.setScArea(rs.getDouble(6));
            }
            return school;
        }catch (SQLException e){
            System.out.println("根据code查询错误"+e);
        }finally {
            DBUtil.getClose(conn,pst,rs);
        }
        return null;
    }
    //根据主键修改
    public int updateSchool(School school){
        conn=DBUtil.getConn();
        String sql="update school set sc_name=?,sc_address=?,sc_birth=?,sc_total=?,sc_area=? where sc_code=?";
        pst=null;
        try {
            pst=conn.prepareStatement(sql);
            pst.setString(1,school.getScName());
            pst.setString(2,school.getScAddress());
            pst.setTimestamp(3,new java.sql.Timestamp(school.getScBirth().getTime()));
            pst.setInt(4,school.getScTotal());
            pst.setDouble(5,school.getScArea());
            pst.setInt(6,school.getScCode());
            int i = pst.executeUpdate();
            return i;
        }catch (SQLException e){
            System.out.println("修改错误"+e);
        }finally {
            DBUtil.getClose(conn,pst,rs);
        }
        return 0;
    }
    //添加
    public int addSchool(School school){
        conn=DBUtil.getConn();
        String sql="insert into school values(null,?,?,?,?,?)";
        pst=null;
        try {
            pst=conn.prepareStatement(sql);
            pst.setString(1,school.getScName());
            pst.setString(2,school.getScAddress());
            pst.setTimestamp(3,new java.sql.Timestamp(school.getScBirth().getTime()));
            pst.setInt(4,school.getScTotal());
            pst.setDouble(5,school.getScArea());
            int i = pst.executeUpdate();
            return i;
        }catch (SQLException e){
            System.out.println("添加错误"+e);
        }finally {
            DBUtil.getClose(conn,pst,rs);
        }
        return 0;
    }
    //根据id删除
    public int deleteByCode(int scCode){
        conn=DBUtil.getConn();
        String sql="delete from school where sc_code="+scCode;
        pst=null;
        try {
            pst=conn.prepareStatement(sql);
            int i = pst.executeUpdate();
            return i;
        }catch (SQLException e){
            System.out.println("删除错误"+e);
        }finally {
            DBUtil.getClose(conn,pst,rs);
        }
        return 0;
    }
}

3.service类实现功能
4.servlet类获取前端数据,将前端数据string类型转换成需要的类型
将登录中保存的session写在增删改查的前面,判断session不为null才可以继续,为null则返回,保证不登陆不可以使用该功能

public class SchoolCrudServlet extends HttpServlet {
    SchoolService service=new SchoolService();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解码
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        //
        HttpSession session = req.getSession();
        Object loginuser = session.getAttribute("loginuser");
        if (loginuser==null){
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
            return;
        }
        //增删改查
        if (req.getServletPath().equals("/list.do")){

            List<School> schools = service.getSchools();
            req.setAttribute("schools",schools);
            RequestDispatcher rd = req.getRequestDispatcher("listSchool.jsp");
            rd.forward(req,resp);
        }else if (req.getServletPath().equals("/toUpdate.do")){
            String scCode = req.getParameter("scCode");
            if (scCode!=null){
                int s1 = Integer.parseInt(scCode);
                School school = service.getSchool(s1);
                req.setAttribute("school",school);
                RequestDispatcher rd = req.getRequestDispatcher("updateSchool.jsp");
                rd.forward(req,resp);
            }
        }else if (req.getServletPath().equals("/update.do")){
            update(req,resp);
        }else if (req.getServletPath().equals("/delete.do")){
            String scCode = req.getParameter("scCode");
            if (scCode==null){
                resp.sendRedirect(req.getContextPath()+"/list.do");
                return;
            }else {
                int i = Integer.parseInt(scCode);
                boolean b = service.deleteSchool(i);
                resp.sendRedirect(req.getContextPath()+"/list.do");
            }
        }else if (req.getServletPath().equals("/add.do")){
            add(req,resp);
        }
    }
    //增加
    private void add(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        //获取
        String scName = req.getParameter("scName");
        String scAddress = req.getParameter("scAddress");
        String scBirth = req.getParameter("scBirth");
        String scTotal = req.getParameter("scTotal");
        String scArea = req.getParameter("scArea");
        //转换
        Date scBirth1 = new Date();
        int scTotal1=-1;
        double scArea1=-1;
        if (scBirth!=null){
            try {
                scBirth1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(scBirth);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (scTotal!=null){
            scTotal1=Integer.parseInt(scTotal);
        }
        if (scArea!=null){
            scArea1=Double.parseDouble(scArea);
        }
        School school = new School();
        school.setScName(scName);
        school.setScAddress(scAddress);
        school.setScBirth(scBirth1);
        school.setScTotal(scTotal1);
        school.setScArea(scArea1);
        service.addSchool(school);
        resp.sendRedirect(req.getContextPath()+"/list.do");
    }
    //更新
    private void update(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        //获取
        String scCode=req.getParameter("scCode");
        String scName = req.getParameter("scName");
        String scAddress = req.getParameter("scAddress");
        String scBirth = req.getParameter("scBirth");
        String scTotal = req.getParameter("scTotal");
        String scArea = req.getParameter("scArea");
        //转换
        int scCode1=-1;
        Date scBirth1 = new Date();
        int scTotal1=-1;
        double scArea1=-1;
        if (scCode!=null){
            scCode1=Integer.parseInt(scCode);
        }
        if (scBirth!=null){
            try {
                scBirth1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(scBirth);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (scTotal!=null){
            scTotal1=Integer.parseInt(scTotal);
        }
        if (scArea!=null){
            scArea1=Double.parseDouble(scArea);
        }
        School school = new School();
        school.setScCode(scCode1);
        school.setScName(scName);
        school.setScAddress(scAddress);
        school.setScBirth(scBirth1);
        school.setScTotal(scTotal1);
        school.setScArea(scArea1);
        service.updateSchool(school);
        resp.sendRedirect(req.getContextPath()+"/list.do");
    }
}

配置路径

action.SchoolCrudServlet中配置路径,后+.do可以访问

<servlet>
        <servlet-name>school</servlet-name>
        <servlet-class>action.SchoolCrudServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>school</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值