經過servlet實現幾個網站經常使用的功能

幫朋友寫的小程序,因爲功能比較簡單因此就偷懶只使用了Servletcss

1、JSP頁面部分(這個部分的設置比較粗糙,主要是爲了查看功能可否實現,若是須要向用戶展現還得修飾一下)html

1)功能頁(全部須要後臺實現的功能都放在這裏集中展現)前端

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.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="css/styles.css">

</head>

<body>
    <div id="title">功能頁:本頁面顯示全部功能項目,實際開發中請將各自功能項目部署到實際頁面中</div>
    <div id="body">
        <div class="funcblack">
            <br> 訪客留言:
            <form action="servlet/messageIssue.do" method="post">
                <table>
                    <tr>
                        <td><input type="text" name="contact" placeholder="QQ號" />
                        </td>
                    </tr>
                    <tr>
                        <td><textarea rows="6" cols="20" name="message"
                                placeholder="留言..."></textarea>
                        </td>
                    </tr>
                    <tr>
                        <td><input type="submit" value="提交" />
                        </td>
                    </tr>
                </table>
            </form>
        </div>
        <div class="funcblack">
            <br>用戶註冊:
            <form action="servlet/userregister.do" method="post">
                <table>
                    <tr>
                        <td><input type="text" name="userName" placeholder="用戶名..." />
                        </td>
                    </tr>
                    <tr>
                        <td><input type="password" name="userPassword"
                            placeholder="密碼..." /></td>
                    </tr>
                    <tr>
                        <td><input type="password" name="userPasswordConfirm"
                            placeholder="確認密碼..." /></td>
                    </tr>
                </table>
                <input type="submit" value="註冊">
            </form>
        </div>
        <div class="funcblack">
            <br>用戶登陸:
            <form action="servlet/userlog.do" method="post">
                <table>
                    <tr>
                        <td><input type="text" name="userName" placeholder="用戶名..." />
                        </td>
                    </tr>
                    <tr>
                        <td><input type="password" name="userPassword"
                            placeholder="密碼..." /></td>
                    </tr>
                </table>
                <input type="submit" value="登陸">
            </form>
        </div>
        <div class="funcblack">
            <br>新聞發佈:
            <form action="servlet/newsIssue.do" method="post">
                <table>
                    <tr>
                        <td><input type="text" name="newsTitle" placeholder="新聞標題..." />
                        </td>
                    </tr>
                    <tr>
                        <td><textarea rows="6" cols="20" name="newsBody"
                                placeholder="詳細內容..."></textarea>
                        </td>
                    </tr>
                    <tr>
                        <td><input type="submit" value="發佈" />
                        </td>
                    </tr>
                </table>
            </form>
        </div>
        <div class="clear"></div>
    </div>
    <div id="line">
        <a href="servlet/newsDisplay.do">新聞頁</a>
    </div>
</body>
</html>
index.jsp

2)添加一個跳轉成功頁面和一個失敗頁面(開發的時候測試使用,開發完成之後能夠刪除)java

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'success.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>
    <h1>success</h1>
    <%=request.getAttribute("remind")%>
</body>
</html>
success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'success.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>
    <h1>success</h1>
    <%=request.getAttribute("remind")%>
</body>
</html>
failure.jsp

3)因爲功能中包含一個新聞展現的功能,因此補充添加一個新聞展現頁面mysql

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'newsBody.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>
    <h1>News</h1>
    <hr>
    <c:forEach var="news" items="${newsList}">
        <c:if test="${param.id==news.id}">
            <c:out value="${news.newsTitle}" />
            <br>
            <textarea rows="15" cols="100" readonly="readonly">${news.newsBody}</textarea>
        </c:if>
    </c:forEach>
</body>
</html>
newsBody.jsp

4)再添加兩個管理頁面,也是功能展現使用。主要演示若是是管理員登陸,頁面跳轉應與普通用戶有所區別(具體當時爲何要這樣設計有點忘記了,反正也不重要。參考的時候能夠忽略)程序員

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'display.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>
    <h1>inner display</h1>
    <%=request.getAttribute("remind")%>
    <table border="1">
        <c:forEach var="message" items="${messages}">
            <tr>
                <td><c:out value="${message.contact}" /></td>
                <td><c:out value="${message.message}" /></td>
                <td><a href="servlet/messagemanage.do?messageId=${message.id}">刪除</a>
                </td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>
