zoukankan      html  css  js  c++  java
  • 黑马day07 注册案例(二)

    1依据index.jsp我们首先制定了注册的功能,当点击注册button什么时候。超链接到注册页面。下面是一个注册jsp页

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
      	<script type="text/javascript">
      		function changeImage(image){
      			image.src=image.src+"?

    time"+new Date().getTime(); } </script> <title></title> <meta http-equiv=" pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> </head> <body style="text-align: center"> <h1>我的站点_注冊</h1> <font color="red">${msg }</font> <form action="${pageContext.request.contextPath }/servlet/RegistServlet" method="post"> <table border="1" cellspacing="0" align="center"> <tr> <td>用户名</td> <td><input type="text" name="username" value="${param.username }"/></td> </tr> <tr> <td>密码</td> <td><input type="password" name="password"/></td> </tr> <tr> <td>确认密码</td> <td><input type="password" name="password2"/></td> </tr> <tr> <td>昵称</td> <td><input type="text" name="nickname" value="${param.nickname }"/></td> </tr> <tr> <td>邮箱</td> <td><input type="text" name="email" value="${param.email }"/></td> </tr> <tr> <td>验证码</td> <td><input type="text" name="valistr" /></td> </tr> <tr> <td><input type="submit" value="注冊" /></td> <td><img src="${pageContext.request.contextPath }/servlet/ValiImage" style="cursor: pointer" onclick="changeImage(this)"/></td> </tr> </table> </form> </body> </html>

    执行界面示意图:


    2.完毕验证码的功能建立ValiImage的servlet的类,把字符串保存到session域中,为了一会在RegistServlet中跟用户输入的验证码进行比較


    package cn.itheima.web;
    
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    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 ValiImage extends HttpServlet {
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		//告知浏览器不缓存
    		response.setDateHeader("Expires", -1);
    		response.setHeader("Cache-Control", "no-cache");
    		response.setHeader("Pragma", "no-cache");
    		int height=30;
    		int width=130;
    		//1.得到内存中的图片
    		BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    		//2.得到画布
    		Graphics2D g = (Graphics2D) image.getGraphics();
    		//3.填充背景色
    		g.setColor(Color.LIGHT_GRAY);
    		g.fillRect(0, 0, width, height);
    		//4.画一个矩形
    		g.setColor(Color.black);
    		g.drawRect(0, 0, width-1, height-1);
    		//5.随机斜线
    		for(int i=0;i<4;i++){
    			g.setColor(Color.RED);
    			g.drawLine(randNum(0,width), randNum(0,height), randNum(0,width), randNum(0,height));
    		}
    		//6.随机写一个汉字
    		String base = "u7684u4e00u4e86u662fu6211u4e0du5728u4ebau4eecu6709u6765u4ed6u8fd9u4e0au7740u4e2au5730u5230u5927u91ccu8bf4u5c31u53bbu5b50u5f97u4e5fu548cu90a3u8981u4e0bu770bu5929u65f6u8fc7u51fau5c0fu4e48u8d77u4f60u90fdu628au597du8fd8u591au6ca1u4e3au53c8u53efu5bb6u5b66u53eau4ee5u4e3bu4f1au6837u5e74u60f3u751fu540cu8001u4e2du5341u4eceu81eau9762u524du5934u9053u5b83u540eu7136u8d70u5f88u50cfu89c1u4e24u7528u5979u56fdu52a8u8fdbu6210u56deu4ec0u8fb9u4f5cu5bf9u5f00u800cu5df1u4e9bu73b0u5c71u6c11u5019u7ecfu53d1u5de5u5411u4e8bu547du7ed9u957fu6c34u51e0u4e49u4e09u58f0u4e8eu9ad8u624bu77e5u7406u773cu5fd7u70b9u5fc3u6218u4e8cu95eeu4f46u8eabu65b9u5b9eu5403u505au53ebu5f53u4f4fu542cu9769u6253u5462u771fu5168u624du56dbu5df2u6240u654cu4e4bu6700u5149u4ea7u60c5u8defu5206u603bu6761u767du8bddu4e1cu5e2du6b21u4eb2u5982u88abu82b1u53e3u653eu513fu5e38u6c14u4e94u7b2cu4f7fu5199u519bu5427u6587u8fd0u518du679cu600eu5b9au8bb8u5febu660eu884cu56e0u522bu98deu5916u6811u7269u6d3bu90e8u95e8u65e0u5f80u8239u671bu65b0u5e26u961fu5148u529bu5b8cu5374u7ad9u4ee3u5458u673au66f4u4e5du60a8u6bcfu98ceu7ea7u8ddfu7b11u554au5b69u4e07u5c11u76f4u610fu591cu6bd4u9636u8fdeu8f66u91cdu4fbfu6597u9a6cu54eau5316u592au6307u53d8u793eu4f3cu58ebu8005u5e72u77f3u6ee1u65e5u51b3u767eu539fu62ffu7fa4u7a76u5404u516du672cu601du89e3u7acbu6cb3u6751u516bu96beu65e9u8bbau5417u6839u5171u8ba9u76f8u7814u4ecau5176u4e66u5750u63a5u5e94u5173u4fe1u89c9u6b65u53cdu5904u8bb0u5c06u5343u627eu4e89u9886u6216u5e08u7ed3u5757u8dd1u8c01u8349u8d8au5b57u52a0u811au7d27u7231u7b49u4e60u9635u6015u6708u9752u534au706bu6cd5u9898u5efau8d76u4f4du5531u6d77u4e03u5973u4efbu4ef6u611fu51c6u5f20u56e2u5c4bu79bbu8272u8138u7247u79d1u5012u775bu5229u4e16u521au4e14u7531u9001u5207u661fu5bfcu665au8868u591fu6574u8ba4u54cdu96eau6d41u672au573au8be5u5e76u5e95u6df1u523bu5e73u4f1fu5fd9u63d0u786eu8fd1u4eaeu8f7bu8bb2u519cu53e4u9ed1u544au754cu62c9u540du5440u571fu6e05u9633u7167u529eu53f2u6539u5386u8f6cu753bu9020u5634u6b64u6cbbu5317u5fc5u670du96e8u7a7fu5185u8bc6u9a8cu4f20u4e1au83dcu722cu7761u5174u5f62u91cfu54b1u89c2u82e6u4f53u4f17u901au51b2u5408u7834u53cbu5ea6u672fu996du516cu65c1u623fu6781u5357u67aau8bfbu6c99u5c81u7ebfu91ceu575au7a7au6536u7b97u81f3u653fu57ceu52b3u843du94b1u7279u56f4u5f1fu80dcu6559u70edu5c55u5305u6b4cu7c7bu6e10u5f3au6570u4e61u547cu6027u97f3u7b54u54e5u9645u65e7u795eu5ea7u7ae0u5e2eu5566u53d7u7cfbu4ee4u8df3u975eu4f55u725bu53d6u5165u5cb8u6562u6389u5ffdu79cdu88c5u9876u6025u6797u505cu606fu53e5u533au8863u822cu62a5u53f6u538bu6162u53d4u80ccu7ec6";
    		StringBuffer buffer=new StringBuffer();
    		for(int i=0;i<4;i++){
    			g.setColor(Color.black);
    			int r=randNum(-45, 45);
    			g.rotate(1.0*r/180*Math.PI, 5+30*i, 21);//旋转ת
    			g.setFont(new Font("red", Font.BOLD, 15));
    			String s=base.charAt(randNum(0, base.length()-1))+"";
    			g.drawString(s, 5+30*i, 21);
    			buffer.append(s);
    			g.rotate(1.0*-r/180*Math.PI, 5+30*i, 21);//旋转的是画布,因此旋转完,要归位
    		}
    		request.getSession().setAttribute("valistr", buffer.toString());
    		System.out.println(buffer.toString());
    		//将指定格式的文件输出到response缓冲区
    		ImageIO.write(image, "jpg", response.getOutputStream());
    	}
    	//随机产生begin--end 之间的数字
    	public int randNum(int begin,int end){
    		Random rand=new Random();
    		return rand.nextInt(end-begin)+begin;//5-10 10-5=5 5+5=10
    	}
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    
    }
    
    3.建立RegistServlet实现对应的功能

    package cn.itheima.web;
    
    import java.io.IOException;
    import java.lang.reflect.InvocationTargetException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import cn.itheima.domain.User;
    import cn.itheima.exception.MsgException;
    import cn.itheima.service.UserSevice;
    
    import com.sun.org.apache.commons.beanutils.BeanUtils;
    
    public class RegistServlet extends HttpServlet {
    
    	UserSevice service = new UserSevice();
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		try {
    			response.setContentType("text/html;charset=utf-8");
    			request.setCharacterEncoding("utf-8");
    			// 1.验证验证码
    			String valistr = request.getParameter("valistr");
    			String valistr2 = (String) request.getSession().getAttribute(
    					"valistr");
    
    			if (valistr == null || valistr2 == null ||!valistr.equals(valistr2)) {
    				request.setAttribute("msg", "验证码不对");
    				request.getRequestDispatcher("/regist.jsp").forward(request,
    						response);
    				return;
    			}
    			// 2.封装数据校验数据
    			User user = new User();
    
    			BeanUtils.populate(user, request.getParameterMap());
    			user.check();
    			// 3.加入到数据库中
    			service.registUser(user);
    			request.getSession().setAttribute("user", user);//登陆
    			// 4.3秒后跳转到主页
    			response.getWriter().write("恭喜您注冊成功!三秒后跳转到主页");
    			response.setHeader("refresh", "3;url=" + request.getContextPath()
    					+ "/index.jsp");
    		} catch (MsgException e) {
    			request.setAttribute("msg", e.getMessage());
    			request.getRequestDispatcher("/regist.jsp").forward(request, response);
    			return;
    		}catch (Exception e) {
    			e.printStackTrace();
    			throw new RuntimeException();
    		}
    
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    假设抛出异常。就走catch中的代码块,将msg放到request域中,等到回到regist.jsp中进行友好的提示。假设成功注冊,那么就把用户放到session域中

    执行界面:


    4.依据index,jsp完毕注销的功能,LogoutServlet然后重定向到主页

    package cn.itheima.web;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.jsp.PageContext;
    
    public class LogoutServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		if(request.getSession(false)!=null&&request.getSession().getAttribute("user")!=null){
    			request.getSession().invalidate();
    		}
    			response.sendRedirect(request.getContextPath()+"/index.jsp");
    		
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    

    执行结果示意图:

    5.完毕登录功能建立login.jsp

    <%@page import="java.net.URLDecoder"%>
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://www.itheima.com/simple/mytag" prefix="s" %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
      
        
        <title></title>
        
    	<meta http-equiv=" pragma" content="no-cache">
    	<meta http-equiv="cache-control" content="no-cache">
    	<meta http-equiv="expires" content="0">    
    	
      </head>
      
      <body>
      <div align="center">
      <h1>我的站点_登陆</h1>
      <font color="red">${msg }</font>
      <hr>
        <form action="${pageContext.request.contextPath}/servlet/LoginSevlet" method="post">
        	<table border="1">
        		<tr>
        			<td>username</td>
        			<td><input type="text" name="username" value='<s:decode encoding="utf-8" str="${cookie.remname.value}"/>'/></td>
        		</tr>
        		<tr>
        			<td>密码</td>
        			<td><input type="password" name="password"/></td>
        		</tr>
        		<tr>
        			<td><input type="submit" value="登录"/></td>
        			<td><input type="checkbox" name="remname" value="OK" />记住username</td>
        		</tr>
        	</table>
        </form>
        </div>
      </body>
    </html>
    

    执行界面示意图;


    5.LoginSevlet

    package cn.itheima.web;
    
    import java.io.IOException;
    import java.net.URLEncoder;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.jsp.PageContext;
    
    import cn.itheima.domain.User;
    import cn.itheima.service.UserSevice;
    
    public class LoginSevlet extends HttpServlet {
    	UserSevice service=new UserSevice();
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		request.setCharacterEncoding("utf-8");
    		response.setContentType("text/html;charset=utf-8");
    		//1.得到username与password
    		String username = request.getParameter("username");
    		String password=request.getParameter("password");
    		String OK=request.getParameter("remname");
    		//2.跟数据库的惊醒比較推断
    		User user=service.isUser(username, password);
    		if(user==null){
    			//3.不匹配,就提醒
    			request.setAttribute("msg", "username或密码不对!

    "); request.getRequestDispatcher("/login.jsp").forward(request, response); return; }else{ //4.找到用户。重定向到index.jsp request.getSession().setAttribute("user", user); if("OK".equals(OK)){ //用户须要记住username Cookie c=new Cookie("remname",URLEncoder.encode(user.getUsername(), "utf-8")); c.setPath(request.getContextPath()); c.setMaxAge(3600*24*30); response.addCookie(c); }else{ //假设用户没有勾选记住username则删除记住username的cookie Cookie c = new Cookie("remname",""); c.setPath(request.getContextPath()); c.setMaxAge(0); response.addCookie(c); } } response.sendRedirect(request.getContextPath()+"/index.jsp"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

    Cookie是为了实现记住username的操作。

    6.由于加入Cookie的时候有中文乱码的问题。因此须要url编码和解码的操作....自己定义标签完毕。

    package cn.itheima.utils;
    
    import java.io.IOException;
    import java.net.URLDecoder;
    import java.net.URLEncoder;
    
    import javax.servlet.jsp.JspException;
    import javax.servlet.jsp.tagext.SimpleTagSupport;
    
    public class SimpleURL extends SimpleTagSupport{
    	private String str;
    	private String encoding;
    	
    	public void setStr(String str) {
    		this.str = str;
    	}
    
    	public void setEncoding(String encoding) {
    		this.encoding = encoding;
    	}
    
    	@Override
    	public void doTag() throws JspException, IOException {
    		String decode = URLDecoder.decode(str,  encoding == null ?

    "UTF-8" : encoding); getJspContext().getOut().write(decode); } }



    tld文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
     <tlib-version>1.0</tlib-version>
     <short-name>s</short-name>
     <uri>http://www.itheima.com/simple/mytag</uri>
     <tag>
     	<name>decode</name>
     	<tag-class>cn.itheima.utils.SimpleURL</tag-class>
     	<body-content>empty</body-content>
     	<attribute>
     		<name>str</name>
     		<required>true</required>
     		<rtexprvalue>true</rtexprvalue>
     		<type>java.lang.String</type>
     	</attribute>
     	<attribute>
     		<name>encoding</name>
     		<required>true</required>
     		<rtexprvalue>true</rtexprvalue>
     		<type>java.lang.String</type>
     	</attribute>
     </tag>
    </taglib>
    




  • 相关阅读:
    .net批量插入SqlServer数据库的方法:
    Google主页中国元宵节
    左岸读书你是想读书,还是想读完书?
    Google主页中国著名教育家和画家 丰子恺先生 诞辰114周年
    【转载】图的遍历
    Google主页爱尔兰作家 布拉姆斯托克诞辰165周年
    诺基亚黯然关闭其在欧洲的最后一个手机工厂的背后
    [POJ 1012] Joseph(约瑟夫)
    台湾南投3.27地震
    左岸读书语不惊人死不休(95)
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5047896.html
Copyright © 2011-2022 走看看