1、新建項(xiàng)目prj,導(dǎo)入mysql-connector-java-5.0.7-bin.jar到相應(yīng)WebRoot下的WEB-INF\lib下,WebRoot下新建index.jsp,list.jsp,code as follows:
<%@ page contentType="text/html;charset=GBK"%>
<html>
<head>
<title></title>
</head>
<body>
<h2 align="center">登錄界面</h2>
<hr>
<div align="center">
<form action="LoginServlet" method="post">
用戶名:<input type="text" name="userName"/><br>
密碼:<input type="password" name="userPwd"/><br>
<input type="submit" value="進(jìn)入系統(tǒng)"/>
<input type="reset" value="重置"/>
</form>
<font color="red">
<%
String result = (String)request.getAttribute("error");
if(result != null) {
if("NOUSER".equals(result)) {
out.println("用戶不存在");
} else {
out.println("密碼不正確");
}
}
%>
</font>
</div>
</body>
</html>
list.jsp
<%@ page contentType="text/html;charset=GBK" import="java.util.*,org.riker.news.data.*"%>
<html>
<head>
<title></title>
<jsp:useBean id = "news" scope = "page" class = "org.riker.news.logic.NewsLogicBean"/>
</head>
<body>
<center>
<%
String username = (String)session.getAttribute("user");
if(username != null) {
}
%>
歡迎您進(jìn)入本系統(tǒng):<%=username%>
<hr>
<table border="1">
<tr><td>序號</td><td>新聞標(biāo)題</td></tr>
<%
String str_curPage = request.getParameter("curPage");
if(str_curPage!=null){
news.setCurPage(Integer.parseInt(str_curPage));
}
List list = news.findAll();
int allRows = news.getAllRows();
int curPage = news.getCurPage();
int rowPerPage = news.getRowPerPage();
int allPage = news.getAllPages();
for(int i=0; i<list.size(); i++) {
NewsDataBean bean = (NewsDataBean)list.get(i);
%>
<tr><td><input type="radio" name="newsid"><%=(curPage-1)*rowPerPage+i+1%></td>
<td><a href="detail.jsp?newid=<%=bean.getNewsid()%>"><%=bean.getNewstitle()%>(<%=bean.getNewsdate()%>)</td></tr>
<%
}
%>
</table>
<%
if(curPage!=1) {
%>
<a href="/news/main/list.jsp?curPage=1">首頁</a>
<a href="/news/main/list.jsp?curPage=<%=curPage-1%>">上一頁</a>
<% }
%>
<%
if(curPage!=allPage){
%>
<a href="/news/main/list.jsp?curPage=<%=curPage+1%>">下一頁</a>
<a href="/news/main/list.jsp?curPage=<%=allPage%>">末頁</a>
<%
}
%>
</center>
<hr>
<input type="submit" name="operate" value="增加新聞">
<input type="submit" name="operate" value="修改新聞">
<input type="submit" name="operate" value="刪除新聞">
</body>
</html>
2、org.riker.prj.comm包下建立DataSource.java,采用設(shè)計(jì)模式中的單子模式建立數(shù)據(jù)庫連接,用PowerDesigner12.0建表,并用MySQL Query Browser插入相關(guān)數(shù)據(jù),code as follows:
package org.riker.news.comm;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 一個單子設(shè)計(jì)模式的數(shù)據(jù)庫連接
* @author RiKeR
*/
public class DataSource {
private static Connection conn;
private DataSource() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/news","root","root");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
if(conn == null) {
new DataSource();
}
return conn;
}
/**
public static void main(String[] args) {
new DataSource();
System.out.println(conn);
}
*/
}
3、org.riker.prj.logic包下建立LoginLogicBean.java,本JavaBean用來驗(yàn)證登錄,code as follows:
package org.riker.news.logic;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.riker.news.comm.DataSource;
public class LoginLogicBean {
/**
* 驗(yàn)證登錄的方法,如果用戶名和密碼都正確,則返回"OK"
* 如果用戶名正確,密碼錯誤,則返回"PWD"
* 如果用戶名不正確,則沒有必要判斷密碼,返回"NO USER"
* @param userName
* @param userPwd
* @return
*/
public String verify(String userName, String userPwd) {
String result = null;
Connection conn = null;
Statement st = null;
ResultSet rs = null;
conn = DataSource.getConnection();
try {
st = conn.createStatement();
rs = st.executeQuery("select password from user where username='" + userName + "' ");
if (rs.next()) {
if (userPwd.equals(rs.getString(1))) {
result = "OK";
} else {
result = "PWD";
}
} else {
result = "NOUSER";
}
} catch (Exception e) {
} finally {
try {
if(rs != null) rs.close();
if(st != null) st.close();
// if(conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
/**
public static void main(String[] args) {
System.out.println(new LoginLogicBean().verify("RiKeR", "YuRi"));
}
*/
}
4、接下來我們對MVC中的C,控制層進(jìn)行編碼設(shè)計(jì),新建org.riker.news.control包,
建立Servlet:LoginServlet.java,典型的Servlet直接生成時(shí)可選擇相應(yīng)Getter&Setter方法
package org.riker.news.control;
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 org.riker.news.logic.LoginLogicBean;
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 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 {
String userName = request.getParameter("userName");
String userPwd = request.getParameter("userPwd");
LoginLogicBean loginBean = new LoginLogicBean();
String result = loginBean.verify(userName, userPwd);
if("OK".equals(result)) {
request.getSession().setAttribute("user", userName);
request.getRequestDispatcher("main/list.jsp").forward(request, response);
} else if("PWD".equals(result)) {
request.setAttribute("error", "PWD");
request.getRequestDispatcher("index.jsp").forward(request, response);
} else {
request.setAttribute("error", "NOUSER");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
}
è到此,本系統(tǒng)我們已經(jīng)開發(fā)出大體框架及模塊。接下來進(jìn)行細(xì)化:采用過濾器過濾和分頁技術(shù)完善本系統(tǒng),防止用戶直接從main目錄下登入etc
1、org.riker.news.comm寶下,建立SecurityFilter.java
package org.riker.news.comm;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SecurityFilter implements Filter {
public void init(FilterConfig arg0) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
if(request.getSession().getAttribute("user") == null) {
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
chain.doFilter(request, response);
}
public void destroy() {
}
}
2、將list.jsp根據(jù)需求移到/main目錄下,建立org.riker.news.data包下的新聞數(shù)據(jù)Bean
package org.riker.news.data;
public class NewsDataBean {
private String newsid;
private String newstitle;
private String newscontent;
private String newscount;
private String newsdate;
public String getNewscotent() {
return newscontent;
}
public void setNewscontent(String newscontent) {
this.newscontent = newscontent;
}
public String getNewscount() {
return newscount;
}
public void setNewscount(String newscount) {
this.newscount = newscount;
}
public String getNewsdate() {
return newsdate;
}
public void setNewsdate(String newsdate) {
this.newsdate = newsdate;
}
public String getNewsid() {
return newsid;
}
public void setNewsid(String newsid) {
this.newsid = newsid;
}
public String getNewstitle() {
return newstitle;
}
public void setNewstitle(String newstitle) {
this.newstitle = newstitle;
}
}
3、相應(yīng)的開發(fā)對新聞分頁的邏輯Bean,建立在org.riker.news.logic下NewsLogicBean,這里的分頁“小算法”挺8錯
package org.riker.news.logic;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.riker.news.comm.DataSource;
import org.riker.news.data.NewsDataBean;
public class NewsLogicBean {
private int allRows;
private int curPage = 1;
private int rowPerPage = 5;
private int allPages;
public List findAll() {
List list = new ArrayList();
Statement st = null;
ResultSet rs = null;
try {
st = DataSource.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery("select newsid, newstitle, newscontent, newscount, newsdate from news order by newsdate desc");
rs.last();
this.allRows = rs.getRow();
if(this.allRows%this.rowPerPage==0) {
this.allPages = this.allRows/this.rowPerPage;
} else {
this.allPages = this.allRows/this.rowPerPage + 1;
}
if(this.curPage == 1) {
rs.beforeFirst();
} else {
rs.absolute((this.curPage - 1) * this.rowPerPage);
}
int i = 0;
while(rs.next() && i < this.rowPerPage) {
NewsDataBean bean = new NewsDataBean();
bean.setNewsid(rs.getString(1));
bean.setNewstitle(rs.getString(2));
bean.setNewscontent(rs.getString(3));
bean.setNewscount(rs.getString(4));
bean.setNewsdate(rs.getString(5));
list.add(bean);
i++;
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args) {
List list = new NewsLogicBean().findAll();
System.out.println(list.size());
}
public int getCurPage() {
return curPage;
}
public void setCurPage(int curPage) {
this.curPage = curPage;
}
public int getAllPages() {
return allPages;
}
public int getAllRows() {
return allRows;
}
public int getRowPerPage() {
return rowPerPage;
}
}
至此第一階段算是開發(fā)完畢,明天再發(fā)相關(guān)后續(xù)。。。昨天早上4.00到5.00這段時(shí)間Debug得我相當(dāng)郁悶,氣得我都差點(diǎn)睡不著了。。。絕對路徑和JSP完結(jié)標(biāo)簽,還有就是session.getAttribute()、request.getAttribute()、和request.getSession().getAttribute(),這些地方我犯迷糊了,不過這也成為我的經(jīng)驗(yàn)教訓(xùn)了。