display.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'newsTitle.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>
    <h1>News Title</h1>
    <%=request.getAttribute("remind")%>
    <c:forEach var="news" items="${newsList}">
        <br>
        <a href="newsBody.jsp?id=${news.id }">${news.newsTitle}&nbsp;&nbsp;&nbsp;${news.newsDate}</a>
    </c:forEach>
</body>
</html>
newsTitle.jsp

ps:以上的兩個頁面須要放置在WEB-INF/inner/目錄下,只容許服務器跳轉。web

2、web.xml文件配置sql

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name></display-name>
    <servlet>
        <servlet-name>messageIssue</servlet-name>
        <servlet-class>servlet.MessageIssue</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>UserRegister</servlet-name>
        <servlet-class>servlet.UserRegister</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>UserLog</servlet-name>
        <servlet-class>servlet.UserLog</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>MessageManage</servlet-name>
        <servlet-class>servlet.MessageManage</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>NewsIssue</servlet-name>
        <servlet-class>servlet.NewsIssue</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>NewsDisplay</servlet-name>
        <servlet-class>servlet.NewsDisplay</servlet-class>
    </servlet>

    <!-- 設置*.do做爲調用Servlet的標誌 -->
    <servlet-mapping>
        <servlet-name>messageIssue</servlet-name>
        <url-pattern>/servlet/messageIssue.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>UserRegister</servlet-name>
        <url-pattern>/servlet/userregister.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>UserLog</servlet-name>
        <url-pattern>/servlet/userlog.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>MessageManage</servlet-name>
        <url-pattern>/servlet/messagemanage.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>NewsIssue</servlet-name>
        <url-pattern>/servlet/newsIssue.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>NewsDisplay</servlet-name>
        <url-pattern>/servlet/newsDisplay.do</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>
web.xml

3、Java代碼及數據庫配置數據庫

1)目錄層次小程序

2)數據庫鏈接

package util;

import java.sql.*;

import java.util.Properties;

/*
 * 根據db.properties的配置獲取數據庫鏈接
 */
public class DatabaseConnection {
    private static Connection connection;

    // 返回單例Connection對象
    public static Connection getConnection() {
        if (connection == null) {
            connection = createConnection();
        }
        return connection;
    }
    
