学习篇--(jsp+servlet+mysql) 登录界面 【前后台交互学习笔记】

 

经典的样例,自己手打一边,学习一下!

 

UserBean,代码如下:

package com.szx.jnmc;

    public class User {

    private String username;
    private String userpass;
    private int role;
    private int lognum;
    private  String regtime;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getUserpass() {
        return userpass;
    }
    public void setUserpass(String userpass) {
        this.userpass = userpass;
    }
    public int getRole() {
        return role;
    }
    public void setRole(int role) {
        this.role = role;
    }

    public int getLognum() {
        return lognum;
    }
    public void setLognum(int lognum) {
        this.lognum = lognum;
    }
    public String getRegtime() {
        return regtime;
    }
    public void setRegtime(String regtime) {
        this.regtime = regtime;
    }

}

================================================================================================

对user进行数据的封装。

下面再写一个数据库连接类DBOper 这个类具有连接数据库以及增删改(executeUpdate)查(executeQuery)的功能,以便于AddUserServlet的调用

package com.szx.jnmc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBOper {

    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    //打开连接
    public Connection getConn(String server,String dbname,String dbuser,String dbpwd){      
        String DRIVER = "com.mysql.jdbc.Driver";
        String URL = "jdbc:mysql://"+server+":3306/"+dbname+"?user="+dbuser+"&password="+dbpwd+"&useUnicode=true&characterEncoding=utf8";
        try{
            Class.forName(DRIVER);  
            conn = DriverManager.getConnection(URL);
        }catch(Exception e){
            e.printStackTrace();
        }
        return conn;
    }
    //关闭连接
    public void closeAll(){
        try{
            if(rs != null){
                rs.close();
            }
        }catch(SQLException e){
            e.printStackTrace();
        }finally{
            try{
                if(ps != null){
                    ps.close();
                }
            }catch(SQLException e){
                e.printStackTrace();
            }finally{
            try{
                if(conn != null){
                    conn.close();
                }
            }catch (SQLException e){
                e.printStackTrace();
            }
            }
        }

    }
    //执行sql语句,可以进行查询
    public ResultSet executeQuery(String preparedSql,String []param){
        try{
            ps = conn.prepareStatement(preparedSql);
            if(param != null){
                for (int i = 0; i < param.length; i++) {
                    ps.setString(i + 1, param[i]);
                }
            }
            rs = ps.executeQuery();
        }catch(SQLException e){
            e.printStackTrace();
        }       
        return rs;

    }
    //执行sql语句,增加,修改,删除
    public int executeUpdate(String preparedSql,String[]param){
        int num = 0;
        try{
            ps = conn.prepareStatement(preparedSql);
            if(ps != null){
                for (int i = 0; i < param.length; i++) {
                    ps.setString(i + 1, param[i]);
                }
            }
            num = ps.executeUpdate();
        }catch(SQLException e){
            e.printStackTrace();
        }
        return num;
    }
}

==========================================================================

数据库连接类写完之后,继续写一个UserDao,这个类主要功能是对用户进行增删改查 代码如下:

