1、新建项目prj,导入mysql-connector-java-5.0.7-bin.jar到相应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="进入系统"/>
<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) {
}
%>
欢迎您进入本系统:<%=username%>
<hr>
<table border="1">
<tr><td>序号</td><td>新闻标题</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,采用设计模式中的单子模式建立数据库连接,用PowerDesigner12.0建表,并用MySQL Query Browser插入相关数据,code as follows:
package org.riker.news.comm;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 一个单子设计模式的数据库连接
* @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用来验证登录,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 {
/**
* 验证登录的方法,如果用户名和密码都正确,则返回"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,控制层进行编码设计,新建org.riker.news.control包,
建立Servlet:LoginServlet.java,典型的Servlet直接生成时可选择相应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
}
}
è到此,本系统我们已经开发出大体框架及模块。接下来进行细化:采用过滤器过滤和分页技术完善本系统,防止用户直接从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根据需求移到/main目录下,建立org.riker.news.data包下的新闻数据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、相应的开发对新闻分页的逻辑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;
}
}
至此第一阶段算是开发完毕,明天再发相关后续。。。昨天早上4.00到5.00这段时间Debug得我相当郁闷,气得我都差点睡不着了。。。绝对路径和JSP完结标签,还有就是session.getAttribute()、request.getAttribute()、和request.getSession().getAttribute(),这些地方我犯迷糊了,不过这也成为我的经验教训了。