    private static Connection createConnection() {
        String driver = null;
        String url = null;
        String username = null;
        String password = null;
        Properties prop = new Properties();
        try {
            prop.load(DatabaseConnection.class.getClassLoader().getResourceAsStream("db.properties"));
            driver = prop.getProperty("driver");
            url = prop.getProperty("url");
            username = prop.getProperty("username");
            password = prop.getProperty("password");
            Class.forName(driver);
            return DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void closeStatement(Statement stmt) {
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void closeResultSet(ResultSet rs) {
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
util/DatabaseConnection.java
#數據庫鏈接信息保存在這裏
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/learnhow
username=root
password=111111111
db.properties

3)Servlet代碼

package servlet;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Message;
import model.News;

import service.MessageService;
import service.NewsService;
import util.DatabaseConnection;

/*
 * servlet工具類,public方法寫在這裏供全部servlet調用
 * 返回的ServletUtil單例對象,開發環境中放在各自的servlet中,生產環境中若是有前端控制器能夠考慮部署裏面。
 */
public class ServletUtil {
    private HttpServletRequest request;
    private HttpServletResponse response;
    private static ServletUtil servletUtil = buildServletUtil();

    public static ServletUtil getServletUtil() {
        return servletUtil;
    }

    private ServletUtil() {

    }

    private static ServletUtil buildServletUtil() {
        return new ServletUtil();
    }

    // 插入一條記錄到session
    public boolean insertHttpSession(String name, Object value) {
        if (servletUtil.request == null) {
            return false;
        } else {
            request.getSession().setAttribute(name, value);
            return true;
        }
    }

    // 插入一條記錄到application
    public boolean insertServletContext(String name, Object value) {
        if (servletUtil.request == null) {
            return false;
        } else {
            request.getServletContext().setAttribute(name, value);
            return true;
        }
    }

    public boolean checkServletContext(String name) {
        if (servletUtil.request == null) {
            return false;
        } else {
            Object o = request.getServletContext().getAttribute(name);
            if (o == null) {
                return false;
            } else {
                return true;
            }
        }
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public ServletUtil setRequest(HttpServletRequest request) {
        this.request = request;
        return this;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public ServletUtil setResponse(HttpServletResponse response) {
        this.response = response;
        return this;
    }

    public ServletUtil setRequestResponse(HttpServletRequest request,
            HttpServletResponse response) {
        this.request = request;
        this.response = response;
        return this;
    }

    // 讀取config.properties中的配置
    public String getConfig(String key) {
        Properties prop = new Properties();
        try {
            prop.load(DatabaseConnection.class.getClassLoader()
                    .getResourceAsStream("config.properties"));
            return prop.getProperty(key);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 返回用戶意見列表
    public List<Message> getMessages() {
        MessageService messageService = new MessageService();
        return messageService.getMessageList();
    }

    // 刪除session中的一條記錄
    public boolean removeHttpSession(String key) {
        if (servletUtil.request == null) {
            return false;
        } else {
            request.getSession().removeAttribute(key);
            return true;
        }
    }

    // 返回新聞列表
    public List<News> getNews() {
        NewsService newsService = new NewsService();
        return newsService.getNewsList();
    }

}
ServletUtil.java

ServletUtil.getConfig(String key) 方法須要讀取一個名爲config.properties配置文件中的信息,這個文件是提供給網站管理員配置除數據庫之外的其餘參數的。在裏面的全部數據均可以在配置完成之後經過前面的方法讀取出來。(做爲演示只配置一條信息用來肯定管理員的用戶名,做爲管理員能夠在數據庫中任選一個用戶用來登陸後臺)

#與網站有關的其餘信息保存在這裏
admin=admin
config.properties
package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

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

import model.Message;
import model.News;
import service.MessageService;
import service.NewsService;

public class NewsIssue extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        if ((request.getParameter("newsTitle") != null && !request
                .getParameter("newsTitle").equals(""))
                && (request.getParameter("newsBody") != null && !request
                        .getParameter("newsBody").equals(""))) {
            // 非空值和空串
            String title = request.getParameter("newsTitle");
            String body = request.getParameter("newsBody");
            this.saveNews(title, body);
            ServletUtil servletUtil = ServletUtil.getServletUtil()
                    .setRequestResponse(request, response);
            List<News> news = servletUtil.getNews();
            //這裏是觸發前臺新聞列表更新的惟一的地方,不經過這裏操做的新聞修改操做都會引起先後臺數據不一致,考慮到真實環境中若是有要求更高的用戶建議使用框架編寫會輕鬆
            servletUtil.insertServletContext("newsList", news);
            request.setAttribute("remind", "新聞已發佈");
            request.getRequestDispatcher("/success.jsp").forward(request,
                    response);
        } else {
            request.setAttribute("remind", "新聞信息填寫錯誤");
            request.getRequestDispatcher("/failure.jsp").forward(request,
                    response);
        }
    }

    private void saveNews(String title, String body) {
        News newsEntity = new News(title, body);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new Date());
        newsEntity.setNewsDate(date);
        NewsService newsService = new NewsService();
        newsService.save(newsEntity);
    }

}
NewsIssue.java
package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Properties;

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

import model.Message;
import model.User;

import service.MessageService;
import service.UserService;
import util.DatabaseConnection;

public class UserLog extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        ServletUtil servletUtil = ServletUtil.getServletUtil()
                .setRequestResponse(request, response);
        // 得到管理員的名字
        String admin = servletUtil.getConfig("admin");
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        if (userName.equals(admin) && this.loggin(userName, userPassword)) {
            // 若是用戶名和密碼覈對成立而且用戶名等於指定的管理員則跳轉到管理員頁面,生產環境中也能夠考慮將這個功能單獨分開,呵呵噠~
            List<Message> messages = servletUtil.getMessages();
            servletUtil.insertHttpSession("messages", messages);
            servletUtil.insertHttpSession("userName", userName);
            request.setAttribute("remind", "管理員已成功登陸");
            request.getRequestDispatcher("/WEB-INF/inner/display.jsp").forward(
                    request, response);
        } else if (this.loggin(userName, userPassword)) {
            // 用戶名和密碼覈對成立,但並不是管理員登陸
            servletUtil.insertHttpSession("userName", userName);
            request.setAttribute("remind", "您已成功登陸");
            request.getRequestDispatcher("/success.jsp").forward(request,
                    response);
        } else {
            request.setAttribute("remind", "用戶名不存在或密碼不符,請聯繫系統管理員");
            request.getRequestDispatcher("/failure.jsp").forward(request,
                    response);
        }
    }

    private boolean loggin(String userName, String userPassword) {
        User userEntity = new User(userName, userPassword);
        UserService userService = new UserService();
        return userService.log(userEntity);
    }
}
UserLog.java
package 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 javax.servlet.http.HttpSession;

import service.UserService;

import model.User;

public class UserRegister extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //生產環境中建議經過JavaScript作前端檢查
        if ((request.getParameter("userPassword") != null && !request
                .getParameter("userPassword").equals(""))
                && (request.getParameter("userPasswordConfirm") != null && !request
                        .getParameter("userPasswordConfirm").equals(""))
                && (request.getParameter("userPassword").equals(request
                        .getParameter("userPasswordConfirm")))) {
            // 用戶名和密碼非空串和空值而且兩次密碼相同
            String userName = request.getParameter("userName");
            String userPassword = request.getParameter("userPassword");
            if (this.register(userName, userPassword)) {
                request.setAttribute("remind", "感謝您的註冊");
                request.getRequestDispatcher("/success.jsp").forward(request,
                        response);
            } else {
                request.setAttribute("remind", "用戶名重複");
                request.getRequestDispatcher("/failure.jsp").forward(request,
                        response);
            }
        } else {
            request.setAttribute("remind", "兩次密碼不符");
            request.getRequestDispatcher("/failure.jsp").forward(request,
                    response);
        }
    }

    private boolean register(String userName, String userPassword) {
        User userEntity = new User(userName, userPassword);
        UserService userService = new UserService();
        return userService.save(userEntity);
    }
}
UserRegister.java
package servlet;

import java.io.IOException;
import java.util.Date;

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

import service.MessageService;

import model.*;

/*
 * 負責用戶留言
 */
public class MessageIssue extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 在開發環境中使用的臨時設置,部署到生產環境之後能夠經過filter統一設置
        request.setCharacterEncoding("utf-8");

