1. 程式人生 > >基於jsp+servlet+javabean的MVC模式簡單應用

基於jsp+servlet+javabean的MVC模式簡單應用

del html word exe usebean amp nco roo cut

原先寫在CSDN的一篇,我直接扒過來吧。之前打算在CSDN的,結果寫了幾回,發現他那個發布系統簡直爛到家,經常丟失圖片各種。所以很長一段時間我也沒寫什麽。

一、MVC模式

1、M : javabean;

2、V : jsp;

3、C : servlet;

4、DB:MySQL;

二、文件夾

三、項目內容

1、建立數據庫並封裝數據庫操作

create database testDB;  
  
use testDB;  
  
create table user  
(  
id int auto_increment primary key,  
username varchar(
20), password varchar(20), phone varchar(20), addr varchar(225) );

/** 
 * 封裝數據庫操作 
 * 包括對javabean存儲的操作; 
 */  
  
import java.sql.*;  
  
import com.yck.mvc.bean.User;  
  
public class DB  
 {  
    static  
    {  
        try  
        {  
            Class.forName("com.mysql.jdbc.Driver");   
        } 
catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() { Connection connection = null; try { connection = DriverManager.getConnection("jdbc:mysql://localhost/testdb?user=root&password=yck940522"); }
catch (SQLException e) { e.printStackTrace(); } return connection; } public static void closeConnection(Connection connection) { try { if(connection != null) { connection.close(); connection = null; } } catch (SQLException e) { e.printStackTrace(); } } public static PreparedStatement preparedStatement(Connection connection,String sql) { PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); } catch (SQLException e) { e.printStackTrace(); } return preparedStatement; } public static void closePreparedStatement(PreparedStatement preparedStatement) { try { if(preparedStatement != null) { preparedStatement.close(); preparedStatement = null; } } catch (SQLException e) { e.printStackTrace(); } } public static Statement createStatement(Connection connection) { Statement statement = null; try { statement = connection.createStatement(); } catch (SQLException e) { e.printStackTrace(); } return statement; } public static void closeStatement(Statement statement) { try { if(statement != null) { statement.close(); statement = null; } } catch (SQLException e) { e.printStackTrace(); } } public static ResultSet getResultSet(Statement statement,String sql) { ResultSet resultSet = null; try { resultSet = statement.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } return resultSet; } public static void closeResultSet(ResultSet resultSet) { try { if(resultSet != null) { resultSet.close(); resultSet = null; } } catch (SQLException e) { e.printStackTrace(); } } //構造在數據庫中存儲User的方法 public static void saveUser(User u) { Connection connection = null; PreparedStatement preparedStatement = null; try { connection = DB.getConnection(); String sql = "insert into user values(null,?,?,?,?)"; preparedStatement = DB.preparedStatement(connection, sql); preparedStatement.setString(1, u.getUsername()); preparedStatement.setString(2, u.getPassword()); preparedStatement.setString(3, u.getPhone()); preparedStatement.setString(4, u.getAddr()); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } }

2、建立Model:封裝User

public class User  
{  
    private String username;  
    private String password;  
    private String phone;  
    private String addr;  
    public String getUsername()  
    {  
        return username;  
    }  
    public void setUsername(String username)  
    {  
        this.username = username;  
    }  
    public String getPassword()  
    {  
        return password;  
    }  
    public void setPassword(String password)  
    {  
        this.password = password;  
    }  
    public String getPhone()  
    {  
        return phone;  
    }  
    public void setPhone(String phone)  
    {  
        this.phone = phone;  
    }  
    public String getAddr()  
    {  
        return addr;  
    }  
    public void setAddr(String addr)  
    {  
        this.addr = addr;  
    }  
      
  
}  

3 建立View:寫jsp頁面

1)register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>註冊用戶</title>  
</head>  
<body>  
<form name="regiserForm" action="http://localhost:8080/MVC/RegisterServlet" method = "post">  
    <table id="registerTableId" align="center">  
        <tr>  
            <td colspan="2" align="center">用戶註冊</td>  
        </tr>  
        <tr>  
            <td>用戶名</td> <td><input id="usernameId" type="text" name="username"></td>  
            <td><span id="usernameTipId"></span></td>  
        </tr>  
         <tr>  
            <td>密碼</td> <td><input id="passwordId" type="password" name="password"></td>  
            <td><span id="passwordTipId"></span></td>  
        </tr>  
         <tr>  
            <td>密碼確認</td> <td><input id="password2Id" type="password" name="password2"></td>  
            <td><span id="password2TipId"></span></td>  
        </tr>  
         <tr>  
            <td>手機號碼</td> <td><input id="phoneId" type="text" name="phone"></td>  
            <td><span id="phoneTipId"></span></td>  
        </tr>  
         <tr>  
            <td>地址</td> <td><textarea id="addrId" name="addr" rows="3" cols="25"></textarea></td>  
        </tr>  
         <tr>  
            <td><input id="registerSubmitId" type="submit" value="提交"></td>  
            <td><input id="registerResetId" type="reset" value="重置"></td>  
        </tr>  
          
    </table>  
</form>  
  
</body>  
</html>  

2)registerInfo.jsp 顯示註冊信息

<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>註冊成功</title>  
</head>  
<body>  
<jsp:useBean id="registerUser" class="com.yck.mvc.bean.User" scope="session"></jsp:useBean>  
<table id="registerInfoId" align="center">  
    <tr><td colspan="2" align="center">用戶信息</td></tr>  
    <tr>  
        <td>用戶名</td> <td> <jsp:getProperty property="username" name="registerUser"/></td>   
    </tr>  
    <tr>  
        <td>手機號碼</td> <td> <jsp:getProperty property="phone" name="registerUser"/></td>   
    </tr>  
    <tr>  
        <td>地址</td> <td> <jsp:getProperty property="addr" name="registerUser"/></td>   
    </tr>  
</table>  
  
</body>  
</html>  

4、建立Control層:寫servlet

RegisterServlet

import java.io.IOException;  
import javax.servlet.ServletException;  
import javax.servlet.annotation.WebServlet;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import com.yck.mvc.DButil.DB;  
import com.yck.mvc.bean.User;  
  
/** 
 * Servlet implementation class RegisterServlet 
 */  
@WebServlet("/RegisterServlet")  
public class RegisterServlet extends HttpServlet {  
    private static final long serialVersionUID = 1L;  
         
    /** 
     * @see HttpServlet#HttpServlet() 
     */  
    public RegisterServlet() {  
        super();  
        // TODO Auto-generated constructor stub  
    }  
  
    /** 
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
     */  
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException   
    {  
        doPost(request,response);  
      
    }  
  
    /** 
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
     */  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException   
    {  
        request.setCharacterEncoding("utf-8");  
        try  
        {  
            String username = request.getParameter("username");  
            String password = request.getParameter("password");  
            String phone = request.getParameter("phone");  
            String addr = request.getParameter("addr");  
            User u = new User();  
            u.setUsername(username);  
            u.setPassword(password);  
            u.setPhone(phone);  
            u.setAddr(addr);  
            DB.saveUser(u);  
              
            request.getSession().setAttribute("registerUser", u);  
            request.getRequestDispatcher("registerInfo.jsp").forward(request, response);  
        } catch (Exception e)  
        {  
            e.printStackTrace();  
        }  
              
    }  
  
}  

  那邊也沒有測試的結果圖,我猜肯定是掛了。CSDN毛病特別多,作者甚至不能預覽自己寫的東西。提交之後在審核的過程中,點擊自己的文章就是報錯,所以我都是寫完就丟那

基於jsp+servlet+javabean的MVC模式簡單應用