前天晚上完成了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>
如果你是一個新手,我希望能對你有所幫助,嘻嘻!如果你是大神,請多多指教,小弟感激不盡。