登录  /  注册

MVC模式实现登录以及增删改查之登录

高洛峰
发布: 2016-11-04 17:15:13
原创
3536人浏览过

我在这里用的不是maven项目,用的一般的web项目,所以需要用到的架包需要自己去下载添加,在项目中,一定注意环境的配置,我用的是jre1.7

 1  新建项目

1.png

2  建立好MVC的管理包,导入对应的架包servlet

1.png

3 建立好与数据库对应的实体类 teacher.java

public class Teacher {
            private  int  tid;
            private  String tname;
            private  String tpsw;
            public int getTid() {
                return tid;
            }
            public void setTid(int tid) {
                this.tid = tid;
            }
            public String getTname() {
                return tname;
            }
            public void setTname(String tname) {
                this.tname = tname;
            }
            public String getTpsw() {
                return tpsw;
            }
            public void setTpsw(String tpsw) {
                this.tpsw = tpsw;
            }
            public Teacher(String tname, String tpsw) {
                super();
                this.tname = tname;
                this.tpsw = tpsw;
            }
            public Teacher(int tid, String tname, String tpsw) {
                super();
                this.tid = tid;
                this.tname = tname;
                this.tpsw = tpsw;
            }
            public Teacher() {
                super();
            }
}
登录后复制

4 在WebContent新建login.jsp文件编写登陆框

1

2

3 用户名:

4 密码:

5

6


5 配置web.xml文件对应表单请求login

1.png

web.xml文件

注意:配置时要在之前,否则会报错

<!-- 提交登录请求 -->
  <servlet>
    <servlet-name>login</servlet-name>
    <servlet-class>com.zr.controller.LoginController</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>login</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
登录后复制

6 编写对应的请求实体类LoginController.java:继承HttpServlet重写doget(),dopost()方法,根据method请求的不同调用doget或者dopost方法

LoginController.java

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.zr.model.Teacher;
import com.zr.service.valiDateService;
import com.zr.serviceIm.valiDateServiceImpl;
public class LoginController   extends  HttpServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
         throws ServletException, IOException {
                super.doPost(req, resp);
            }
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {
           //获取前台form表单的input输入框
           String tname=req.getParameter("tname");
           String tpsw=req.getParameter("tpsw");
           Teacher tc=new Teacher();
           tc.setTname(tname);
           tc.setTpsw(tpsw);
           valiDateService vds=new valiDateServiceImpl();
          Teacher t=    vds.valiDateTeacher(tc);
        HttpSession  session=req.getSession();
        session.setAttribute("teacher", t);
        if (t!=null) {
            //返回的不是空值,重定向到登录成功界面
            req.getRequestDispatcher("main.jsp").forward(req, resp);
        } else {
            //返回空值,请求转发到登录界面
            resp.sendRedirect("login.jsp");
        }      
            }
}
登录后复制

7 从后台dao层写到control层

public interface TeacherDao {
    
    /**
     * 验证老师是否存在
     * @param tc
     * @return
     */
    public Teacher validateTeacher(Teacher tc);
}
登录后复制

8.1 编写封装类建立与数据库的连接JDBCUtil.java

package JDBCUtil;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

    public class JDBCUtil {
         //1.数据库地址  (根据不同的数据标准是不一样)
          private  final  static String DBURL = "jdbc:mysql://localhost:3306/student_crm?useUnicode=true&characterEncoding=UTF8";
          //2.设置用户和密码
          private  final  static String  USERNAME = "root";
          private  final  static String  PASSWORD = "root";
          //3.设置驱动名称 (根据不同的数据标准是不一样)
          private  final  static String  DBDRIVER = "com.mysql.jdbc.Driver";
          /**
           * 获取数据库连接
           * @return  返回数据库连接
           */
          public  static  Connection  getConnection(){
              Connection  con = null;
              try {
                Class.forName(DBDRIVER);
                con  =  DriverManager.getConnection(DBURL, USERNAME, PASSWORD);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
              return  con;    
          }
//关闭连接 
          public static void  closeJDBC(Statement st,Connection  con) throws SQLException{
                if(st!=null){
                    st.close();
                }
                if(con!=null){
                    con.close();
                }
          }

}
登录后复制

8.2 dao层的实现

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.zr.dao.TeacherDao;
import com.zr.model.Teacher;
import JDBCUtil.JDBCUtil;
public class TeacherDaoImpl implements TeacherDao{
    /**
     * 输入老师的对象,返回老师对象
     * @param args
     */
    public Teacher validateTeacher(Teacher tc) {
        Teacher teacher=new Teacher();
        //sql语句
        StringBuffer sql=new StringBuffer("select * from teacher where tname=? and tpsw=?");
        //获取数据库连接
        Connection con=JDBCUtil.getConnection();
        try {
            PreparedStatement  pst=con.prepareStatement(sql.toString());
            pst.setString(1, tc.getTname());
            pst.setString(2, tc.getTpsw());
            //返回一个结果集
            ResultSet rs=pst.executeQuery();
            if (rs.next()) {
            //把结果集里面的数据放入对应的teacher对象
                teacher=new Teacher(rs.getInt("tid"),rs.getString("tname"),rs.getString("tpsw"));
            } 
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return teacher;
    }
}
登录后复制

9 Service层

public interface valiDateService {
/**
 * @param tc
 * @return 老师对象
 * 根据用户输入值验证老师是否存在
 */
    public Teacher valiDateTeacher(Teacher tc);

}
登录后复制

10 Service层实现ServiceImpl.java

import com.zr.dao.TeacherDao;
import com.zr.daoIm.TeacherDaoImpl;
import com.zr.model.Teacher;
import com.zr.service.valiDateService;
public class valiDateServiceImpl implements valiDateService{
    public Teacher valiDateTeacher(Teacher tc) {
        //父类的引用指向子类的对象,父类可以直接调用子类的方法
        TeacherDao teacherDao=new TeacherDaoImpl();
        //调用dao层的方法验证存在
        Teacher teacher=teacherDao.validateTeacher(tc);
        return teacher;
    }
}
登录后复制

11 com.zr.controller层

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.zr.model.Teacher;
import com.zr.service.valiDateService;
import com.zr.serviceIm.valiDateServiceImpl;
public class LoginController extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取前台form表单的input输入框
        String tname = req.getParameter("tname");
        String tpsw = req.getParameter("tpsw");
        // 将前台对象放入tc对象,作为输入参数
        Teacher tc = new Teacher();
        tc.setTname(tname);
        tc.setTpsw(tpsw);
        // 调用Service层的方法传入tc对象,并用t接收返回结果
        valiDateService vds = new valiDateServiceImpl();
        Teacher t = vds.valiDateTeacher(tc);
        // 获取JSP作用域session,将老师t对象放入session
        HttpSession session = req.getSession();
        int a = t.getTid();//最好根据返回的老师的id进行判断
        if (a != 0) {
            // 返回的有id,重定向到登录成功界面
            req.getRequestDispatcher("main.jsp").forward(req, resp);
            session.setAttribute("teacher", t);
        } else {
            // 返回空值,请求转发到登录界面
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    }
}
登录后复制
智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号