ServletJsp20151021学习笔记
entity.User.java
package entity; public class User { private int id; private String username; private String pwd; private String name; private String gender; public User() { // TODO Auto-generated constructor stub } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public User(int id, String username, String pwd, String name, String gender) { super(); this.id = id; this.username = username; this.pwd = pwd; this.name = name; this.gender = gender; } @Override public String toString() { return "user [id=" + id + ", username=" + username + ", pwd=" + pwd + ", name=" + name + ", gender=" + gender + "]"; } }
dao.DBUtil.java
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBUtil { public static Connection getConnection() throws Exception{ Connection conn=null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager. getConnection( "jdbc:mysql://localhost:3306/leemamas?useUnicode=true&characterEncoding=utf8", "root", ""); } catch (Exception e) { e.printStackTrace(); throw e; } return conn; } public static void closeConnection(Connection conn)throws Exception{ if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw e; } } } public static void main(String[] args) throws Exception { System.out.println(getConnection()); } }
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import entity.User; public class UserDAO { public User findByUsername(String username) throws Exception{ User user=null; Connection conn=null; PreparedStatement stmt=null; ResultSet rs=null; try { conn=DBUtil.getConnection(); String sql="select * from user where username=?"; stmt=conn.prepareStatement(sql); stmt.setString(1, username); rs=stmt.executeQuery(); if(rs.next()){ user=new User(); user.setId(rs.getInt("id")); user.setUsername(username); user.setPwd(rs.getString("pwd")); user.setName(rs.getString("name")); user.setGender(rs.getString("gender")); } } catch (Exception e) { e.printStackTrace(); throw e; }finally{ DBUtil.closeConnection(conn); } return user; } }
web.ValidateCode
package web; 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.io.PrintWriter; 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; import javax.servlet.http.HttpSession; import com.sun.org.apache.commons.digester.rss.Image; public class ValidateCode extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //画布 BufferedImage image=new BufferedImage(90,30,BufferedImage.TYPE_INT_RGB); //画笔 Graphics g=image.getGraphics(); //设置颜色 g.setColor(new Color(255,255,255)); //设置背景 g.fillRect(0, 0, 90, 30); //重射画笔颜色 Random ran=new Random(); g.setColor( new Color(ran.nextInt(255),ran.nextInt(255),ran.nextInt(255))); //随机数/./.. String num=getNumber(5); //绑定session HttpSession session=request.getSession(); session.setAttribute("num", num); g.setFont(new Font(null,Font.BOLD,24)); //验证码转化图片 g.drawString(num, 5, 25); //干扰线 for(int i=0;i<8;i++){ g.setColor( new Color(ran.nextInt(255),ran.nextInt(255),ran.nextInt(255))); g.drawLine(ran.nextInt(90),ran.nextInt(30),ran.nextInt(90), ran.nextInt(30)); } //服务器返回数据类型 response.setContentType("image/jpeg"); //输出流 OutputStream os=response.getOutputStream(); ImageIO.write(image, "jpeg", os); os.close(); } public String getNumber(int size){ String num=""; String str="ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; Random ran=new Random(); for(int i=0;i<size;i++){ num+=str.charAt(ran.nextInt(str.length())); } return num; } }
package web; import java.io.IOException; import javax.jms.Session; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dao.UserDAO; import entity.User; public class ActionServlet extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //字符控制 String uri = request.getRequestURI(); String action =uri.substring(uri.lastIndexOf("/")+1,uri.lastIndexOf(".")); //地址判断 if("login".equals(action)){ String code=request.getParameter("code"); //输入验证码 HttpSession session = request.getSession(); String num=(String)session.getAttribute("num"); //随机生成码 if(!code.equalsIgnoreCase(num)){ //判断验证码 request.setAttribute("code_error", "Code error!"); request.getRequestDispatcher("login.jsp").forward(request, response); return; } String username =request.getParameter("username"); //读取用户名和密码 String pwd =request.getParameter("pwd"); UserDAO dao = new UserDAO(); //查数据库相应记录 try { User user = dao.findByUsername(username); if(user != null&& user.getPwd().equals(pwd)){ //判断用户名和密码 session.setMaxInactiveInterval(60); //session死亡时间60秒 session.setAttribute("user", username); //绑定用户名到seesion response.sendRedirect("index.jsp"); //正确返回主页 }else{ request.setAttribute("login_failed","User or Pwd error!"); //登录失败提示 request.getRequestDispatcher("login.jsp").forward(request, response); } } catch (Exception e) { e.printStackTrace(); throw new ServletException(e); } }else if("logout".equals(action)){ //用户登出 HttpSession session=request.getSession(); session.invalidate(); response.sendRedirect("login.jsp"); } } }
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>ActionServlet</servlet-name> <servlet-class>web.ActionServlet</servlet-class> </servlet> <servlet> <servlet-name>ValidateCode </servlet-name> <servlet-class>web.ValidateCode</servlet-class> </servlet> <servlet-mapping> <servlet-name>ActionServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ValidateCode </servlet-name> <url-pattern>/code</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
<%@page pageEncoding="utf-8" contentType="text/html; charset=utf-8"%> <html> <head> <style type="text/css"> .s1{ cursor: pointer; } </style> </head> <body style="font-size:30px"> <form action="login.do" method="post"> <fieldset> <legend>Login</legend> username:<input name="username"> <% String msg=(String)request.getAttribute("login_failed"); %> <span style="color:red"><%=(msg==null?"":msg)%></span> <br/> pwd: <input type="password" name="pwd"><br/> Code: <input name="code"> <% String msg2=(String)request.getAttribute("code_error"); %> <img src="code" onclick="this.src='code?'+Math.random();" class="s1" title="change"> <span style="color:red"><%=(msg2==null?"":msg2)%></span> <br/> <input type="submit" value="Login" > </fieldset> </form> </body> </html>
<%@page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <% Object user=session.getAttribute("user"); if(user==null){ response.sendRedirect("login.jsp"); return; } %> <html> <head></head> <body> <h1><%=user.toString() %>,</h3>登录成功!<br/><br/> <a href="logout.do">Logout</a> </body> </html>
lib库导入mysql驱动包!