基于jsp+servlet+javabean的MVC模式简单应用

时间:2022-11-29 23:30:12

原先写在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毛病特别多,作者甚至不能预览自己写的东西。提交之后在审核的过程中,点击自己的文章就是报错,所以我都是写完就丢那