计算器 & 登录注册 案例 model1 model2 开发模式 BeanUtils

JSP 两种开发模式

JSP model1 : JSP + JavaBean 组合 ,适合开发中小型简单应用,JSP负责业务流程控制、页面显示;JavaBean 负责数据封装和处理
JSP model2 : Servlet + JSP + JavaBean 组合,符合MVC 设计模式,适合开发业务流程复杂大型应用,JSP 只负责页面显示,JavaBean负责数据封装和处理,Servlet负责业务流程控制,JavaBean、JSP调度 --------- 分工明确,便于维护

计算器案例:

calculator.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    function validateForm(){
        var first = document.getElementById("first").value; // 这个v必须小写
        var second = document.getElementById("second").value;
        // 判断两个参数 必须为数字
        if(isNaN(first) || isNaN(second)){
            // 输入非法 
            alert("输入的参数必须为数字!");
            return false; // 阻止form 提交
        }
    }
</script>
</head>
<body>
<!-- 页面由两个部分组成 -->
<!-- 显示运算结果 -->
<!-- 封装请求参数 到JavaBean对象中 -->
<jsp:useBean id="calculator" class="cn.itcast.domain.Calculator" scope="page"></jsp:useBean>
<jsp:setProperty property="*" name="calculator"/>
<!-- 执行运算,显示计算结果 -->
<h3>计算结果是 :${calculator.firstNum } ${calculator.operator } ${calculator.secondNum } = ${calculator.result }</h3>
<hr/>
<!-- 计算参数输入form表单 -->
<form action="/day9/calculator.jsp" method="post" onsubmit="return validateForm();">
    <table>
        <tr>
            <td>第一个参数</td>
            <td><input type="text" name="firstNum" id="first"/></td>
        </tr>
        <tr>
            <td>运算符</td>
            <td>
                <select name="operator">
                    <option value="+">+</option>
                    <option value="-">-</option>
                    <option value="*">*</option>
                    <option value="/">/</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>第二个参数</td>
            <td><input type="text" name="secondNum" id="second" /></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="计算" />
            </td>
        </tr>
    </table>
</form>
</body>
</html>

Calculator.java

package cn.itcast.domain;

import java.math.BigDecimal;

/**
 * 存放计算器数据
 * 
 * @author seawind
 * 
 */
public class Calculator {
    private String firstNum = "0";
    private String operator = "+";
    private String secondNum = "0";
    private double result;

    public String getFirstNum() {
        return firstNum;
    }

    public void setFirstNum(String firstNum) {
        this.firstNum = firstNum;
    }

    public String getOperator() {
        return operator;
    }

    public void setOperator(String operator) {
        this.operator = operator;
    }

    public String getSecondNum() {
        return secondNum;
    }

    public void setSecondNum(String secondNum) {
        this.secondNum = secondNum;
    }

    public void setResult(double result) {
        this.result = result;
    }

    // 在获得result的时候,进行计算
    public double getResult() {
        // 将两个参数 转换 double 类型
        BigDecimal num1 = new BigDecimal(firstNum);
        BigDecimal num2 = new BigDecimal(secondNum);
        BigDecimal result = null;
        if (operator.equals("+")) {
            result = num1.add(num2);
        } else if (operator.equals("-")) {
            result = num1.subtract(num2);
        } else if (operator.equals("*")) {
            result = num1.multiply(num2);
        } else if (operator.equals("/")) {
            if (num2.doubleValue() == 0) {
                throw new RuntimeException("除数不能为0!");
            }
            result = num1.divide(num2, 9, BigDecimal.ROUND_HALF_UP);
        }
        return result.doubleValue();
    }

    // public double getResult() {
    // // 将两个参数 转换 double 类型
    // double num1 = Double.parseDouble(firstNum);
    // double num2 = Double.parseDouble(secondNum);
    // if (operator.equals("+")) {
    // result = num1 + num2;
    // } else if (operator.equals("-")) {
    // result = num1 - num2;
    // } else if (operator.equals("*")) {
    // result = num1 * num2;
    // } else if (operator.equals("/")) {
    // if (num2 == 0) {
    // throw new RuntimeException("除数不能为0!");
    // }
    // result = num1 / num2;
    // }
    // return result;
    // }

}

登录注册案例:

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>主页</h1>
<!-- 通过判断 session中信息,得知用户是否登陆 -->
<c:if test="${empty existUser}">
    您还未登陆!
</c:if>

<c:if test="${not empty existUser}">
    用户昵称:${existUser.nickname }
    邮箱 :${existUser.email }
    <a href="/day9user/invalidate" >注销</a>
</c:if>
<hr/>
<a href="/day9user/regist.jsp">用户注册</a>
<a href="/day9user/login.jsp">用户登陆</a>
</body>
</html>

