MVC的第一个实例

J2EE
J2EE API包含以下几个部分:

Jsp(java server page)接口:优秀的jsp接口易于维护,不负责业务逻辑的处理(可以交给JavaBean和ejb完成)
JNDI(java naming and directory interface)接口:为访问目录服务提供支持
还有[/size]Java事务接口(jta),数据库连接(jdbc api),远程方法调用(rmi),消息服务接口(jms)
这些API和3层架构的关系如下图:

MVC的第一个实例

在myeclipse中建立一个web工程MVCFirst。

模型层
/*
 *@(#){file_name} Aug 3, 2010
 *
 *Copyright 2010 Zhoujunmei.
 */
package javabean;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class User {
	private String userName;
	private String userAddress;
	private String userSex;
	private Connection conn;
	private static final String SQL = "select username,usersex,useraddress from user where username=?";

	public User() { // 构造函数进行jdbc数据库连接
		try {
			Class.forName("org.gjt.mm.mysql.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			conn = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/login", "root", "root");

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void getDBUser(String userName) {
		PreparedStatement selectQuery = null;
		try {
			selectQuery = conn.prepareStatement(SQL);
			selectQuery.setString(1, userName);
			ResultSet rs = selectQuery.executeQuery();

			while (rs.next()) {
				this.setUserName(rs.getString("username"));
				this.setUserSex(rs.getString("usersex"));
				this.setUserAddress(rs.getString("useraddress"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserAddress() {
		return userAddress;
	}

	public void setUserAddress(String userAddress) {
		this.userAddress = userAddress;
	}

	public String getUserSex() {
		return userSex;
	}

	public void setUserSex(String userSex) {
		this.userSex = userSex;
	}

}


使用的是mysql数据库,需要导入数据库驱动包,mysql中建立一个login数据库,建立user数据表

用户输入界面的jsp代码:Usernameinput.jsp
    <%@ page language="java" contentType="text/html;charset=gb2312"
	pageEncoding="gb2312"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>username input</title>
	</head>
	<body bgcolor="#ffffff">
	<!-- 我们约定本页面将用户输入提交的action所指定的servlet中去,这里就是视图和控制器交互的所在 -->
		<form method="post" action="UserServlet" name="form1">
			<br>
			Username:
			<br>
			<input type="text" size="24" name="username" value="">
			<p>
				<input type="submit" value="提交" name="submit">
				<input type="reset" value="重置" name="reset">
		</form>
	</body>
</html>


返回信息的界面jsp代码:Usernameresult.jsp
 <%@ page language="java" contentType="text/html;charset=gb2312"
	pageEncoding="gb2312"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>username result</title>
	</head>
	<body bgcolor="#ffffff">
	<!-- 接收控制器层的返回信息,在servlet控制器中的定义3个返回信息会以userName,userSex标识 -->
		<h1>username:</h1><%=request.getAttribute("userName") %>
		<h2>usersex:</h2><%=request.getAttribute("userSex") %>
		<h3>useraddress:</h3><%=request.getAttribute("userAddress") %>
	</body>
</html>



控制器代码:
在myeclipse中新建一个servlet,doPost和doGet代码如下:
doPost和doGet根本区别是doGet请求时url会包含传入的参数

package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javabean.User;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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 {
//		<input type="text" size="24" name="username" value="">
	String username = request.getParameter("username");   //取得视图层的表单输入的username
	User user = new User();
	user.getDBUser(username);   //调用 模型层的业务逻辑方法
	
	//将得到的信息放在request的attribute中以userName,。。来标识
	request.setAttribute("userName", user.getUserName());
	request.setAttribute("userSex", user.getUserSex());
	request.setAttribute("userAddress", user.getUserAddress());
	
	String nextpage ="/usernameresult.jsp";
	RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher(nextpage);
	dispatcher.forward(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 {

		this.doGet(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
}
建完servlet后在web.xml会自动配置所见的servlet,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  
  <!-- 建立servlet类后自动配置的 -->
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>servlet.UserServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/UserServlet</url-pattern>
  </servlet-mapping>
  </web-app>

执行结果:
启动Tomcat,在地址栏输入:
http://localhost:8080/MVCFirst/usernameinput.jsp,输入数据库中已有的用户名,就会跳转到usernameresult.jsp页面

你可能感兴趣的:(java,sql,mvc,jsp,servlet,server)