        if ((request.getParameter("contact") != null && !request.getParameter(
                "contact").equals(""))
                && (request.getParameter("message") != null && !request
                        .getParameter("message").equals(""))) {
            // 非空串和空值才能夠提交留言
            String contact = request.getParameter("contact");
            String message = request.getParameter("message");
            this.saveMessage(contact, message);
            request.setAttribute("remind", "留言已提交");
            request.getRequestDispatcher("/success.jsp").forward(request,
                    response);
        } else {
            request.setAttribute("remind", "請填寫正確的信息");
            request.getRequestDispatcher("/failure.jsp").forward(request,
                    response);
        }
    }

    private void saveMessage(String contact, String message) {
        Message messageEntity = new Message(contact, message);
        messageEntity.setDate(new Date());
        MessageService messageService = new MessageService();
        messageService.save(messageEntity);
    }
}
MessageIssue.java
package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

import model.Message;

import service.MessageService;

/*
 * 因爲用戶留言只有後臺可見,所以只提供給管理員能夠查看和刪除
 */
public class MessageManage extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        ServletUtil servletUtil = ServletUtil.getServletUtil()
                .setRequestResponse(request, response);
        int messageId = Integer.valueOf(request.getParameter("messageId"));
        if (removeMessage(messageId)) {
            List<Message> messages = servletUtil.getMessages();
            servletUtil.removeHttpSession("messages");
            servletUtil.insertHttpSession("messages", messages);
            request.setAttribute("remind", "留言已經刪除");
            request.getRequestDispatcher("/WEB-INF/inner/display.jsp").forward(
                    request, response);
        } else {
            request.setAttribute("remind", "刪除留言出錯");
            request.getRequestDispatcher("/failure.jsp").forward(request,
                    response);
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    private boolean removeMessage(int messageId) {
        MessageService messageService = new MessageService();
        return messageService.removeMessage(messageId);
    }
}
MessageManage.java
package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

import model.News;

/*
 * 新聞展現:管理員添加了新聞以後用戶登陸就能夠看到
 */
