JSP开发模型

JSP开发模型

为了方便使用JSP技术,SUN公司玮JSP技术提供了两种开发模型:JSP Mode1 和 JSP Mode2.

1.创建项目,编写JavaBean

(1)编写一个UserBean类,用于封装用户信息,代码如下:

package chapter14.jsp;
 
public class UserBean {
	private String name;
	private String password;
	private String email;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
}

2) 编写RegisterFormBean类,用于封装注册表单

package chapter14.jsp;
 
import java.util.HashMap;
import java.util.Map;
 
public class RegisterFormBean {
 
	//1.用来封装注册参数的
	private String name;
	private String password;
	private String password2;
	private String email;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getPassword2() {
		return password2;
	}
	public void setPassword2(String password2) {
		this.password2 = password2;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	//------------进行服务端的数据-----------------------
	//2.定义变量来接收用户校验的信息,比如说用户名、邮箱是否符合规范,
	//第一个参数 属性名称  第二个参数:属性值是否符合规范信息,比如(“email”,”邮箱格式有误“);
	private Map<String,String> errors = new HashMap<String,String>();
	public boolean validate(){
		//2.定义变量,来判断数据是否满足规范,如果满足 就返回true,不满足就返回false
		boolean flag = true;
		if(name == null || name.trim().equals("")){
			errors.put("name","请输入用户名");
			flag = false;
			return flag;
		}
		if(password == null || password.trim().equals("")){
			errors.put("password","请输入密码");
			flag = false;
			return flag;
		}else if(password.length()>12 || password.length()<6){
			errors.put("password","请输入6-12个字符");
			flag = false;
			return flag;
		}
		if(password != null && !password.equals(password2)){
			errors.put("password2","两次输入密码不一致");
			flag = false;
			return flag;
		}
		//校验邮箱,校验邮箱格式是否满足规范
		  String regex = "[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+";
		  if(email == null || email.trim().equals("")){
				errors.put("email","请输入邮箱");
				flag = false;
				return flag;
		 }else if(!email.matches(regex)){
				errors.put("email","邮箱格式错误");
				flag = false;
				return flag;
		}
		
			return flag;
	}
	//获取错误信息的方法
	public Map<String, String> getErrors() {
		return errors;
	}
	//提供向map集合中添加错误信息
	public void setErrorMsg(String err,String errMsg){
		if((err != null) && (errMsg!=null)){
			errors.put(err, errMsg);
		}
	}
}

2.创建工具类 
(1) 编写DBUtil,实现两个功能,一个是定义了一个HashMap集合users,用于模拟数据库,并向数据库中存入了两条学生信息,第二个是定义getUser()方法和insertYser()方法操作数据库,如果存在就不能新建(返回FALSE),不存在则注册成功(返回TRUE)代码如下:

package chapter14.jsp;
 
import java.util.HashMap;
 
import chapter14.jsp.UserBean;
 
/*
 * 模拟数据库
 */
/*
 * 模拟数据库
 */
public class DBUtil {
	private static DBUtil instance = new DBUtil();
	public static  DBUtil getInstance(){
		return instance;
	}
	//定义集合,来保存用户注册的数据
	private HashMap<String, UserBean> users = new HashMap<String, UserBean>();
	
