一 Java Web开发模式的变迁
1 最初的Java web服务器端编程技术是Servlet,利用Servlet就可以开发出一个Web应用程序。
2 为了解决Servlet缺陷,SUN推出了JSP技术。但是开发人员又走向了另一个极端就是完全放弃了Servlet。
在JSP页面混合使用HTML标记和java代码编写的脚本元素标记来开发Web程序。采用这种方法虽然可以编写JSP页面变得简单,直观,然而,他只适合于业务流程简单,系统规模较小的应用系统。
如果系统较大的话,就会出现两个严重的缺点:
1) 页面严重缺乏可读性。
2) 没有将页面表现和业务逻辑实现分开,使维护难度增加了。
在JSP中使用JavaBean可以实现页面与逻辑业务分开。
3 SUN公司将在Web应用开发中使用JSP+JavaBean技术。===JSP模式1 (适用于规模较小,业务逻辑简单的web应用开发)。
4 SUN在java web开发中引入了MVC架构模式,利用Servlet,JSP,JavaBean技术(讲servlet作为MVC架构模式中的控制器,JSP作为视图,javabean作为模型)===JSP模式2()这也不是绝对完美的。
二 在JSP中使用JavaBean
一个标准的JavaBean组件具有以下几个特征
1 package com.cy.bean; 2 3 import java.io.Serializable; 4 5 /*JavaBean 类必须是一个公共类,并将其访问属性设置为 public。*/ 6 /*JavaBean应该是可序列化(serializable)的,即实现java.io.Serializable 接口 */ 7 8 public class User implements Serializable { 9 private static final long serialVersionUID = 1L; 10 /* 一个JavaBean类不应有公共实例变量,类变量都为private */ 11 private int id; 12 private String name; 13 private String pwd; 14 private int postion; 15 16 /* JavaBean 类必须有一个空的构造函数,(系统会默认一个无参构造器,如果没有其他的构造器) */ 17 public User() { 18 super(); 19 } 20 21 /* 要访问这些类变量,应该通过一组存取方法(getXxx 和 setXxx)来访问, */ 22 public int getId() { 23 return id; 24 } 25 26 public void setId(int id) { 27 this.id = id; 28 } 29 30 public String getName() { 31 return name; 32 } 33 34 public void setName(String name) { 35 this.name = name; 36 } 37 38 public String getPwd() { 39 return pwd; 40 } 41 42 public void setPwd(String pwd) { 43 this.pwd = pwd; 44 } 45 46 public int getPostion() { 47 return postion; 48 } 49 50 public void setPostion(int postion) { 51 this.postion = postion; 52 } 53 54 }
为了在JSP页面中使用JavaBean,SUN在JSP规范中提供了三种标准动作。
<jsp:useBean id=“beanName” //变量名 scope=“page|request|session|application” //作用范围 class=“className” //类全路径/>
1 <jsp:useBean id="user" class="com.cy.bean.User" scope="request"></jsp:useBean>
id:代表bean的引用名,id在一个页面中必须是一个唯一的值;User user = new User();
scope: 指定JavaBean生存的作用域
class: 指定JavaBean的包名及类名
type:id的引用的数据类型,默认情况下,它与class的类型相同。
<jsp:getProperty name="beanname" property="propertyname"/>
1 <jsp:getProperty property="name" name="user"/>
property: 指的是返回JavaBean中的相对应的属性名
name: <jsp:useBean>动作中指定的id名,
<jsp:setProperty name="BeanName" property="属性名" param="参数名"/>
<jsp:setProperty name="BeanName" property="属性名" value="属性值" />
<jsp:setProperty name="BeanName" property="*"/>
1 ----.jsp 2 <jsp:setProperty property="name" name="user" param="username"/> 3 <jsp:setProperty property="pwd" name="user" param="pwd"/> 4 5 6 ----.html 7 username:<input type="text" name="username"/> 8 pwd :<input type ="password" name="pwd"/>
name: bean的名称
property:JavaBean相对应的属性
value设置属性的值
param将property指定的属性名的值设置为一个请求参数的值
property="*"用来设置所有与所得到的参数同名的属性值
三 JSP开发模式1
1 package com.cy.bean; 2 3 import java.io.Serializable; 4 5 6 7 public class UserBean implements Serializable { 8 private static final long serialVersionUID = 1L; 9 10 private String name; 11 private String pwd; 12 13 public UserBean () { 14 super(); 15 } 16 17 18 public String getName() { 19 return name; 20 } 21 22 public void setName(String name) { 23 this.name = name; 24 } 25 26 public String getPwd() { 27 return pwd; 28 } 29 30 public void setPwd(String pwd) { 31 this.pwd = pwd; 32 } 33 34 35 }
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>login.html</title> 5 6 <meta name="keywords" content="keyword1,keyword2,keyword3"> 7 <meta name="description" content="this is my page"> 8 <meta name="content-type" content="text/html; charset=UTF-8"> 9 10 <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> 11 12 </head> 13 14 <body> 15 <form action="/java_web/CheckUser.jsp" method="post"> 16 username:<input type="text" name="username"/> 17 pwd :<input type ="password" name="pwd"/> 18 <input type="submit" value="submit"/> 19 </form> 20 </body> 21 </html>
1 package com.cy.bean; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.sql.Statement; 8 9 public class CheckUserBean { 10 11 public boolean checkUser(User user) { 12 13 String name = user.getName(); 14 String pwd = user.getPwd(); 15 Connection conn = null; 16 Statement st = null; 17 ResultSet rs = null; 18 String url = "jdbc:mysql://localhost:3306/demo"; 19 String user1 = "root"; 20 String password = "1234"; 21 String sql = "select * from t_user where user_name='" + name 22 + "' and user_password='" + pwd + "'"; 23 try { 24 Class.forName("com.mysql.jdbc.Driver"); 25 conn = DriverManager.getConnection(url, user1, password); 26 st = conn.createStatement(); 27 rs = st.executeQuery(sql); 28 29 if (rs.next()) { 30 return true; 31 } 32 } catch (Exception e) { 33 e.printStackTrace(); 34 } finally { 35 try { 36 rs.close(); 37 st.close(); 38 conn.close(); 39 } catch (SQLException e) { 40 e.printStackTrace(); 41 } 42 } 43 44 return false; 45 46 } 47 }
1 <%@ page language="java" import="java.util.*,com.cy.bean.*" pageEncoding="utf-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'CheckUser.jsp' starting page</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 23 </head> 24 25 <body> 26 <%CheckUserBean cub=new CheckUserBean(); %> 27 <jsp:useBean id="user" class="com.cy.bean.User" scope="request"></jsp:useBean> 28 <jsp:setProperty property="*" name="user"/> 29 <%if(cub.checkUser(user)) {%> 30 <jsp:forward page="success.jsp"></jsp:forward> 31 <%}else{%> 32 <jsp:forward page="fail.jsp"></jsp:forward> 33 <%} %> 34 </body> 35 </html>
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'success.jsp' starting page</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 23 </head> 24 25 <body> 26 <jsp:useBean id="user" class="com.cy.bean.User" scope="request"></jsp:useBean> 27 28 欢迎你:<jsp:getProperty property="name" name="user"/> 29 </body> 30 </html>
1 package com.cy.bean; 2 3 import java.io.Serializable; 4 5 public class User implements Serializable { 6 7 private String name; 8 private String pwd; 9 10 public String getName() { 11 return name; 12 } 13 14 public void setName(String name) { 15 this.name = name; 16 } 17 18 public String getPwd() { 19 return pwd; 20 } 21 22 public void setPwd(String pwd) { 23 this.pwd = pwd; 24 } 25 26 }
1 package com.cy.servlet; 2 3 import java.io.IOException; 4 import java.sql.Connection; 5 import java.sql.DriverManager; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 import java.sql.Statement; 9 10 import javax.servlet.ServletException; 11 import javax.servlet.http.HttpServlet; 12 import javax.servlet.http.HttpServletRequest; 13 import javax.servlet.http.HttpServletResponse; 14 15 import com.cy.bean.User; 16 // 需要连接数据库 17 public class LoginServlet extends HttpServlet{ 18 19 @Override 20 protected void doGet(HttpServletRequest req, HttpServletResponse resp) 21 throws ServletException, IOException { 22 req.setCharacterEncoding("utf-8"); 23 resp.setCharacterEncoding("utf-8"); 24 resp.setContentType("text/html;charset=utf-8"); 25 26 /*使用一个Servlet来处理请求 */ 27 String name = req.getParameter("username"); 28 String pwd = req.getParameter("pwd"); 29 30 31 32 Connection conn = null; 33 Statement st = null; 34 ResultSet rs = null; 35 String url="jdbc:mysql://localhost:3306/demo"; 36 String user = "root"; 37 String password ="1234"; 38 String sql = "select * from t_user where user_name='"+name+"' and user_password='"+pwd+"'"; 39 40 //System.out.println(sql); 41 try { 42 Class.forName("com.mysql.jdbc.Driver"); 43 conn = DriverManager.getConnection(url,user,password); 44 st = conn.createStatement(); 45 rs = st.executeQuery(sql); 46 if(rs.next()){ 47 48 /* 在Servlet中填充Bean*/ 49 User u = new User(); 50 u.setPwd(pwd); 51 u.setUsername(name); 52 53 54 /*在Servlet中,将Bean存储到请求、会话或者Servlet上下文中*/ 55 req.getSession().setAttribute("user", u); 56 57 /*将请求转发到JSP页面*/ 58 req.getRequestDispatcher("/welcome.jsp").forward(req, resp); 59 }else{ 60 req.getRequestDispatcher("/index.jsp").forward(req, resp); 61 } 62 } catch (Exception e) { 63 e.printStackTrace(); 64 }finally{ 65 try { 66 rs.close(); 67 st.close(); 68 conn.close(); 69 } catch (SQLException e) { 70 e.printStackTrace(); 71 } 72 } 73 74 } 75 76 @Override 77 protected void doPost(HttpServletRequest req, HttpServletResponse resp) 78 throws ServletException, IOException { 79 doGet(req, resp); 80 } 81 82 }
这里还写了一个简单的util
1 package com.cy.util; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.sql.Statement; 8 9 public class DBUtil { 10 private static String url = "jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf-8"; 11 private static String user = "root"; 12 private static String pwd = "1234"; 13 private DBUtil(){}; 14 static{ 15 try { 16 Class.forName("com.mysql.jdbc.Driver"); 17 } catch (ClassNotFoundException e) { 18 e.printStackTrace(); 19 } 20 21 } 22 23 public static Connection getConn() throws SQLException{ 24 return DriverManager.getConnection(url,user,pwd); 25 } 26 27 public static void closeRe(Connection conn,Statement st,ResultSet rs){ 28 if(rs!=null){ 29 try { 30 rs.close(); 31 } catch (SQLException e) { 32 e.printStackTrace(); 33 }finally{ 34 if(st!=null){ 35 try { 36 st.close(); 37 } catch (SQLException e) { 38 e.printStackTrace(); 39 }finally{ 40 if(conn!=null){ 41 try { 42 conn.close(); 43 } catch (SQLException e) { 44 e.printStackTrace(); 45 } 46 } 47 } 48 } 49 } 50 } 51 } 52 53 public static void closeRe(Connection conn,Statement st) { 54 if(st!=null){ 55 try { 56 st.close(); 57 } catch (SQLException e) { 58 e.printStackTrace(); 59 }finally{ 60 if(conn!=null){ 61 try { 62 conn.close(); 63 } catch (SQLException e) { 64 e.printStackTrace(); 65 } 66 } 67 } 68 } 69 70 } 71 72 }
在web.xml配置Servlet
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 6 <display-name></display-name> 7 <welcome-file-list> 8 <welcome-file>index.jsp</welcome-file> 9 </welcome-file-list> 10 11 <servlet> 12 <servlet-name>login</servlet-name> 13 <servlet-class>com.cy.servlet.LoginServlet</servlet-class> 14 </servlet> 15 16 <servlet-mapping> 17 <servlet-name>login</servlet-name> 18 <url-pattern>/login</url-pattern> 19 </servlet-mapping> 20 21 </web-app>
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'welcome.jsp' starting page</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 23 </head> 24 25 <body> 26 welcome页码显示数据 27 <jsp:useBean id="user" type="com.cy.bean.User" scope="session"></jsp:useBean> 28 <p>欢迎你:<jsp:getProperty property="name" name="user"></jsp:getProperty></p> 29 </body> 30 </html>
1 package com.cy.servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 import com.cy.bean.User; 11 12 public class DemoServlet extends HttpServlet { 13 14 @Override 15 protected void doGet(HttpServletRequest req, HttpServletResponse resp) 16 throws ServletException, IOException { 17 req.setCharacterEncoding("utf-8"); 18 String name = req.getParameter("username"); 19 String pwd = req.getParameter("pwd"); 20 21 User user = new User(); 22 user.setPwd(pwd); 23 user.setUsername(name); 24 req.getSession().setAttribute("user1", user); 25 String uri = req.getRequestURI(); 26 req.getRequestDispatcher(uri).forward(req, resp); 27 } 28 29 @Override 30 protected void doPost(HttpServletRequest req, HttpServletResponse resp) 31 throws ServletException, IOException { 32 doGet(req, resp); 33 } 34 35 }
1 package com.cy.filter; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 import javax.servlet.http.HttpServletRequest; 12 13 import com.lovo.bean.User; 14 15 public class DemoFilter implements Filter { 16 17 public void destroy() { 18 // TODO Auto-generated method stub 19 20 } 21 22 public void doFilter(ServletRequest arg0, ServletResponse arg1, 23 FilterChain arg2) throws IOException, ServletException { 24 HttpServletRequest req = (HttpServletRequest)arg0; 25 User user = new User(); 26 String name = req.getParameter("username"); 27 String pwd = req.getParameter("pwd"); 28 user.setPwd(pwd); 29 user.setUsername(name); 30 req.getSession().setAttribute("user", user); 31 arg2.doFilter(req, arg1); 32 } 33 34 public void init(FilterConfig arg0) throws ServletException { 35 // TODO Auto-generated method stub 36 37 } 38 39 }
在web.xml中配置部署Filter,servlet
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 6 <display-name></display-name> 7 <welcome-file-list> 8 <welcome-file>index.jsp</welcome-file> 9 </welcome-file-list> 10 11 <filter> 12 <filter-name>jsp</filter-name> 13 <filter-class>com.cy.filter.DemoFilter</filter-class> 14 </filter> 15 <filter-mapping> 16 <filter-name>jsp</filter-name> 17 <url-pattern>/*</url-pattern> 18 </filter-mapping> 19 30 31 </web-app>
小结:
引自:https://www.cnblogs.com/hellokitty1/p/4954376.html