public class NewsDisplay extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        ServletUtil servletUtil = ServletUtil.getServletUtil()
                .setRequestResponse(request, response);
        /*
         * 第一次訪問的用戶負責將newsList注入Application,以後其餘用戶的訪問不會觸發注入動做。新聞列表經過後臺管理員編輯新聞更新。
         * 這樣作有一個缺點,當管理員直接操做數據庫刪除數據的時候不會觸發前臺的更新列表操做。從而形成展現列表和數據庫中的數據不一致,遇到這樣的狀況須要管理員手動刷新一次列表。
         * 因此通常不建議網站管理人員任意改動數據庫中的信息。可是這樣作又會帶來另外一個問題,就是可能隨着網站管理功能的增長都須要在程序員編寫相應的邏輯代碼。
         */
        if (!servletUtil.checkServletContext("newsList")) {
            List<News> newsList = servletUtil.getNews();
            servletUtil.insertServletContext("newsList", newsList);
        }
        request.setAttribute("remind", "新聞概覽");
        request.getRequestDispatcher("/WEB-INF/inner/newsTitle.jsp").forward(
                request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}
NewsDisplay.java

以上Servlet的部分就所有完成了,一些數據檢查的功能在實際生產環境中應該部署到JavaScript中取檢查以減小服務器壓力。可是考慮到使用servlet編寫的程序通常都不會大,普通pc足以運行。

4、model和vo(model和vo最大的區別是vo不須要保存進數據庫因此是完整的對象模型)

package model;

import java.util.Date;

/*
 * CREATE TABLE `eps_log` (
 * `id` int(11) NOT NULL AUTO_INCREMENT,
 * `title` varchar(20) NOT NULL,
 * `_date` varchar(20) NOT NULL,
 * PRIMARY KEY (`id`)
 * ) ENGINE=InnoDB DEFAULT CHARSET=utf8
 */
public class Log {
    private int id;
    private String title;
    private Date date;

    public Log() {
    }

    public Log(String title, Date date) {
        this.title = title;
        this.date = date;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

}
Log.java
package model;

import java.util.Date;

/*
 * CREATE TABLE `eps_message` (
 *  `id` int(11) NOT NULL AUTO_INCREMENT,
 *  `contact` varchar(20) NOT NULL,
 *  `message` varchar(255) NOT NULL,
 *  `_date` varchar(20) NOT NULL,
 *  PRIMARY KEY (`id`)
 *  ) ENGINE=InnoDB DEFAULT CHARSET=utf8
 */
public class Message {
    private int id;
    private String contact;
    private String message;
    private Date date;

    public Message() {
    }

    public Message(String contact, String message) {
        this.contact = contact;
        this.message = message;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getContact() {
        return contact;
    }

    public void setContact(String contact) {
        this.contact = contact;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "Message [id=" + id + ", contact=" + contact + ", message="
                + message + ", date=" + date + "]";
    }

}
Message.java
package model;

/*
 * CREATE TABLE `sps_news` (
 * `id` int(11) NOT NULL AUTO_INCREMENT,
 * `title` varchar(20) NOT NULL,
 * `body` varchar(255) NOT NULL,
 * `_date` varchar(20) NOT NULL,
 * PRIMARY KEY (`id`)
 * ) ENGINE=InnoDB DEFAULT CHARSET=utf8
 */
public class News {
    private int id;
    private String newsTitle;
    private String newsBody;
    private String newsDate;

    public News() {
    }

    public News(String newsTitle, String newsBody) {
        this.newsTitle = newsTitle;
        this.newsBody = newsBody;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNewsTitle() {
        return newsTitle;
    }

    public void setNewsTitle(String newsTitle) {
        this.newsTitle = newsTitle;
    }

    public String getNewsBody() {
        return newsBody;
    }

    public void setNewsBody(String newsBody) {
        this.newsBody = newsBody;
    }

    public String getNewsDate() {
        return newsDate;
    }

    public void setNewsDate(String newsDate) {
        this.newsDate = newsDate;
    }

    @Override
    public String toString() {
        return "News [id=" + id + ", newsTitle=" + newsTitle + ", newsBody="
                + newsBody + ", newsDate=" + newsDate + "]";
    }

}
News.java
package model;

/*
 * CREATE TABLE `eps_user` (
 * `id` int(11) NOT NULL AUTO_INCREMENT,
 * `userName` varchar(20) NOT NULL,
 * `userPassword` varchar(20) NOT NULL,
 * PRIMARY KEY (`id`)
 * ) ENGINE=InnoDB DEFAULT CHARSET=utf8
 */
public class User {
    private int id;
    private String userName;
    private String userPassword;