	//插入2条数据
	public DBUtil(){
		UserBean user1 = new UserBean();
		user1.setName("Jack");
		user1.setPassword("123456");
		user1.setEmail("jack@it315.org");
		users.put("Jack",user1);//链接数据库,放进去
		
		UserBean user2 = new UserBean();
		user2.setName("Rose");
		user2.setPassword("abcdefr");
		user2.setEmail("rose@it315.org");
		users.put("Rose",user2);
	
	}
	//获取值的方法
	public UserBean getUser(String username){
		UserBean user = users.get(username);
		return user;
	}
	//提供插入数据库的方法
	public boolean insertUser(UserBean user){
		//用户为null,不能插入
		if(user == null){
			return false;
		}
		//判断用户名是否重复
		String username = user.getName();//用户提交过来的注册的参数
		//String usernameDB = users.get(username).getName();//从数据库查询出来的用户名
		UserBean userDB = users.get(username);
		if(userDB !=null){//根据注册参数查询数据库有用户对象,表明用户名存在
			return false;
		}
		users.put(username,user);
		return true;
		
	}
}

3.创建Servlet用来处理用户请求,新建一个ControllerServlet代码如下:

package chapter14.jsp;
 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
 
/**
 * Servlet implementation class ControllerServlet
 */
@WebServlet("/ControllerServlet")
public class ControllerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
 
 
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}
 
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		String password2 = request.getParameter("password2");
		String email = request.getParameter("email");
		RegisterFormBean formBean = new RegisterFormBean();
		formBean.setName(name);
		formBean.setPassword(password);
		formBean.setPassword2(password2);
		formBean.setEmail(email);
		//验证参数填写是否符合要求,如果不符合,转发到register.jsp重新填写
		if(!formBean.validate()) {
			request.setAttribute("formBean", formBean);
			request.getRequestDispatcher("/register.jsp").forward(request, response);
			return;
		}
		//参数填写符合要求,则将数据封装到UserBean类中
		UserBean userBean = new UserBean();
		userBean.setName(name);
		userBean.setPassword(password);
		userBean.setEmail(email);
		//调用DBUtil的insertYser()方法执行添加操作,并返回一个boolean类型的标志
		boolean b = DBUtil.getInstance().insertUser(userBean);
		//如果返回false则表示注册的用户存在,重新填写
		if(!b) {
			request.setAttribute("DBMes", "你注册的用户已存在");
			request.setAttribute("formBean", formBean);
			request.getRequestDispatcher("/register.jsp").forward(request, response);
			return;
		}
		response.getWriter().print("恭喜你注册成功,3秒钟自动跳转");
		//将成功注册的用户信息添加到Session中
		request.getSession().setAttribute("userBean", userBean);
		//注册成功后,3秒跳转到登录成功页面loginSuccess.jsp
		response.setHeader("refresh", "3;url=loginSuccess.jsp");
	}
}

4. 创建JSP页面

(1) 编写register.jsp文件,代码如下:

<%@ page language="java" pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
    <title>用户注册</title>
    <style type="text/css">
        h3 {
	        margin-left: 100px;
        }
        #outer {
	        width: 750px;
        }
        span {
	        color: #ff0000
        }
        div {
             height:20px;
	        margin-bottom: 10px;
        }
        .ch {
	        width: 80px;
	        text-align: right;
	        float: left;
        }
        .ip {
	        width: 500px;
	        float: left
        }
        .ip>input {
	        margin-right: 20px
        }
        #bt {
	        margin-left: 50px;
        }
        #bt>input {
	        margin-right: 30px;
        }
    </style>
</head>
<body>
	    <form action="ControllerServlet" method="post">
		    <h3>用户注册</h3>
		    <div id="outer">
			    <div>
				    <div class="ch">姓名:</div>
				    <div class="ip">
				<input type="text" name="name" value="${formBean.name }" />
					    <span>${formBean.errors.name}${DBMes}</span>
				    </div>
			    </div>
			    <div>
				    <div class="ch">密码:</div>
				    <div class="ip">
					    <input type="password" name="password" />
					    <span>${formBean.errors.password}</span>
				    </div>
			    </div>
			    <div>
				    <div class="ch">确认密码:</div>
				    <div class="ip">
					    <input type="password" name="password2" />
					    <span>${formBean.errors.password2}</span>
				    </div>
			    </div>
			    <div>
				    <div class="ch">邮箱:</div>
				    <div class="ip">
			<input type="text" name="email" value="${formBean.email }" />
					    <span>${formBean.errors.email}</span>
				    </div>
			    </div>
			    <div id="bt">
				    <input type="reset" value="重置 " />
				    <input type="submit" value="注册" />
			    </div>
		    </div>
	    </form>
</body>
</html>

(2) 编写loginSuccess.jsp文件,是用来显示用户登录成功页面,代码如下:

<%@ page language="java" pageEncoding="GBK" import="chapter14.jsp.UserBean"%>
 
<%@ 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>
<title>login successfully</title>
    <style type="text/css">
        #main {
	        width: 500px;
	        height: auto;
        }
        #main div {
	        width: 200px;
	        height: auto;
        }
        ul {
	        padding-top: 1px;
	        padding-left: 1px;
	        list-style: none;
        }
    </style>
</head>
<body>
 
	    <div id="main">
		    <div id="welcome">恭喜你,登录成功</div>
             <hr />
		    <div>您的信息</div>
		    <div>
			    <ul>
				    <li>您的姓名: ${userBean.name }</li>
				    <li>您的邮箱:${userBean.email}</li>
			    </ul>
		    </div>
	    </div>
</body>
</html>

5. 运行程序,测试结果 

 运行register.jsp:

JSP开发模型

输入姓名,密码,邮箱,点击注册就可以注册,

 JSP开发模型

 JSP开发模型

 

上一篇:MySql pwd policy requirement


下一篇:9.29JavaWeb之PreparedStatement针对测试表的操作