Javaweb的登录实现

Javaweb的登录实现

新建一个Javaweb项目
在这里插入图片描述
这是项目结构,比较简单

准备(我用的,当然其他的也可以):
IDE: Eclipse Mars Release (4.5.0)
jdk:1.8.0_171
Tomcat:v7.0
MySQL:5.7(mysql-connector-java-5.1.26)

一、建立数据库连接

连接
建立一个数据库连接类,包括驱动,数据库名称,用户名,密码

public class DBUtil {
	static   private String classDriver;
	static   private String url;
	static   private String username;
	static   private String password;
	static{
			classDriver="com.mysql.jdbc.Driver";
			url="jdbc:mysql://localhost:3306/db_name";   
			username="";
			password="";
			try{
				Class.forName(classDriver);
		}catch(ClassNotFoundException e){
			    e.printStackTrace();
		}
	}
		
		public static Connection getConnection() throws SQLException{                  //外部调用方法连接
			     Connection conn=DriverManager.getConnection(url, username, password);
			     return conn;
			
		}
数据库参数写在外部,统一调用
db.propertices
userName=
passWord=
classDriver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/syrinxsysorder?useUnicode=true&characterEncoding=UTF-8

public class DBUtil {
	static   private String classDriver;
	static   private String url;
	static   private String userName;
	static   private String passWord;
    static {
        try {        
            ClassLoader classLoader = DBUtil.class.getClassLoader();    
            InputStream is = classLoader.getResourceAsStream("jdbc.properties"); //加载配置文件,字节输入流
            Properties props = new Properties();
            props.load(is);读取配置文件
  
            classDriver = props.getProperty("classDriver");
            url = props.getProperty("url");
            userName = props.getProperty("userName");
            passWord = props.getProperty("passWord");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() {
        Connection conn = null;
            try {
				Class.forName(classDriver);
				conn = DriverManager.getConnection(url, userName, passWord);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        return conn;
    }
}

二、使用变量类
在这里插入图片描述
建立一个user类,私有化变量,变量值设置

public class User {
	private int id;
	private String name;
	private String phone;
	private String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

}

构造一个抽象类 userdao,声明抽象方法

public interface UserDao {
	    public void insert(User user) throws Exception;
	    public void update(User user) throws Exception;
	    public void delete(User user) throws Exception;
	    public boolean queryByNP(User user) throws Exception;  //这里只用了这个方法,传入user,返回一个Boolean值
	    public List<User> queryAll() throws Exception;
	
}

三、实现抽象类
在这里插入图片描述

public class UserDaoImpl implements UserDao {
//实现具体的抽象方法
	DBUtil jdbc = new DBUtil();
	Connection conn = null;
	PreparedStatement ps = null;

	
	@Override
	public boolean queryByNP(User user) throws Exception {
		// TODO Auto-generated method stub
		boolean flag=false;
		String sql = "select * from sys_user where phone=? and password=?";
		conn = jdbc.getConnection(); // 建立连接
		if (conn != null) {
			System.out.println("DB connect succeed!");
			// System.out.println(user.getName());    这里查看输入的用户名和密码
			// System.out.println(user.getPassword());
		}
		ps = conn.prepareStatement(sql);// 把sql交给prepareStatement进行处理
		ps.setString(1, user.getPhone());
		ps.setString(2, user.getPassword());

		// flag=ps.execute();   //execute() 判断SQL是否执行,返回Boolean值
		// if(flag){
		// System.out.println("执行成功");
		// }
		//
		// else{
		// System.out.println("执行失败");
		// }
		ResultSet rs = ps.executeQuery();  //执行sql,返回一个结果集
		if (rs.next()) {
			flag=true;  //如果结果集不为null
		}
		 //关闭连接
		rs.close();
		ps.close();
		conn.close();  
		return flag;
  }
	}

四、新建一个servlet,用来实现前端和后台代码的关联

在这里插入图片描述
用eclipse快捷新建一个servlet类(当然是用其他的IDE也可以)

package com.syrinx.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
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 com.syrinx.daoimpl.UserDaoImpl;
import com.syrinx.user.User;
import com.syrinx.user.UserDao;
/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	   在jsp中,method的方式决定了,调用的是servlet中的doGet还是doPost
	 * @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");
	        response.setContentType("text/html;charset=UTF-8");
	        this.login(request,response);  //调用login方法
	        
	}
	
	protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		// TODO Auto-generated method stub
	
		String name=request.getParameter("name");         //得到页面中输入框的值
		String password=request.getParameter("password");
		boolean flag=false;           //定义一个初始化为false的Boolean,判断是否登录成功
		User user=new User();    //实例化user对象,因为dao中需要传入user
		UserDao ud=new UserDaoImpl();      //构造对象
		user.setPhone(name);  //把页面得到值给一个user对象
		user.setPassword(password);    
		try {
			flag=ud.queryByNP(user);   //调用方法,传递user值,返回一个Boolean值
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(flag){
			System.out.println("登录成功");
			response.sendRedirect("../managedemo/index.jsp");   //登录成功后跳转
		}
		else{
			System.out.println("登录失败");
		}		
	} 
}

当需要传值的是:

//jsp//
           <form action="../servlet/OrderServlet" method="post"  >
			<label>
				<input type="text" id="username" class="txt_input txt_input2" name="search_input" placeholder="请输入您的手机号" onkeyup="this.value=this.value.replace(/^ +| +$/g,'')">
			</label>
			<div class="rem_sub">
				<label>
					<input type="submit" class="sub_button" name="button" id="button" value="查&nbsp;&nbsp;&nbsp;询" style="opacity: 0.7;" >
				</label>
			</div>
			</form>
			
//servlet//
String order_no = request.getParameter("order_no");   //得到jsp中传入的值
		OrderDao ud = new OrderDaoImpl();
		List<OrderUser> list = new ArrayList<OrderUser>(); 构造一个bean的集合
		try {
			list = ud.orderShow(order_no);  //返回list集合
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (list != null && list.size() > 0) {
			request.setAttribute("list", list);
			String path = request.getContextPath();
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ path + "/showorder/";
			request.setAttribute("path", basePath);
			RequestDispatcher disp = request.getRequestDispatcher("../showorder/member_show.jsp");
			disp.forward(request, response); //传值
			
		}
	
	}
//jsp//
<%
		List<OrderUser> list = (List<OrderUser>) request.getAttribute("list");
	    for (OrderUser order : list) {
									%>								


五、新建login.jsp,实现登录窗口
在这里插入图片描述

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8">
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link href="static/h-ui/css/H-ui.min.css" rel="stylesheet" type="text/css" />
<link href="static/h-ui.admin/css/H-ui.login.css" rel="stylesheet" type="text/css" />
<link href="static/h-ui.admin/css/style.css" rel="stylesheet" type="text/css" />
<link href="lib/Hui-iconfont/1.0.8/iconfont.css" rel="stylesheet" type="text/css" />

<title>后台登录</title>

</head>
<body>
<input type="hidden" id="TenantId" name="TenantId" value="" />
<div class="header"></div>
<div class="loginWraper">
  <div id="loginform" class="loginBox">
  <!- 提交方式为post,提交的时候自动执行servlet中doPost方法-,action为servlet类的路径。这里servlet/LoginServlet,是web.xml中映射的路径>
    <form class="form form-horizontal"  action="../servlet/LoginServlet"  method="post">
     
      <div class="row cl">
        <label class="form-label col-xs-3"><i class="Hui-iconfont">&#xe60d;</i></label>
        <div class="formControls col-xs-8">
          <input id="" name="name" type="text" placeholder="账户" class="input-text size-L">
        </div>
      </div>
      
      <div class="row cl">
        <label class="form-label col-xs-3"><i class="Hui-iconfont">&#xe60e;</i></label>
        <div class="formControls col-xs-8">
          <input id="" name="password" type="password" placeholder="密码" class="input-text size-L">
        </div>
      </div>
      <div class="row cl">
        <div class="formControls col-xs-8 col-xs-offset-3">
          <input name="" type="submit" class="btn btn-success radius size-L" value="&nbsp;登&nbsp;&nbsp;&nbsp;&nbsp;录&nbsp;">
          <input name="" type="reset" class="btn btn-default radius size-L" value="&nbsp;取&nbsp;&nbsp;&nbsp;&nbsp;消&nbsp;">
        </div>
      </div>
   
    </form>
  </div>
</div>
<div class="footer">Copyright 你的公司名称 by H-ui</div>
<script type="text/javascript" src="lib/jquery/1.9.1/jquery.min.js"></script> 
<script type="text/javascript" src="static/h-ui/js/H-ui.min.js"></script>
</body>
</html>

六、在web.xml中添加jsp与servlet的联系
在这里插入图片描述

  <servlet>
    <servlet-name>LoginServlet</servlet-name> <!-- 自由设置servlet名称 -->
    <servlet-class>com.syrinx.servlet.LoginServlet</servlet-class> <!-- servlet实际路径 -->
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name><!-- 与上面保存一致 -->
    <url-pattern>/servlet/LoginServlet</url-pattern>  <!-- 路径映射 -->
  </servlet-mapping>

七、执行
1、执行的时候需要把jdbc驱动包放到Tomcat中lib下面,否则执行报错,
2、如果路径不对,会报错404(注意web.xml中的映射路径)
在这里插入图片描述
有问题欢迎随时咨询

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值