    public User() {
    }

    public User(String userName, String userPassword) {
        this.userName = userName;
        this.userPassword = userPassword;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

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

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

}
User.java

sql代碼放在每個類中須要本身創建,因爲沒有使用任何orm框架因此得本身建表,好在也沒有設計表關聯不然操做起來會有點複雜。

package model.vo;

/*
 * 值對象不須要實現持久化
 */
public class UserVo {
    private int id;
    private String userName;
    private String userPassword;
    private String userPasswodConfirm;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

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

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public String getUserPasswodConfirm() {
        return userPasswodConfirm;
    }

    public void setUserPasswodConfirm(String userPasswodConfirm) {
        this.userPasswodConfirm = userPasswodConfirm;
    }

}
UserVo.java

5、Dao層和Service層

處於安全考慮用戶註冊,管理員登陸,用戶登陸,留言,新聞發佈等功能都會在Log數據庫表中保存相應的日誌。所以須要在service層配置數據庫事物。若不用配置事物能夠也能夠省略Dao層。

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;

import util.DatabaseConnection;

import model.*;

public class LogDao {
    // 日誌數據保存進數據庫
    public boolean save(Log log) throws SQLException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String date = sdf.format(log.getDate());
        Connection conn = DatabaseConnection.getConnection();
        String sql = "INSERT INTO eps_log VALUES(NULL,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, log.getTitle());
        ps.setString(2, date);
        ps.execute();
        ps.close();
        return true;
    }
}
LogDao.java
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import util.DatabaseConnection;
import model.Message;

public class MessageDao {
    // 訪客留言信息保存進數據庫
    public boolean save(Message message) throws SQLException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(message.getDate());
        Connection conn = DatabaseConnection.getConnection();
        String sql = "INSERT INTO eps_message VALUES(NULL,?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, message.getContact());
        ps.setString(2, message.getMessage());
        ps.setString(3, date);
        ps.execute();
        ps.close();
        return true;
    }

    // 讀取全部訪客留言並封裝成List對象
    public List<Message> getMessageList() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Message> messages = new ArrayList<Message>();
        Connection conn = DatabaseConnection.getConnection();
        String sql = "SELECT * FROM eps_message";
        try {
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()) {
                Message message = new Message();
                message.setId(rs.getInt(1));
                message.setContact(rs.getString(2));
                message.setMessage(rs.getString(3));
                message.setDate(sdf.parse(rs.getString(4)));
                messages.add(message);
            }
            return messages;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } catch (ParseException e2) {
            e2.printStackTrace();
            return null;
        }
    }

    // 根據信息id刪除相應留言
    public boolean remove(int messageId) throws SQLException {
        Connection conn = DatabaseConnection.getConnection();
        String sql = "DELETE FROM eps_message WHERE id = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, messageId);
        ps.execute();
        ps.close();
        return true;
    }
}
MessageDao.java
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import model.Message;
import model.News;
import util.DatabaseConnection;

//新聞發佈
public class NewsDao {
    public boolean save(News news) throws SQLException {
        Connection conn = DatabaseConnection.getConnection();
        String sql = "INSERT INTO eps_news VALUES(NULL,?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, news.getNewsTitle());
        ps.setString(2, news.getNewsBody());
        ps.setString(3, news.getNewsDate());
        ps.execute();
        ps.close();
        return true;
    }

    public List<News> getNewsList() {
        List<News> newsList = new ArrayList<News>();
        Connection conn = DatabaseConnection.getConnection();
        String sql = "SELECT * FROM eps_news";
        try {
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()) {
                News news = new News();
                news.setId(rs.getInt(1));
                news.setNewsTitle(rs.getString(2));
                news.setNewsBody(rs.getString(3));
                news.setNewsDate(rs.getString(4));
                newsList.add(news);
            }
            return newsList;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}
NewsDao.java
package dao;

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

import util.DatabaseConnection;

import model.User;

public class UserDao {
    // 用戶註冊
    public boolean save(User user) throws SQLException {
        Connection conn = DatabaseConnection.getConnection();
        String sql = "INSERT INTO eps_user VALUES(NULL,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, user.getUserName());
        ps.setString(2, user.getUserPassword());
        ps.execute();
        ps.close();
        return true;
    }

