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

一,数据库

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+"/";
%>




 
   
    
    My JSP 'login.jsp' starting page
    


   





 
  
 
   

   用户名:

   密码:

   验证码: style="width: 80px; height: 30px; border: 1px solid black;" /> 
换一张


   
   
   
   
   

 

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+"/";
%>




 
   
    
    My JSP 'index.jsp' starting page
    


   





 
  
 
    登录成功

 

三,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 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 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配置



  servlet-1
 
CodeServlet
    controller.CodeServlet
 

 
    This is the description of my J2EE component
    This is the display name of my J2EE component
    LoginServlet
    controller.LoginServlet
 



 
    CodeServlet
    /checkCode
 

 
    LoginServlet
    /LoginServlet
 


代码就这多,登录页面

用jsp+servlet+jdbc实现登录功能(体现mvc设计思想)_第1张图片

你可能感兴趣的:(java)