JSP——MVC模式+Servlet生命周期
设计模式MVC模式
模型MODEL操作数据库的增删改查——javaBean
视图VIEW显示数据——JSP
控制器CONTROLLER响应用户的——servlet
Model(模型),是程序的主体部分,主要包含业务数据和业务逻辑。在模型层,还会涉及到用户发布的服务,在服务中会根据不同的业务需求,更新业务模型中的数据。
View(视图),是程序呈现给用户的部分,是用户和程序交互的接口,用户会根据具体的业务需求,在View视图层输入自己特定的业务数据,并通过界面的事件交互,将对应的输入参数提交给后台控制器进行处理。
Controller(控制器),Controller是用来处理用户输入数据,已经更新业务模型的部分。控制器中接收了用户与界面交互时传递过来的数据,并根据数据业务逻辑来执行服务的调用和更新业务模型的数据和状态。

模型:代表应用程序状态和业务逻辑
视图:提供可交换的客户界面,向用户显示模型数据
控制器:根据客户的请求来操纵模型,并且把结果经由视图展现给客户
MVC设计模式的优点:代码的重用性、有利于开发的分工、各司其职互不干涉。


Servlet生命周期
Servlet是一个JAVA程序,是在服务器上运行以处理用户操作信息。
extendsHTTPServlet
init()
service()doget()dopost()






