時(shí)間:2023-05-31 03:57:01 | 來源:網(wǎng)站運(yùn)營
時(shí)間:2023-05-31 03:57:01 來源:網(wǎng)站運(yùn)營
Web開發(fā)模式【Mode I 和Mode II的介紹、應(yīng)用案例】:public class Calculator { private double firstNum; private double secondNum; private char Operator = '+'; private double result; //JavaBean提供了計(jì)算的功能 public void calculate() { switch (this.Operator) { case '+': this.result = this.firstNum + this.secondNum; break; case '-': this.result = this.firstNum - this.secondNum; break; case '*': this.result = this.firstNum * this.secondNum; break; case '/': if (this.secondNum == 0) { throw new RuntimeException("除數(shù)不能為0"); } this.result = this.firstNum / this.secondNum; break; default: throw new RuntimeException("傳入的字符非法!"); } } public double getFirstNum() { return firstNum; } public void setFirstNum(double firstNum) { this.firstNum = firstNum; } public double getSecondNum() { return secondNum; } public void setSecondNum(double secondNum) { this.secondNum = secondNum; } public char getOperator() { return Operator; } public void setOperator(char operator) { Operator = operator; } public double getResult() { return result; } public void setResult(double result) { this.result = result; } }
<%--開發(fā)用戶界面--%> <form action="/zhongfucheng/1.jsp" method="post"> <table border="1"> <tr> <td colspan="2">簡單計(jì)數(shù)器</td> <td></td> </tr> <tr> <td>第一個(gè)參數(shù):</td> <td><input type="text" name="firstNum"></td> </tr> <tr> <td>運(yùn)算符</td> <td> <select name="operator"> <option value="+">+</option> <option value="-">-</option> <option value="*">*</option> <option value="/">/</option> </select> </td> </tr> <tr> <td>第二個(gè)參數(shù):</td> <td><input type="text " name="secondNum"></td> </tr> <tr> <td colspan="2"><input type="submit" value="提交"></td> <td></td> </tr> </table> </form>
<%--獲取得到Bean對(duì)象--%> <jsp:useBean id="calculator" class="domain.Calculator" scope="page"/> <%--設(shè)置Bean對(duì)象的數(shù)據(jù)--%> <jsp:setProperty name="calculator" property="*"/> <%--調(diào)用Caculator的方法計(jì)算出值--%> <jsp:scriptlet> calculator.calculate(); </jsp:scriptlet> <%--得出的結(jié)果:--%> <c:out value="計(jì)算得出的結(jié)果是:"/> <jsp:getProperty name="calculator" property="firstNum"/> <jsp:getProperty name="calculator" property="operator"/> <jsp:getProperty name="calculator" property="secondNum"/> <c:out value="="/> <jsp:getProperty name="calculator" property="result"/>
private int id; private String username; private String password; private String email; private Date birthday; //....各種setter、getter
//外界傳遞用戶名和密碼進(jìn)來,我要在XML文檔中查找是否有該條記錄 public User find(String username, String password) { //得到XML文檔的流對(duì)象 InputStream inputStream = UserImplXML.class.getClassLoader().getResourceAsStream("user.xml"); //得到dom4j的解析器對(duì)象 SAXReader saxReader = new SAXReader(); try { //解析XML文檔 Document document = saxReader.read(path); //使用XPATH技術(shù),查找XML文檔中是否有傳遞進(jìn)來的username和password Element element = (Element) document.selectSingleNode("//user[@username='" + username + "' and@password='" + password + "']"); if (element == null) { return null; } //如果有,就把XML查出來的節(jié)點(diǎn)信息封裝到User對(duì)象,返回出去 User user = new User(); user.setId(Integer.parseInt(element.attributeValue("id"))); user.setUsername(element.attributeValue("username")); user.setPassword(element.attributeValue("password")); user.setEmail(element.attributeValue("email")); //生日就需要轉(zhuǎn)換一下了,XML文檔保存的是字符串,User對(duì)象需要的是Date類型 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy-MM-dd"); Date birthday = simpleDateFormat.parse(element.attributeValue("birthday")); user.setBirthday(birthday); //返回User對(duì)象出去 return user; } catch (DocumentException e) { e.printStackTrace(); throw new RuntimeException("初始化時(shí)候出錯(cuò)啦!"); } catch (ParseException e) { e.printStackTrace(); throw new RuntimeException("查詢的時(shí)候出錯(cuò)啦!"); } }
private String username = "zhongfucheng"; private String password = "123"; @Test public void testLogin() { UserImplXML userImplXML = new UserImplXML(); User user = userImplXML.find(username, password); System.out.println(user.getBirthday()); System.out.println(user.getEmail()); System.out.println(user.getId()); System.out.println(user.getUsername()); System.out.println(user.getPassword()); }
//注冊功能,外界傳遞一個(gè)User對(duì)象進(jìn)來。我就在XML文檔中添加一條信息 public void register(User user) { //獲取XML文檔路徑! String path = UserImplXML.class.getClassLoader().getResource("user.xml").getPath(); try { //獲取dom4j的解析器,解析XML文檔 SAXReader saxReader = new SAXReader(); Document document = saxReader.read(path); //在XML文檔中創(chuàng)建新的節(jié)點(diǎn) Element newElement = DocumentHelper.createElement("user"); newElement.addAttribute("id", String.valueOf(user.getId())); newElement.addAttribute("username", user.getUsername()); newElement.addAttribute("email", user.getEmail()); newElement.addAttribute("password", user.getPassword()); //日期返回的是指定格式的日期 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy-MM-dd"); String date = simpleDateFormat.format(user.getBirthday()); newElement.addAttribute("birthday",date); //把新創(chuàng)建的節(jié)點(diǎn)增加到父節(jié)點(diǎn)上 document.getRootElement().add(newElement); //把XML內(nèi)容中文檔的內(nèi)容寫到硬盤文件上 OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("UTF-8"); XMLWriter xmlWriter = new XMLWriter(new FileWriter(path),outputFormat); xmlWriter.write(document); xmlWriter.close(); } catch (DocumentException e) { e.printStackTrace(); throw new RuntimeException("注冊的時(shí)候出錯(cuò)了?。?!"); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("注冊的時(shí)候出錯(cuò)了?。?!"); } }
@Test public void testRegister() { UserImplXML userImplXML = new UserImplXML(); //這里我為了測試的方便,就添加一個(gè)帶5個(gè)參數(shù)的構(gòu)造函數(shù)了! User user = new User(10, "nihao", "123", "sina@qq.com", new Date()); userImplXML.register(user); }
public class UserServiceXML { //Service層就是調(diào)用Dao層的方法,我們就直接在類中創(chuàng)建Dao層的對(duì)象了 UserDao userImplXML = new UserImplXML(); public void register(User user) { userImplXML.register(user); } public void login(String username, String password) { userImplXML.find(username, password); } }
public class RegisterUIServlet extends javax.servlet.http.HttpServlet { protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { //直接跳轉(zhuǎn)到顯示注冊界面的JSP request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response); } protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { this.doPost(request, response); } }
<h1>歡迎來到注冊界面!</h1><%--提交給處理注冊的處理Servlet--%><form method="post" action="${pageContext.request.contextPath}/RegisterServlet"> <table> <%--對(duì)于id來講,是服務(wù)器分配的!不需要用戶自己輸入--%> <tr> <td>用戶名</td> <td> <input type="text " name="username"> </td> </tr> <tr> <td>密碼</td> <td> <input type="text" name="password"> </td> </tr> <tr> <td>確認(rèn)密碼</td> <td> <input type="text" name="password"> </td> </tr> <tr> <td>郵箱</td> <td> <input type="text" name="email"> </td> </tr> <tr> <td>生日</td> <td> <input type="text " name="birethday"> </td> </tr> <tr> <td> <input type="submit" value="提交"> </td> <td> <input type="reset" value="重置!"> </td> </tr> </table></form>
//首先要接受Parameter的參數(shù),封裝到User里面去 String username = request.getParameter("username"); String password = request.getParameter("password"); //......如果參數(shù)過多,我們就要寫好多好多類似的代碼了...
/* * 將Parameter參數(shù)的數(shù)據(jù)封裝到Bean中,為了外邊不用強(qiáng)轉(zhuǎn),這里就使用泛型了! * * @request 由于要獲取的是Parameter參數(shù)的信息,所以需要有request對(duì)象 * @tClass 本身是不知道封裝什么對(duì)象的,所以用class * * */ public static <T> T request2Bean(HttpServletRequest httpServletRequest, Class<T> tClass) { try { //創(chuàng)建tClass的對(duì)象 T bean = tClass.newInstance(); //獲取得到Parameter中全部的參數(shù)的名字 Enumeration enumeration = httpServletRequest.getParameterNames(); //遍歷上邊獲取得到的集合 while (enumeration.hasMoreElements()) { //獲取得到每一個(gè)帶過來參數(shù)的名字 String name = (String) enumeration.nextElement(); //獲取得到值 String value = httpServletRequest.getParameter(name); //把數(shù)據(jù)封裝到Bean對(duì)象中 BeanUtils.setProperty(bean, name, value); } return bean; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("封裝數(shù)據(jù)到Bean對(duì)象中出錯(cuò)了!"); } }
//日期轉(zhuǎn)換器 ConvertUtils.register(new DateLocaleConverter(), Date.class);
/*生成ID*/ public static int makeId() { return Integer.parseInt(UUID.randomUUID().toString()); }
User user = WebUtils.request2Bean(request, User.class); user.setId(WebUtils.makeId()); //調(diào)用service層的注冊方法,實(shí)現(xiàn)注冊 ServiceBussiness serviceBussiness = new UserServiceXML(); serviceBussiness.register(user);
public class FormBean { //表單提交過來的數(shù)據(jù)全都是String類型的,birthday也不例外! private String username; private String password; private String password2; private String email; private String birthday; /*用于判斷表單提交過來的數(shù)據(jù)是否合法*/ public boolean validate() { return false; } //......各種setter、getter方法}
public boolean validate() { //用戶名不能為空,并且要是3-8的字符 abcdABcd if (this.username == null || this.username.trim().equals("")) { return false; } else { if (!this.username.matches("[a-zA-Z]{3,8}")) { return false; } } //密碼不能為空,并且要是3-8的數(shù)字 if (this.password == null || this.password.trim().equals("")) { return false; } else { if (!this.password.matches("//d{3,8}")) { return false; } } //兩次密碼要一致 if (this.password2 != null && !this.password2.trim().equals("")) { if (!this.password2.equals(this.password)) { return false; } } //郵箱可以為空,如果為空就必須合法 if (this.email != null && !this.email.trim().equals("")) { if (!this.email.matches("//w+@//w+(//.//w+)+")) { System.out.println("郵箱錯(cuò)誤了!"); return false; } } //日期可以為空,如果為空就必須合法 if (this.birthday != null && !this.birthday.trim().equals("")) { try { DateLocaleConverter dateLocaleConverter = new DateLocaleConverter(); dateLocaleConverter.convert(this.birthday); } catch (Exception e) { System.out.println("日期錯(cuò)誤了!"); return false; } } //如果上面都沒有執(zhí)行,那么就是合法的了,返回true return true; }
//將表單的數(shù)據(jù)封裝到formBean中 FormBean formBean = WebUtils.request2Bean(request, FormBean.class); //驗(yàn)證表單的數(shù)據(jù)是否合法,如果不合法就跳轉(zhuǎn)回去注冊的頁面 if(formBean.validate()==false){ request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response); return; } try { //將表單的數(shù)據(jù)封裝到User對(duì)象中 User user = WebUtils.request2Bean(request, User.class); user.setId(WebUtils.makeId()); //調(diào)用service層的注冊方法,實(shí)現(xiàn)注冊 ServiceBussiness serviceBussiness = new UserServiceXML(); serviceBussiness.register(user); } catch (Exception e) { e.printStackTrace(); }
if (user.getEmail() == null) { newElement.addAttribute("email", ""); } else { newElement.addAttribute("email", user.getEmail()); } //如果不是空才格式化信息 if (user.getBirthday() != null) { //日期返回的是指定格式的日期 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String date = simpleDateFormat.format(user.getBirthday()); newElement.addAttribute("birthday", date); } else { newElement.addAttribute("birthday", ""); }
解決辦法:public static <T> T request2Bean(HttpServletRequest httpServletRequest, Class<T> tClass) { try { //創(chuàng)建tClass的對(duì)象 T bean = tClass.newInstance(); //獲取得到Parameter中全部的參數(shù)的名字 Enumeration enumeration = httpServletRequest.getParameterNames(); //日期轉(zhuǎn)換器 ConvertUtils.register(new DateLocaleConverter(), Date.class); //遍歷上邊獲取得到的集合 while (enumeration.hasMoreElements()) { //獲取得到每一個(gè)帶過來參數(shù)的名字 String name = (String) enumeration.nextElement(); //獲取得到值 String value = httpServletRequest.getParameter(name); //如果Parameter中的數(shù)據(jù)為"",那么我就不封裝到User對(duì)象里邊去!執(zhí)行下一次循環(huán) if (value == "") { continue; } else { //把數(shù)據(jù)封裝到Bean對(duì)象中 BeanUtils.setProperty(bean, name, value); } } return bean; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("封裝數(shù)據(jù)到Bean對(duì)象中出錯(cuò)了!"); } }
//將表單的數(shù)據(jù)封裝到formBean中 FormBean formBean = WebUtils.request2Bean(request, FormBean.class); //驗(yàn)證表單的數(shù)據(jù)是否合法,如果不合法就跳轉(zhuǎn)回去注冊的頁面 if(formBean.validate()==false){ request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response); return; } try { //這是第一種-------------------------- /*User user = new User(); user.setId(WebUtils.makeId()); BeanUtils.copyProperties(user,formBean);*/ //------------------------------------------ //這是第二種 User user1 = WebUtils.request2Bean(request,User.class); user1.setId(WebUtils.makeId()); //----------------------------------- //調(diào)用service層的注冊方法,實(shí)現(xiàn)注冊 ServiceBussiness serviceBussiness = new UserServiceXML(); serviceBussiness.register(user1); } catch (Exception e) { e.printStackTrace(); }
現(xiàn)在還有問題,如果我填寫信息不合法,提交給服務(wù)器驗(yàn)證以后,服務(wù)器應(yīng)該告訴用戶哪個(gè)信息不合法,而不是直接把跳轉(zhuǎn)回注冊界面,把所有的信息全部清空,讓用戶重新填寫!//表單提交過來的數(shù)據(jù)全都是String類型的,birthday也不例外! private String username; private String password; private String password2; private String email; private String birthday; //記錄錯(cuò)誤的信息 private HashMap<String, String> error = new HashMap<>(); /*用于判斷表單提交過來的數(shù)據(jù)是否合法*/ public boolean validate() { //用戶名不能為空,并且要是3-8的字符 abcdABcd if (this.username == null || this.username.trim().equals("")) { error.put("username", "用戶名不能為空,并且要是3-8的字符"); return false; } else { if (!this.username.matches("[a-zA-Z]{3,8}")) { error.put("username", "用戶名不能為空,并且要是3-8的字符"); return false; } } //密碼不能為空,并且要是3-8的數(shù)字 if (this.password == null || this.password.trim().equals("")) { error.put("password", "密碼不能為空,并且要是3-8的數(shù)字"); return false; } else { if (!this.password.matches("//d{3,8}")) { error.put("password", "密碼不能為空,并且要是3-8的數(shù)字"); return false; } } //兩次密碼要一致 if (this.password2 != null && !this.password2.trim().equals("")) { if (!this.password2.equals(this.password)) { error.put("password2", "兩次密碼要一致"); return false; } } //郵箱可以為空,如果為空就必須合法 if (this.email != null && !this.email.trim().equals("")) { if (!this.email.matches("//w+@//w+(//.//w+)+")) { error.put("email", "郵箱不合法!"); return false; } } //日期可以為空,如果為空就必須合法 if (this.birthday != null && !this.birthday.trim().equals("")) { try { DateLocaleConverter dateLocaleConverter = new DateLocaleConverter(); dateLocaleConverter.convert(this.birthday); } catch (Exception e) { error.put("birthday", "日期不合法!"); return false; } } //如果上面都沒有執(zhí)行,那么就是合法的了,返回true return true; } //.....各種的setter和getter
//驗(yàn)證表單的數(shù)據(jù)是否合法,如果不合法就跳轉(zhuǎn)回去注冊的頁面 if(formBean.validate()==false){ //在跳轉(zhuǎn)之前,把formbean對(duì)象傳遞給注冊頁面 request.setAttribute("formbean", formBean); request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response); return; }
//直接跳轉(zhuǎn)到登陸界面 request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
<h1>這是登陸界面</h1><form action="${pageContext.request.contextPath}/LoginServlet" method="post"> <table> <tr> <td>用戶名</td> <td><input type="text" name="username"></td> </tr> <tr> <td>密碼</td> <td><input type="password" name="password"></td> </tr> <tr> <td><input type="submit" value="提交"></td> <td><input type="reset" name="重置"></td> </tr> </table></form>
//獲取提交過來的數(shù)據(jù) String username = request.getParameter("username"); String password = request.getParameter("password"); //調(diào)用service層的方法,去查詢數(shù)據(jù)庫(XML)是否有該條記錄 try { ServiceBussiness serviceBussiness = new UserServiceXML(); User user = serviceBussiness.login(username, password); if (user == null) { request.setAttribute("message", "用戶名或密碼是錯(cuò)的"); } else { request.setAttribute("message","登陸成功"); } } catch (Exception e) { e.printStackTrace(); request.setAttribute("message","登陸失敗咯"); } request.getRequestDispatcher("/message.jsp").forward(request, response);
<h1>這是首頁!</h1> <a href="${pageContext.request.contextPath}/LoginUIServlet">登陸</a> <a href="${pageContext.request.contextPath}/RegisterUIServlet">注冊</a> </body>
如果文章有錯(cuò)的地方歡迎指正,大家互相交流。習(xí)慣在微信看技術(shù)文章的同學(xué),可以關(guān)注微信公眾號(hào):Java3y
關(guān)鍵詞:模式
客戶&案例
營銷資訊
關(guān)于我們
微信公眾號(hào)
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。