编程开发 购物 网址 游戏 小说 歌词 快照 开发 股票 美女 新闻 笑话 | 汉字 软件 日历 阅读 下载 图书馆 编程 China
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
移动开发 架构设计 编程语言 互联网 开发经验 Web前端 开发总结
开发杂谈 系统运维 研发管理 数据库 云 计 算 Java开发
VC(MFC) Delphi VB C++(C语言) C++ Builder 其它开发语言 云计算 Java开发 .Net开发 IOS开发 Android开发 PHP语言 JavaScript
ASP语言 HTML(CSS) HTML5 Apache MSSQL数据库 Oracle数据库 PowerBuilder Informatica 其它数据库 硬件及嵌入式开发 Linux开发资料
  编程开发知识库 -> Web前端 -> JSP——MVC模式+Servlet生命周期 -> 正文阅读
 

[Web前端]JSP——MVC模式+Servlet生命周期[第1页]

JSP——MVC模式+Servlet生命周期


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

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


Servlet生命周期
Servlet 是一个JAVA程序,是在服务器上运行以处理用户操作信息。
extends HTTPServlet
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;
	}
		
}

  Web前端 最新文章
echarts莫名缩小,并且宽度不能更改,生成时
JAVA后台 关于如何从后台传递信息在jsp前端
HTTP协议(二)
阿里云服务器的域名解析解决方案
live-server的安装与使用
HTML播放视频(兼容IE低版本)
windows下配置nginx+php环境
Chorme 开代理后无法打开jsp页面的问题
分布式任务调度平台XXL
作用域
上一篇文章      下一篇文章      查看所有文章
加:2016-10-21 16:23:11  更:2016-10-21 16:23:51 
VC(MFC) Delphi VB C++(C语言) C++ Builder 其它开发语言 云计算 Java开发 .Net开发 IOS开发 Android开发 PHP语言 JavaScript
ASP语言 HTML(CSS) HTML5 Apache MSSQL数据库 Oracle数据库 PowerBuilder Informatica 其它数据库 硬件及嵌入式开发 Linux开发资料
360图书馆 软件开发资料 文字转语音 购物精选 软件下载 新闻资讯 小游戏 Chinese Culture 股票 三丰软件 开发 中国文化 网文精选 阅读网 看图 日历 万年历 2018年9日历
2018-9-21 20:07:51
多播视频美女直播
↓电视,电影,美女直播,迅雷资源↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  编程开发知识库