package com.szx.jnmc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao extends DBOper{
    //获取用户列表
    public List getUser(){
        ListuserList = new ArrayList();
        User user = new User();
        String sql = "SELECT * FROM tb_user";
        try{
            ResultSet rs = this.executeQuery(sql,null);
            while(rs.next()){
                user.setUsername(rs.getString("username"));
                user.setUserpass(rs.getString("userpass"));
                user.setLognum(rs.getInt("lognum"));
                user.setRegtime(rs.getString("regtime"));
                user.setRole(rs.getInt("role"));
                userList.add(user);
            }

        }catch(SQLException e){
            e.printStackTrace();
        }finally{
            this.closeAll();
        }
        return userList;
    }
    //根据用户名获取用户
    public User getUserByName(String name){
        User user = null;
        String sql = "SELECT * FROM tb_user WHERE username = ?";
        try{            
            ResultSet rs = this.executeQuery(sql, new String[]{name});
            if(rs.next()){
                user = new User();
                user.setUsername(rs.getString("username"));
                user.setUserpass(rs.getString("userpass"));
                user.setRole(rs.getInt("role"));
                user.setLognum(rs.getInt("lognum"));
                user.setRegtime(rs.getString("regtime"));
            }
        }catch(SQLException e){
            e.printStackTrace();
        }finally{
            this.closeAll();
        }
        return user;
    }
    //修改用户信息
    public boolean editUser(User user){
        boolean r = false;
        String sql = "UPDATE tb_user SET userpass = ?,role = ?,regtime = ?,lognum = ? WHERE username = ?";
        try{
            int num = this.executeUpdate(sql, new String[]{user.getUserpass(),""+user.getRole(),""+user.getLognum(),user.getRegtime(),user.getUsername()});
            if(num > 0){
                r = true;
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            this.closeAll();
        }
        return r;

    }
    //添加用户
    public boolean addUser(User user){
        boolean r = false;
        String sql = "INSERT INTO tb_user(username,userpass,role,regtime)VALUES(?,?,?,?) ";
        try{
            int num = this.executeUpdate(sql,new String[]{user.getUsername(),user.getUserpass(),""+user.getRole(),user.getRegtime()});
            if(num > 0){
                r = true;
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            this.closeAll();
        }
        return r;
    }
    //删除指定用户
    public boolean delUser(String name){
        boolean r = false;
        String sql = "DELETE FROM tb_user WHERE username = ?";
        try{
            int num = this.executeUpdate(sql,new String[]{name});
            if(num > 0){
                r = true;
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            this.closeAll();
        }
        return r;
    }
}

===============================================================================================

注册部分的jsp,addUser.jsp用来接收用户的输入。抛开各种样式,直接用最原始的样式呈现吧,代码如下:

 <%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
    
    
    
    
    添加用户页面
    
    
    
用户名: 密码:

===============================================

注意页面的字符编码设置统一为GBK(以GBK为例,如果自己写的话最好用UTF-8)

下面写我们的AddUserServlet,不多说,直接贴代码:

  package com.szx.jnmc;

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    /**
     * Servlet implementation class AddUserServlet
     */
    @WebServlet("/AddUserServlet")
    public class AddUserServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddUserServlet() {
        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
        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("GBK");
        response.setContentType("text/html;charset = GBK");
        String username = request.getParameter("username");
        String userpass = request.getParameter("userpass");
        //String role = request.getParameter("role");
        Date curTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String regtime = sdf.format(curTime);
        PrintWriter out = response.getWriter();
        ServletContext ctx = this.getServletContext();
        String server = ctx.getInitParameter("server");
        String dbname = ctx.getInitParameter("dbname");
        String dbuser = ctx.getInitParameter("dbuser");
        String dbpwd = ctx.getInitParameter("dbpwd");
        User user = new User();
        user.setUsername(username);
        user.setUserpass(userpass);
        user.setRegtime(regtime);
        //user.setRole(Integer.parseInt(role));
        UserDao dao = new UserDao();
        dao.getConn(server, dbname, dbuser, dbpwd);
        if(dao.addUser(user)){
            out.print("注册成功!");
        }
        else{
            out.print("注册失败!");
        }


    }

    }

===============================================================================================

接下来我们写登陆部分,login.jsp代码如下:

<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>




登陆页面


用户名: 密码:

================================================================================================

LoginServlet代码如下:

package com.szx.jnmc;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        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
        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("GBK");
        response.setContentType("text/html;charset = GBK");
        PrintWriter out = response.getWriter();
        String username = request.getParameter("username");
        String userpass = request.getParameter("userpass");
        ServletContext ctx = request.getServletContext();
        String server = ctx.getInitParameter("server");
        String dbname = ctx.getInitParameter("dbname");
        String dbuser = ctx.getInitParameter("dbuser");
        String dbpwd = ctx.getInitParameter("dbpwd");       
        DBOper db = new DBOper();
        db.getConn(server, dbname, dbuser, dbpwd);
        String sql = "SELECT username,userpass,role FROM tb_user WHERE username = ? AND userpass = ?";
        ResultSet rs = db.executeQuery(sql,new String[]{username,userpass});
        try {
            if(rs != null && rs.next()){
                HttpSession session = request.getSession();
                session.setAttribute("username",username);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String logtime = sdf.format(new Date()); 
                session.setAttribute("logtime",logtime);
                Cookie cookie = new Cookie("username",username);
                cookie.setMaxAge(60*60*24*30);
                response.addCookie(cookie);
                RequestDispatcher dispatcher = request.getRequestDispatcher("MainServlet");
                dispatcher.forward(request,response);
            }else{
                out.print("登录失败");
                out.print("
重新登陆"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void init()throws ServletException { } }

==========================================================================================

LoginServlet里的MianServlet用来显示登陆成功的信息,登陆失败则跳转到login.jsp重新登陆,MainServlet的代码如下:

package com.szx.jnmc;

import java.io.IOException;
import java.io.PrintWriter;

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 javax.servlet.http.HttpSession;

/**
 * Servlet implementation class MainServlet
 */
@WebServlet("/MainServlet")
public class MainServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MainServlet() {
        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
        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("GBK");
        response.setContentType("text/html;charaset = GBK");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String username = (String)session.getAttribute("username");
        String logtime = (String)session.getAttribute("logtime");
        out.println("登录名:"+username+"    登陆时间:"+logtime);
        out.println("欢迎"+username);
    }

}

===============================================================================================

到此我们还有最重要的一步,就是在web.xml里配置我们的项目,web.xml代码如下:



  20170512
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
    server
    localhost
  
  
    dbname
    A20170512
  
  
    dbuser
    root
  
  
    dbpwd
    123456
  
  
    AddUserServlet
    AddUSerServlet
    com.szx.jnmc.AddUserServlet
  
   
  LoginServlet
  LoginServlet
  com.szx.jnmc.LoginServlet
  

转载于:https://blog.csdn.net/ITcreater000/article/details/71759744

 

 

 

你可能感兴趣的:(JavaEE,(后端框架+基础知识))