<%@page import="java.net.URLDecoder"%> <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% request.setCharacterEncoding("utf-8"); String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; if(request.getParameter("zyf")!=null){ String zyf= URLDecoder.decode(request.getParameter("zyf"),"utf-8"); out.print(zyf); } %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'login.jsp' starting page</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="servlet/LoginServlet" method="post"> 用户名:<input type="text" name="name"><br> 密码: <input type="text" name="pwd"><br> <input type="submit" value="提交登录" ><br> </body> </html>Main.jsp
<%@page import="java.net.URLDecoder"%> <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% request.setCharacterEncoding("utf-8"); String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; String zyf = "11"; if (request.getParameter("zyf") != null) { zyf = URLDecoder.decode(request.getParameter("zyf"), "utf-8"); } %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'main.jsp' starting page</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"> --> <link rel="stylesheet" href="css/icon.css"></link> <link rel="stylesheet" href="css/easyui.css"></link> <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script> <script type="text/javascript" src="js/jquery.easyui.min.js"></script> <script type="text/javascript"> $(function() { $('#dg').datagrid({ title:'用户列表', method:'GET', url:'servlet/UserServlet', iconCls:'icon-ok', fitColumns:true, pagination:true, striped:true, nowrap:true, singleSelect:true, rownumbers:true, collapsible:true,//是否可折叠的 pageSize: 1,//每页显示的记录条数,默认为10 pageList: [1,2],//可以设置每页记录条数的列表 fitColumns : true, autoRowHeight:true, striped:true, nowrap:true, pagination:true, toolbar : [ { text:'查询', iconCls : 'icon-search', handler : function() { $('#dg').datagrid('reload'); } }, '-', { text:'修改', iconCls : 'icon-edit', handler : function() { alert('帮助按钮') } }, '-', { text:'增加', iconCls : 'icon-add', handler : function() { alert('帮助按钮') } }, '-', { text:'删除', iconCls : 'icon-remove', handler : function() { alert('帮助按钮') } } ], columns : [ [ { field : 'cc', checkbox:true, width : 100, }, { field : 'userName', title : '用户名', width : 100, align:'center' }, { field : 'pwd', title : '密码', width : 100 }, { field : 'displayName', title : '级别', width : 100, align : 'right' } ] ] }); }) </script> </head> <body> <%=zyf%> This is my main.JSP page. <br> ${sessionScope.user.displayName} <table class="easyui-datagrid" id="dg"> </table> </body> </html>
package com.jredu.web.servlet; import java.io.IOException; import java.io.PrintWriter; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.jredu.web.dao.UserDao; import com.jredu.web.entity.User; public class LoginServlet extends HttpServlet { /** * Constructor of the object. */ public LoginServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String name=request.getParameter("name"); String pwd=request.getParameter("pwd"); String where=" where user_name ='"+name+"' and pwd='"+pwd+"'" ; String namepwd=" where user_name='"+name+"' and pwd='"+pwd+"'"; User user=new User(); UserDao userdao=new UserDao(); user=userdao.selectwhere(where); response.setContentType("text/html"); PrintWriter out = response.getWriter(); //if(userdao.selectwhere2(where)){ if(user!=null){ out.println("登录成功"); System.out.println(user.getDisplayName()); out.println(user.getDisplayName()); HttpSession session=request.getSession(); User users=(User)session.getAttribute("user"); //if(users==null){ session.setAttribute("user", user); //} response.sendRedirect("../login/main.jsp?zyf="+URLEncoder.encode(user.getDisplayName(), "utf-8")); }else{ out.println("登录失败"); response.sendRedirect("../login/login.jsp?zyf="+URLEncoder.encode("用户密码错误", "utf-8")); } out.println("用户名密码"+namepwd); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", 测试登录using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
package com.jredu.web.servlet; 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 net.sf.json.JSONArray; import com.jredu.web.dao.UserDao; import com.jredu.web.entity.User; import java.util.List; public class UserServlet extends HttpServlet { /** * Constructor of the object. */ public UserServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("textml;charset=utf-8"); UserDao userDao = new UserDao(); List<User> list = userDao.selectAll(); //变成单个对象 //JSONObject jo=JSONObject.fromObject(user); //把list变成JSONArray JSONArray ja = JSONArray.fromObject(list); PrintWriter out = response.getWriter(); System.out.println(ja.toString()); out.print(ja.toString()); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
package com.jredu.web.entity; public class User { private String userName; private String pwd; private String displayName; public User(){} public User(String userName, String pwd, String displayName) { super(); this.userName = userName; this.pwd = pwd; this.displayName = displayName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } }
package com.jredu.web.db; import java.sql.*; public class DBConnection { private static Connection con=null; //mysql驱动mingz private static String driverName="com.mysql.jdbc.Driver"; //数据库用户名 private static String userName="root"; //密码 private static String userPasswd = "ffffff"; //数据库名 private static String dbName = "shcoolapp"; //联结字符串 private static String url = "jdbc:mysql://localhost/" + dbName + "?user="+ userName + "&password=" + userPasswd + "&useUnicode=true&characterEncoding=gbk"; public static Connection getConnection(){ try { Class.forName(driverName); con =DriverManager.getConnection(url); } catch (ClassNotFoundException e) { // TODO: handle exception e.printStackTrace(); }catch(SQLException e){ e.printStackTrace(); } return con; } public static void closeConnection(){ if(con!=null){ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package com.jredu.web.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.jredu.web.db.DBConnection; import com.jredu.web.entity.User; public class UserDao { public List<User> selectAll(){ Connection con=DBConnection.getConnection(); Statement stmt; List<User> list=new ArrayList<User>(); try { stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("SELECT * FROM users"); while(rs.next()){ User user=new User(); user.setUserName(rs.getString("user_name")); user.setPwd(rs.getString("pwd")); user.setDisplayName(rs.getString("display_name")); list.add(user); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ DBConnection.closeConnection(); } return list; } public User selectwhere(String whereOption){ Connection con=DBConnection.getConnection(); Statement stmt; User user=null; try { stmt=con.createStatement(); String sql=("SELECT * FROM users"); if(!whereOption.equals("")){ sql+=whereOption; } ResultSet rs=stmt.executeQuery(sql); if(rs.next()){ user=new User(); user.setUserName(rs.getString("user_name")); user.setPwd(rs.getString("pwd")); user.setDisplayName(rs.getString("display_name")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ DBConnection.closeConnection(); } return user; } public boolean selectwhere2(String whereOption2){ Connection con=DBConnection.getConnection(); Statement stmt; User user=null; try { stmt=con.createStatement(); String sql=("SELECT * FROM users"); if(!whereOption2.equals("")){ sql+=whereOption2; } ResultSet rs=stmt.executeQuery(sql); if(rs.next()){ user=new User(); user.setUserName(rs.getString("user_name")); user.setPwd(rs.getString("pwd")); user.setDisplayName(rs.getString("display_name")); return true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ DBConnection.closeConnection(); } return false; } }