    // 用戶名和密碼的檢查,true表明數據庫中有符合的記錄
    public boolean check(User user) {
        Connection conn = DatabaseConnection.getConnection();
        String sql = "SELECT * FROM eps_user WHERE userName = ?";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUserName());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                if (user.getUserName().equals(rs.getString(2))
                        && user.getUserPassword().equals(rs.getString(3))) {
                    return true;
                }
            }
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 用戶名的檢查,true代碼數據庫中沒有相同記錄,容許插入數據
    public boolean check(String userName) {
        Connection conn = DatabaseConnection.getConnection();
        String sql = "SELECT * FROM eps_user WHERE userName = ?";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, userName);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                if (userName.equals(rs.getString(2))) {
                    return false;
                }
            }
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return true;
        }
    }
}
UserDao.java
package service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import util.DatabaseConnection;

import dao.LogDao;
import dao.MessageDao;
import model.Log;
import model.Message;

public class MessageService {
    // 插入客戶留言和插入相應的日誌信息
    public boolean save(Message message) {
        Connection conn = DatabaseConnection.getConnection();
        try {
            conn.setAutoCommit(false);
            MessageDao messageDao = new MessageDao();
            LogDao logDao = new LogDao();
            Log log = new Log("用戶留言", new Date());
            messageDao.save(message);
            logDao.save(log);
            conn.commit();
            return true;
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            try {
                conn.setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // 檢索留言數據
    public List<Message> getMessageList() {
        MessageDao messageDao = new MessageDao();
        return messageDao.getMessageList();
    }

    // 刪除留言數據和插入相應的日誌信息
    public boolean removeMessage(int messageId) {
        Connection conn = DatabaseConnection.getConnection();
        try {
            conn.setAutoCommit(false);
            MessageDao messageDao = new MessageDao();
            LogDao logDao = new LogDao();
            Log log = new Log("刪除留言", new Date());
            messageDao.remove(messageId);
            logDao.save(log);
            conn.commit();
            return true;
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            try {
                conn.setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
MessageService.java
package service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import model.Log;
import model.News;
import util.DatabaseConnection;
import dao.LogDao;
import dao.NewsDao;

public class NewsService {
    public boolean save(News news) {
        Connection conn = DatabaseConnection.getConnection();
        try {
            conn.setAutoCommit(false);
            NewsDao newsDao = new NewsDao();
            LogDao logDao = new LogDao();
            Log log = new Log("發佈新聞", new Date());
            newsDao.save(news);
            logDao.save(log);
            conn.commit();
            return true;
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            try {
                conn.setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public List<News> getNewsList() {
        NewsDao newsDao = new NewsDao();
        return newsDao.getNewsList();
    }
}
NewsService.java
package service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;

import model.Log;
import model.User;
import util.DatabaseConnection;
import dao.LogDao;
import dao.UserDao;

public class UserService {
    public boolean save(User user) {
        Connection conn = DatabaseConnection.getConnection();
        UserDao userDao = new UserDao();
        if (userDao.check(user.getUserName())) {
            try {
                conn.setAutoCommit(false);
                LogDao logDao = new LogDao();
                Log log = new Log(user.getUserName()+"註冊", new Date());
                userDao.save(user);
                logDao.save(log);
                conn.commit();
                return true;
            } catch (Exception e) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
                e.printStackTrace();
                return false;
            } finally {
                try {
                    conn.setAutoCommit(true);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        } else {
            return false;
        }
    }

    public boolean log(User user) {
        UserDao userDao = new UserDao();
        if (userDao.check(user)) {
            LogDao logDao = new LogDao();
            Log log = new Log(user.getUserName() + "登陸", new Date());
            try {
                logDao.save(log);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return true;
        } else {
            return false;
        }
    }
}
UserService.java

後記:很難說這樣寫到底好很差,可是在某些時候感受用戶需求並非很是明確。在這樣的狀況下若是使用各類框架來搭建網站環境再編寫功能代碼反而會以爲多餘。設計這個東西原本就是仁者見仁,智者見智的。我的感受能知足對象的需求又略微擴充一點點彈性的設計纔是最合適的設計思路。小微企業對互聯網的需求並無想象中的強烈,可以提供給他們簡單方便的建站方式或許是幫助它們進入互聯網的最好方法。

最後附上整個項目的目錄結構和IDE版本,處於篇幅考慮沒有提供junit的部分。

 

相關文章
相關標籤/搜索