前天晚上完成了mvc学习的后端处理,接下来我们继续学习前端的开发,主要包括jsp的代码的编写,其主要完成的功能是用户的注册、用户的登录、用户的注销等信息

(1)、首先来看看我们的主页吧,我们写一个简单的主页信息,主要包括用户的注册、登录、注销。

其中的代码实例如下:

<%@ 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>
    <title>主页显示</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
 `3WX<link rel="stylesheet" type="text/css" href="styles.css">'P07F65D4S32 JMNN54
-->
  </head>
  
  <body>
   <h1>XXXX网站</h1>
   <hr/>
   <c:if test="${sessionScope.user == null }">
   <a href="${pageContext.request.contextPath}/register.jsp">注册</a>
   <a href="${pageContext.request.contextPath}/login.jsp">登录</a>
   </c:if>
      <c:if test="${sessionScope.user != null }">
   欢迎您:${sessionScope.user.username}
   <a href="">注销</a>
<a href="${pageContext.request.contextPath}/servlet/LogoutServlet">注销</a>
   </c:if>
  </body>
</html>

(2)、我们来看看注册的jsp代码的编写吧,简单的说一下思路吧。我们的注册信息界面如下

用户名:

密码:

重复密码:

邮箱:

生日:

所以我们得想好接下来该怎么干呢?

1、数据的封装

2、数据的合法性的校验:当然如果不合法应该回显。

3、填充数据模型:回显

4、调用业务接口:保存数据

所以整个代码如下:

package com.zcp.web;


import java.io.IOException;

import java.io.PrintWriter;

import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;


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

import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;


import com.zcp.domain.User;

import com.zcp.exception.UserHasExistException;

import com.zcp.service.BusinessService;

import com.zcp.service.impl.BusinessServiceImpl;

import com.zcp.util.BeanUtil;

import com.zcp.web.forbean.UserFormBean;


public class RegistServlet extends HttpServlet {


private BusinessService bs = new BusinessServiceImpl();

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

UserFormBean formBean = null;

try {

//封装数据

formBean= BeanUtil.fillBean(request, UserFormBean.class);

//验证数据的合法性:回显

if(!formBean.validate()){

request.setAttribute("frombean", formBean);

request.getRequestDispatcher("/register.jsp").forward(request, response);

return;

}

//填充模型:回显

User user = new User();

/*user.setUsername(formBean.getUsername());

user.setPassword(formBean.getPassword());

user.setEmail(formBean.getEmail());

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

user.setBirthday(df.parse(formBean.getBirthday()));*/

ConvertUtils.register(new DateLocaleConverter(), Date.class);

BeanUtils.copyProperties(user, formBean);

//保存数据:调用业务层,给出成功提示

System.out.println("user==========="+user.toString());

bs.regist(user);

System.out.println("user="+user.toString());

response.sendRedirect(request.getContextPath());//成功,重定向到主页

}catch(UserHasExistException e){

//用户名重复

//用户名存在的问题:回显  抓异常的形式捕获

formBean.getErrors().put("username", e.getMessage());

request.setAttribute("formBean", formBean);

request.getRequestDispatcher("/register.jsp").forward(request, response);

System.out.println("用户名重复了");

return;

/*  formBean.getErrors().put("username", "用户名存在了");

                            

request.setAttribute("formBean", formBean);

request.getRequestDispatcher("/register.jsp").forward(request, response);

*/

  

  

 

} catch (Exception e) {

throw new RuntimeException(e);

}

}


public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {


doGet(request, response);

}


}

在上述代码中调用了数据的封装的方法:

所以下面是数据的封装的方法:

package com.zcp.util;



import javax.servlet.http.HttpServletRequest;


import org.apache.commons.beanutils.BeanUtils;


public class BeanUtil {


//把请求参数封装到指定的JavaBean中

public static <T> T fillBean(HttpServletRequest request,Class<T> clazz){

try {

T bean = clazz.newInstance();

BeanUtils.populate(bean, request.getParameterMap());

return bean;

} catch(Exception e) {

throw new RuntimeException(e);

}

}

}

formbean的代码的编写:

package com.zcp.web.forbean;


import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.HashMap;

import java.util.Map;


//字段都是私有的,且都是String类型,避免类型转换

//提供验证的方法。验证不同的还有提示信息


//字段和表单的字段完全一致

public class UserFormBean {


private String username;

private String password;

private String repassword;

private String email;

private String birthday;

private String matchemail = "\\b^['_a-z0-9-\\+]+(\\.['_a-z0-9-\\+]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2}|aero|arpa|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|nato|net|org|pro|tel|travel|xxx)$\\b";

//封装错误信息:key,字段;value:错误信息

private Map<String, String> errors = new HashMap<String, String>();

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public String getRepassword() {

return repassword;

}

public void setRepassword(String repassword) {

this.repassword = repassword;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public String getBirthday() {

return birthday;

}

public void setBirthday(String birthday) {

this.birthday = birthday;

}


//服务器端验证:

public boolean validate(){

//验证的数据不符合要求:向errors中添加字段和错误提示

//用户名:3~8个字母。不能为空

/*if(username.trim().equals("")){

errors.put("username", "请输入用户名");

}else{

if(!username.matches("[a-zA-Z]{3,8}")){

errors.put("username", "用户名必须由3~8位字母组成");

}

}*/

if(username.trim().equals("")){

errors.put("username", "请输入用户名");

}else{

if(!username.matches("[a-zA-Z]{3,8}")){

errors.put("username", "用户名必须由3~8位字母组成");

}

}

//密码:3~8位数字组成,不能为空

if(password.trim().equals("")){

errors.put("password", "请输入密码");

}else{

if(!password.matches("\\d{3,8}")){

errors.put("password", "密码必须由3~8位数字组成");

}

}

//重复密码:必须和密码一致

if(!password.equals(repassword)){

errors.put("repassword", "两次密码必须一致");

}

//邮箱:不能为空,且要符合邮箱的格式

if(email.trim().equals("")){

errors.put("email", "请输入邮箱");

}else{

if(!email.matches(matchemail)){

errors.put("email", "您输入的邮箱格式有误");

}

}

//生日:不能为空,且要符合yyyy-MM-dd的格式

if(birthday.trim().equals("")){

errors.put("birthday", "请输入出生日期");

}else{

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

try {

df.parse(birthday);

} catch (ParseException e) {

e.printStackTrace();

errors.put("birthday", "日期格式不合法");

}

}

return errors.isEmpty();

}


public Map<String, String> getErrors() {

return errors;

}

}

以上就是主要的注册代码了,剩下的就是简单的登录和注销代码。相对于注册来说,登录和注销就简单很多了。我们就看看登录的loginServlet代码吧:

package com.zcp.web;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import com.zcp.domain.User;

import com.zcp.service.BusinessService;

import com.zcp.service.impl.BusinessServiceImpl;


public class loginServlet extends HttpServlet {


BusinessService sb = new BusinessServiceImpl();

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

String username = request.getParameter("username");

String password = request.getParameter("password");

User user = sb.login(username, password);

if(user == null){

out.write("错误的用户名或者密码,2秒后转向登录页面");

response.setHeader("Refresh", "2;URL="+request.getContextPath()+"/login.jsp");

}

request.getSession().setAttribute("user", user);

response.sendRedirect(request.getContextPath());

}


public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {


doGet(request, response);

}


}

再来看看登录的jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>



<!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">    

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->


  </head>

  

  <body>

  


<form action="${pageContext.request.contextPath}/servlet/loginServlet" method="post">

<table border="1" width="538">

<tr>

<td>用户名:</td>

<td>

<input type="text" name="username" value="">

</td>

</tr>

<tr>

<td>密码:</td>

<td>

<input type="text" name="password" value="">

</td>

</tr>

<tr >

<td colspan="2">

<input type="submit" value="提交"/>

</td>

</tr>

</table>

</form>



  </body>

</html>

最后就就是简单的注销代码了:

package com.zcp.web;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class LogoutServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

request.getSession().removeAttribute("user");

response.sendRedirect(request.getContextPath());

}


public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {


doGet(request, response);

}


}

当然在;作为web开发,还有一个最重要的web.xml的配置啦!由于我是采用的myeclipse开发,所以配置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">

  <display-name></display-name>

  <servlet>

    <servlet-name>RegistServlet</servlet-name>

    <servlet-class>com.zcp.web.RegistServlet</servlet-class>

  </servlet>

  <servlet>

    <servlet-name>loginServlet</servlet-name>

    <servlet-class>com.zcp.web.loginServlet</servlet-class>

  </servlet>

  <servlet>

    <servlet-name>LogoutServlet</servlet-name>

    <servlet-class>com.zcp.web.LogoutServlet</servlet-class>

  </servlet>




  <servlet-mapping>

    <servlet-name>RegistServlet</servlet-name>

    <url-pattern>/servlet/RegistServlet</url-pattern>

  </servlet-mapping>

  <servlet-mapping>

    <servlet-name>loginServlet</servlet-name>

    <url-pattern>/servlet/loginServlet</url-pattern>

  </servlet-mapping>

  <servlet-mapping>

    <servlet-name>LogoutServlet</servlet-name>

    <url-pattern>/servlet/LogoutServlet</url-pattern>

  </servlet-mapping>

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

</web-app>

如果你是一个新手,我希望能对你有所帮助,嘻嘻!如果你是大神,请多多指教,小弟感激不尽。