regist.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    // 点击切换验证码
    function change(){
        document.getElementById("myimg").src = "/day9user/checkimg?"+new Date().getTime();
    }
    // 数据合法性 校验
    function validateForm(){
        // 获得需要校验内容的value属性
        var username = document.getElementById("username").value;
        if(username == ""){
            alert("用户名不能为空");
            return false;
        }
        var password = document.getElementById("password").value;
        if(password==""){
            alert("密码不能为空!");
            return false;
        }
        var repassword = document.getElementById("repassword").value;
        if(password != repassword){
            alert("两次密码输入不一致!");
            return false;
        }
        // 省略昵称为空、验证码为空判断
        var email = document.getElementById("email").value;
        // 正则表达式 (\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*;)*
        if(email.match("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+\\.([a-zA-Z0-9_-])+$")==null){
            // 不匹配
            alert("邮箱的地址非法!");
            return false;
        }
    }
</script>
</head>
<body>
<h1>用户注册页面</h1>
<h3 style="color:red">${msg }</h3>
<form onsubmit="return validateForm();" action="/day9user/regist" method="post">
    <table>
        <tr>
            <td>用户名</td>
            <td><input type="text" name="username" id="username"/></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="password" name="password" id="password"/></td>
        </tr>
        <tr>
            <td>确认密码</td>
            <td><input type="password" name="repassword" id="repassword"/></td>
        </tr>
        <tr>
            <td>昵称</td>
            <td><input type="text" name="nickname" id="nickname"/></td>
        </tr>
        <tr>
            <td>邮箱</td>
            <td><input type="text" name="email" id="email" /></td>
        </tr>
        <tr>
            <td>验证码</td>
            <td><input type="text" name="checkcode" id="checkcode"/> <img src="/day9user/checkimg" onclick="change();" id="myimg" style="cursor: pointer;"/></td>
        </tr>
        <tr>
            <td colspan=2">
                <input type="submit" value="注册" />
            </td>
        </tr>
    </table>
</form>
</body>
</html>

RegistServlet.java

package cn.itcast.user.controller;

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 org.apache.commons.beanutils.BeanUtils;

import cn.itcast.user.model.User;
import cn.itcast.user.model.UserOperation;

/**
 * 注册 Servlet程序
 * 
 * @author seawind
 * 
 */
