您的位置:首页 > Web前端 > JavaScript

用jsp+servlet+jdbc实现登录功能(体现mvc设计思想)

2017-09-09 13:19 761 查看

一,数据库

mysql数据库
创建表
CREATE TABLE `user` (

  `id` int(20) NOT NULL AUTO_INCREMENT,

  `name` varchar(40) DEFAULT NULL,

  `psw` varchar(40) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

插入一条数据
INSERT INTO `user` VALUES ('1', 'asd', '123');

二,前端界面(view视图层)

登录页面

login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

    

    <title>My JSP 'login.jsp' starting page</title>

    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

  </head>

  

  <body>

   <form action="LoginServlet" method="post">

   用户名:<input type="text" name="name"><br>

   密码:<input type="password" name="psw"><br>

   验证码:<input type="text" name="yzm"><img src="checkCode" alt="" id="codeImg"

style="width: 80px; height: 30px; border: 1px solid black;" /> 

<a href="javascript:;" onclick="document.getElementById('codeImg').src = 'checkCode?'+(new Date()).getTime()">换一张</a>

<span id="codemsg" style="color: red; font-size: 20px;"></span><br>

   

   <input type="submit" value="登录">

   

   

   </form>

  </body>

</html>

seccess.jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

    

    <title>My JSP 'index.jsp' starting page</title>

    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

  </head>

  

  <body>

    登录成功<br>

  </body>

</html>

三,servlet(controller层)

画出验证码的servlet
package controller;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.io.IOException;

import java.io.OutputStream;

import java.util.Random;

import javax.imageio.ImageIO;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class CodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String codes="0123456789";

BufferedImage img=new BufferedImage(80,30,BufferedImage.TYPE_3BYTE_BGR);
Graphics g=img.getGraphics();
//填充图片
g.setColor(new Color(255,255,255));
g.fillRect(0, 0, 80, 30);
//画入五个随机数
Random rm=new Random();
StringBuffer sb=new StringBuffer();
for(int i=0;i<5;i++){
int index=rm.nextInt(codes.length());
char code=codes.charAt(index);
g.setColor(new Color(rm.nextInt(256),rm.nextInt(256),rm.nextInt(256)));
g.setFont(new Font("宋体", Font.BOLD, 25));
g.drawString(code+"", 2+15*i, 22);
sb.append(code);
}

//画干扰线
for(int i=0;i<10;i++){
g.setColor(new Color(rm.nextInt(256),rm.nextInt(256),rm.nextInt(256)));
g.drawLine(rm.nextInt(100), rm.nextInt(50), rm.nextInt(100), rm.nextInt(50));
}

//将验证码图片回写给浏览器
response.setContentType("image/jpeg;charset=utf-8");
OutputStream out=response.getOutputStream();
ImageIO.write(img, "jpeg", out);

//将随机字符串保存在session中
request.getSession().setAttribute("code", sb.toString());
}

}

LoginServlet.java

接收前台表单的数据
package controller;

import java.io.IOException;

import java.io.PrintWriter;

import javax.jms.Session;

import javax.mail.SendFailedException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import vo.User;

import dao.UserDao;

public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

          String name=request.getParameter("name");

          String psw=request.getParameter("psw");

          String yzm=request.getParameter("yzm");

         String yzm2=(String)request.getSession().getAttribute("code");

         System.out.println(yzm2);
UserDao us=new UserDao();

User u=us.login(name, psw);

System.out.println(u);

if(yzm!=yzm2){
if(u==null){
request.getRequestDispatcher("/login.jsp").forward(request,response);
}else{
request.getRequestDispatcher("/index.jsp").forward(request,response);

}

}
}

}

jdbc连接数据库

package util;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

public class DbOperation {
protected Connection conn;
protected PreparedStatement ps;
protected ResultSet rs;
private final String uname="root";
private final String psw="root";
//获取数据库链接
public void getConn(){

try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//获取链接
conn = DriverManager.getConnection(
"jdbc:mysql:///test",uname,psw);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//关闭
public void closeAll(){
try {
if(conn!=null){
conn.close();
}
if(ps!=null){
ps.close();
}
if(rs!=null){
rs.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

//更新  Object... 会把传过来的任意个object类型的变量封装成一个数组
public void extUpdate(String sql, Object... obj){
try {
ps=conn.prepareStatement(sql);
for(int i=0;i<obj.length;i++){
ps.setObject(i+1, obj[i]);
}
ps.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//查询
public void extQuery(String sql, Object... obj){
try {
ps=conn.prepareStatement(sql);
for(int i=0;i<obj.length;i++){
ps.setObject(i+1, obj[i]);
}
rs=ps.executeQuery();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

创建dao方法
package dao;

import java.sql.SQLException;

import util.DbOperation;

import vo.User;

public class UserDao extends DbOperation{

  public User login(String name,String psw){
 getConn();
 String sql="select * from user where name=? and psw=?";
 extQuery(sql, name,psw);
 User u=null;
 try {
if(rs.next()){
u=new User();
u.setId(rs.getInt("id")); 
u.setName(rs.getString("name"));
u.setPsw(rs.getString("psw"));
 }
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 closeAll();
 return u;

  }

}

封装类

package vo;

public class User {
private int id;

  private String name;

  private String psw;

public String getName() {
return name;

}

public void setName(String name) {
this.name = name;

}

public String getPsw() {
return psw;

}

public void setPsw(String psw) {
this.psw = psw;

}

public int getId() {
return id;

}

public void setId(int id) {
this.id = id;

}  

}

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

  <display-name>servlet-1</display-name>

  <servlet>

<servlet-name>CodeServlet</servlet-name>

    <servlet-class>controller.CodeServlet</servlet-class>

  </servlet>

  <servlet>

    <description>This is the description of my J2EE component</description>

    <display-name>This is the display name of my J2EE component</display-name>

    <servlet-name>LoginServlet</servlet-name>

    <servlet-class>controller.LoginServlet</servlet-class>

  </servlet>

  <servlet-mapping>

    <servlet-name>CodeServlet</servlet-name>

    <url-pattern>/checkCode</url-pattern>

  </servlet-mapping>

  <servlet-mapping>

    <servlet-name>LoginServlet</servlet-name>

    <url-pattern>/LoginServlet</url-pattern>

  </servlet-mapping>

</web-app>

代码就这多,登录页面

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mvc servlet jsp jdbc