五、Servlet链接数据库 建数据库的表
写java文件
Login
/**
* @(#)Login.java * *
* @author
* @version 1.00 2017/2/10 */
//登陆界面
package com.tsinghua; import javax.servlet.http.*; import java.io.*;
public class Login extends HttpServlet{
public Login() { }
//处理get请求
public void doGet(HttpServletRequest req,HttpServletResponse res){ //业务逻辑 try {
//中文乱码解决方法
res.setContentType(\
PrintWriter pw = res.getWriter(); //返回登陆界面 pw.println(\ pw.println(\
pw.println(\登陆界面\
pw.println(\
pw.println(\用户名:
\ pw.println(\密码:
\ pw.println(\ pw.println(\ pw.println(\ pw.println(\ }
catch (Exception ex){ ex.printStackTrace(); } }
public void doPost(HttpServletRequest req,HttpServletResponse res){ this.doGet(req,res); } }
LoginCl
/**
* @(#)Login.java * *
* @author
* @version 1.00 2017/2/10 */
//验证(登陆处理) package com.tsinghua; import javax.servlet.http.*; import java.io.*; import java.sql.*;
public class LoginCl extends HttpServlet{
public LoginCl() { }
//处理get请求
public void doGet(HttpServletRequest req,HttpServletResponse res){
//业务逻辑
Connection ct=null; Statement sm=null; ResultSet rs=null; try { //接受用户名和密码 String u=req.getParameter(\ String p=req.getParameter(\ //链接数据库,加载驱动 Class.forName(\ //得到链接 ct=DriverManager.getConnection(\/xcdb?useUnicode=true&characterEncoding=gbk\ //创建Statement sm=ct.createStatement(); rs=sm.executeQuery(\
//验证 if(rs.next()){ //合法
//将验证成功的信息,写入session //1表示得到session
HttpSession hs=req.getSession(true); //修改session 的存在时间,设为20秒 hs.setMaxInactiveInterval(20); //把信息放session
hs.setAttribute(\
//跳转(welcome)
res.sendRedirect(\ }else{
//不合法
//跳转(回原界面)
res.sendRedirect(\写url } }
catch (Exception ex){ ex.printStackTrace(); }finally{ try{ if(rs!=null){ rs.close(); } if(sm!=null){ sm.close(); } if(ct!=null){ ct.close(); } }
catch(Exception ex){ ex.printStackTrace(); } } }
public void doPost(HttpServletRequest req,HttpServletResponse res){ this.doGet(req,res); } }
Welcome
/**
* @(#)Welcome.java * *
* @author
* @version 1.00 2017/2/10 */
//欢迎界面
package com.tsinghua; import javax.servlet.http.*; import java.io.*;
public class Welcome extends HttpServlet{
public Welcome() { }
//处理get请求
public void doGet(HttpServletRequest req,HttpServletResponse res){
//业务逻辑 try { //得到session
HttpSession hs=req.getSession(true); String val=(String)hs.getAttribute(\
//判断是否非法登陆 if(val==null){ try{ //非法登陆 res.sendRedirect(\ }catch (Exception ex){ ex.printStackTrace(); } } else{ //得到从Logincl传递的用户名 String un=req.getParameter(\ //得到从LoginCl中传递的密码
String up=req.getParameter(\ //输出weclcome PrintWriter pw=res.getWriter(); pw.println(\} }
catch (Exception ex){ ex.printStackTrace(); } }
public void doPost(HttpServletRequest req,HttpServletResponse res){ this.doGet(req,res); } }
放jar包
将mysql-connector-java-5.1.39-bin放到mywebsite里的WEB-INF下的lib文件夹里
结果展示:
Sql注入漏洞
当密码输入bnb' or 1='1类型时无论什么用户都可以登陆