public class RegistServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 处理 中文乱码
        request.setCharacterEncoding("utf-8");

        // 判断验证码信息是否有效
        String checkcode_session = (String) request.getSession().getAttribute(
                "checkcode_session");// session中验证码
        request.getSession().removeAttribute("checkcode_session");
        String checkcode = request.getParameter("checkcode");// 用户输入验证码
        if (checkcode_session == null || !checkcode_session.equals(checkcode)) {
            // 验证码输入错误
            request.setAttribute("msg", "验证码输入错误!");
            request.getRequestDispatcher("/regist.jsp").forward(request,
                    response);
            return;
        }

        // 封装数据 JavaBean
        User user = new User();
        try {
            BeanUtils.populate(user, request.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        // 需要另一个JavaBean处理数据
        UserOperation userOperation = new UserOperation();
        try {
            int result = userOperation.regist(user);
            // 判断注册结果
            if (result == UserOperation.SUCCESS) {
                // 注册成功
                response.sendRedirect("/day9user/login.jsp");
            } else if (result == UserOperation.USERNAMEEXIST) {
                // 用户名已经存在
                request.setAttribute("msg", "用户名已经存在");
                request.getRequestDispatcher("/regist.jsp").forward(request,
                        response);
                return;
            } else {
                // 邮箱已经存在
                request.setAttribute("msg", "邮箱已经存在");
                request.getRequestDispatcher("/regist.jsp").forward(request,
                        response);
                return;

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

UserOperation.java

package cn.itcast.user.model;

import java.io.FileOutputStream;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 数据处理的javabean
 * 
 * @author seawind
 * 
 */
public class UserOperation {
    public static final int SUCCESS = 1;
    public static final int USERNAMEEXIST = 2;
    public static final int EMAILEXIST = 3;

    // 用户登陆
    // 如果方法返回boolean 只能知道登陆成功还是失败
    // 有些情况,需要在登陆后,获得用户一些其它信息 --- 返回用户所有信息
    public User login(User user) throws Exception {
        SAXReader reader = new SAXReader();
        Document document = reader.read("d:\\users.xml");

        Element users = document.getRootElement();// 根元素
        List<Element> userList = users.elements("user");

        // 判断用户名和密码是否正确
        for (Element existUser : userList) {
            if (existUser.elementText("username").equals(user.getUsername())
                    && existUser.elementText("password").equals(
                            user.getPassword())) {
                // 登陆成功,封装用户所有信息
                user.setNickname(existUser.elementText("nickname"));
                user.setEmail(existUser.elementText("email"));
                return user;
            }
        }

        // 用户名和密码不存在
        return null;
    }

    // 用户注册
    public int regist(User user) throws Exception {
        // 读取XML (XML位置 磁盘固定位置或者 src目录)
        SAXReader reader = new SAXReader();
        Document document = reader.read("d:\\users.xml");

        // 判断输入用户信息中 用户名和邮箱是否存在
        Element users = document.getRootElement();
        List<Element> userList = users.elements("user");
        for (Element existUser : userList) {
            if (existUser.elementText("username").equalsIgnoreCase(
                    user.getUsername())) {
                // 用户名已经存在
                return USERNAMEEXIST;
            } else if (existUser.elementText("email").equalsIgnoreCase(
                    user.getEmail())) {
                // 邮箱已经存在
                return EMAILEXIST;
            }
        }

        // 用户名和邮箱不存在,可以注册
        Element newUserElement = DocumentHelper.parseText(
                "<user><username>" + user.getUsername()
                        + "</username><password>" + user.getPassword()
                        + "</password><nickname>" + user.getNickname()
                        + "</nickname><email>" + user.getEmail()
                        + "</email></user>").getRootElement();
        users.add(newUserElement);

        // 回写数据到XML
        OutputFormat format = OutputFormat.createPrettyPrint(); // 自动换行
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(
                "d:\\users.xml"), format);
        xmlWriter.write(document);

        return SUCCESS;
    }
}

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>登陆页面</h1>
<h3 style="color:red">${msg }</h3>
<form action="/day9user/login" method="post">
    <table>
        <tr>
            <td>用户名</td>
            <td><input type="text" name="username" value="${cookie.username.value }"/></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="password" name="password" value="${cookie.password.value }"/></td>
        </tr>
        <tr>
            <td><input type="checkbox" name="remember" value="on" /></td>
            <td>记住用户名和密码</td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="登陆" />
            </td>
        </tr>
    </table>
</form>
</body>
</html>

LoginServlet.java

package cn.itcast.user.controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

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 org.apache.commons.beanutils.BeanUtils;

import cn.itcast.user.model.User;
import cn.itcast.user.model.UserOperation;

/**
 * 完成用户登陆功能
 * 
 * @author seawind
 * 
 */
public class LoginServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 解决请求参数乱码
        request.setCharacterEncoding("utf-8");

        // 封装数据 到javabean
        User user = new User();
        try {
            BeanUtils.populate(user, request.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        // 调用UserOperation 进行登陆操作
        UserOperation userOperation = new UserOperation();
        try {
            User existUser = userOperation.login(user);
            // 判断登陆是成功还是失败
            if (existUser == null) {
                // 登陆失败
                request.setAttribute("msg", "用户名或者密码错误!");
                request.getRequestDispatcher("/login.jsp").forward(request,
                        response);
                return;
            } else {
                // 登陆成功
                // 将登陆用户信息 保存到Session
                request.getSession().setAttribute("existUser", existUser);

                // 记住用户名和密码
                // 判断一下用户是否勾选了 记住选择框
                if ("on".equals(request.getParameter("remember"))) {
                    // 用户勾选了记住 选择框
                    Cookie usernameCookie = new Cookie("username", existUser
                            .getUsername());
                    usernameCookie.setPath("/");
                    usernameCookie.setMaxAge(60 * 60 * 24 * 14);// 两个星期
                    response.addCookie(usernameCookie);

                    Cookie passwordCookie = new Cookie("password", existUser
                            .getPassword());
                    passwordCookie.setPath("/");
                    passwordCookie.setMaxAge(60 * 60 * 24 * 14);// 两个星期
                    response.addCookie(passwordCookie);
                }

                response.sendRedirect("/day9user/index.jsp");
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

InvalidateServlet.java

package cn.itcast.user.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 完成用户注销
 * 
 * @author seawind
 * 
 */
public class InvalidateServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 销毁session
        request.getSession().invalidate();

        // 跳转回主页
        response.sendRedirect("/day9user/index.jsp");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

web.xml

<?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>CheckImgServlet</servlet-name>
    <servlet-class>cn.itcast.user.view.CheckImgServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>RegistServlet</servlet-name>
    <servlet-class>cn.itcast.user.controller.RegistServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>cn.itcast.user.controller.LoginServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>InvalidateServlet</servlet-name>
    <servlet-class>cn.itcast.user.controller.InvalidateServlet</servlet-class>
  </servlet>




  <servlet-mapping>
    <servlet-name>CheckImgServlet</servlet-name>
    <url-pattern>/checkimg</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>RegistServlet</servlet-name>
    <url-pattern>/regist</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>InvalidateServlet</servlet-name>
    <url-pattern>/invalidate</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

posted @ 2014-08-27 09:38  vaer  阅读(658)  评论(0编辑  收藏  举报