这里用到的软件分别如下:
Tomcat:apache-tomcat-6.0.29.zip
Mysql:mysql-essential-5.1.50-win32.msi
JDBC:mysql-connector-java-5.1.13-bin.jar
Myeclipse:myeclipse-8.6.0-win32.exe
这里要做的配置如下:
mysql默认安装,建立root账户,密码root
mysql-connector-java-5.1.13-bin.jar放到Web应用的WEB-INF/lib/目录下或者是tomcat的lib/目录下
这里要制作的效果如下:
登录页面:
注销页面:
这里用到的关键代码如下:
SQL:
create database test;
use test;
CREATE TABLE test.user (
pid varchar(45) default NULL,
username varchar(45) NOT NULL,
password varchar(45) NOT NULL
) DEFAULT CHARSET=GB2312;
INSERT user(pid, username, password) VALUES('1', 'root', 'root');
INSERT user(pid, username, password) VALUES('2', 'admin', 'admin');
首页(视图):
1 <body>
2 <%if (null != session.getAttribute("username")) { %>
3 欢迎您回来:<%=session.getAttribute("username") %>
4 <a href="servlet/ServletLogout">注销</a><br/>
5 <br/>
6 <%} else {%>
7 <form action="servlet/ServletLogin" method="POST">
8 <input type="text" name="username"/><br/>
9 <input type="password" name="password"/><br/>
10 <input type="submit" value="登录"/>
11 </form>
12 <%} %>
13 在线会员人数:<%=application.getAttribute("onlineMember") %><br/>
14 当前在线人数:<%=application.getAttribute("onlineNumber") %><br/>
15 历史访问人数:<%=application.getAttribute("totalNumber") %><br/>
16 </body>
登录(控制器):
1 public void doGet(HttpServletRequest request, HttpServletResponse response)
2 throws ServletException, IOException {
3
4 HttpSession session = request.getSession();
5 ServletContext application = this.getServletContext();
6
7 if (null == session.getAttribute("username")) {
8 try {
9 // 获得表单数据
10 String username = request.getParameter("username");
11 String password = request.getParameter("password");
12
13 // 建立数据库连接
14 Connection conn = DBUtil.getConnection();
15
16 // 定义查询语句
17 String sql = "select * from user where `username`=? and `password`=?";
18 PreparedStatement pstmt = conn.prepareStatement(sql);
19 pstmt.setString(1, username);
20 pstmt.setString(2, password);
21
22 // 查询获得结果集
23 ResultSet rs = pstmt.executeQuery();
24 if (rs.next()) {
25 session.setAttribute("username", rs.getString("username"));
26 //session.setAttribute("password", rs.getString("password"));
27 int olMember = ((Integer) application.getAttribute("onlineMember")).intValue();
28 application.setAttribute("onlineMember", olMember + 1);
29 }
30
31 // 关闭结果集,查询语句,数据库连接
32 rs.close();
33 pstmt.close();
34 conn.close();
35 } catch (InstantiationException e) {
36 // TODO Auto-generated catch block
37 e.printStackTrace();
38 } catch (IllegalAccessException e) {
39 // TODO Auto-generated catch block
40 e.printStackTrace();
41 } catch (ClassNotFoundException e) {
42 // TODO Auto-generated catch block
43 e.printStackTrace();
44 } catch (SQLException e) {
45 // TODO Auto-generated catch block
46 e.printStackTrace();
47 }
48 }
49
50 // 返回上一个页面
51 response.sendRedirect(request.getHeader("Referer"));
52 }
注销(控制器):
1 public void doGet(HttpServletRequest request, HttpServletResponse response)
2 throws ServletException, IOException {
3
4 HttpSession session = request.getSession();
5 ServletContext application = this.getServletContext();
6
7 // 如果此用户没有登录过
8 if (null != session.getAttribute("username")) {
9 int olMember = ((Integer)application.getAttribute("onlineMember")).intValue();
10 application.setAttribute("onlineMember", olMember - 1);
11 //session.invalidate();
12 session.removeAttribute("username");
13 }
14
15 // 返回上一个页面
16 response.sendRedirect(request.getHeader("Referer"));
17 }
数据库(模型):
1 public class DBUtil {
2 private static String username = "root";
3 private static String password = "root";
4 private static String driver = "com.mysql.jdbc.Driver";
5 private static String url = "jdbc:mysql://localhost:3306/test";
6
7 // 得到数据库连接
8 public static Connection getConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
9 Class.forName(driver).newInstance();
10 return DriverManager.getConnection(url, username, password);
11 }
12
13 }
Web配置页面:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
5 <listener>
6 <listener-class>listener.WebListener</listener-class>
7 </listener>
8 <servlet>
9 <servlet-name>ServletWebInitializer</servlet-name>
10 <servlet-class>servlet.ServletWebInitializer</servlet-class>
11 <load-on-startup>1</load-on-startup>
12 </servlet>
13 <servlet>
14 <servlet-name>ServletLogin</servlet-name>
15 <servlet-class>servlet.ServletLogin</servlet-class>
16 </servlet>
17 <servlet>
18 <servlet-name>ServletLogout</servlet-name>
19 <servlet-class>servlet.ServletLogout</servlet-class>
20 </servlet>
21
22 <servlet-mapping>
23 <servlet-name>ServletWebInitializer</servlet-name>
24 <url-pattern>/servlet/ServletWebInitializer</url-pattern>
25 </servlet-mapping>
26 <servlet-mapping>
27 <servlet-name>ServletLogin</servlet-name>
28 <url-pattern>/servlet/ServletLogin</url-pattern>
29 </servlet-mapping>
30 <servlet-mapping>
31 <servlet-name>ServletLogout</servlet-name>
32 <url-pattern>/servlet/ServletLogout</url-pattern>
33 </servlet-mapping>
34 <welcome-file-list>
35 <welcome-file>index.jsp</welcome-file>
36 </welcome-file-list>
37 </web-app>
Web初始化:
1 public void init() throws ServletException {
2 // Put your code here
3 ServletContext app = this.getServletContext();
4 app.setAttribute("onlineMember", new Integer(0)); // 在线会员人数
5 app.setAttribute("onlineNumber", new Integer(0)); // 当前在线人数
6 app.setAttribute("totalNumber", new Integer(0)); // 历史访问人数
7 }
Web监听器:
1 public class WebListener implements HttpSessionListener {
2
3 public WebListener() {
4 // TODO Auto-generated constructor stub
5 }
6
7 public void sessionCreated(HttpSessionEvent se) {
8 // TODO Auto-generated method stub
9
10 ServletContext app = se.getSession().getServletContext();
11 int olCount = ((Integer)app.getAttribute("onlineNumber")).intValue();
12 app.setAttribute("onlineNumber", olCount + 1);
13
14 int ttlCount = ((Integer)app.getAttribute("totalNumber")).intValue();
15 app.setAttribute("totalNumber", ttlCount + 1);
16 }
17
18 public void sessionDestroyed(HttpSessionEvent se) {
19 // TODO Auto-generated method stub
20 ServletContext app = se.getSession().getServletContext();
21 int olCount = ((Integer)app.getAttribute("onlineNumber")).intValue();
22 app.setAttribute("onlineNumber", olCount - 1);
23 }
24
25 }
总结如下:
1. 如果要在Web应用中初始化一些值,那么可以采用在web.xml加入1个或者多个特殊的servlet,并设置对应的servlet配置:
<servlet>
<servlet-name>ServletWebInitializer</servlet-name>
<servlet-class>servlet.ServletWebInitializer</servlet-class>
<load-on-startup>x</load-on-startup>(x>=1,顺序越小启动优先级越高)
</servlet>
将要初始化的内容写在这些特殊的servlet的init()方法内:
public void init() throws ServletException
2. 如果在一个新会话的开始,或者一个会话的结束时要进行某些计算,比如统计在线人数,那么可以在web.xml加入1个或者多个监听器:
<listener>
<listener-class>listener.WebListener</listener-class>
</listener>
对应的计算放在sessionCreated和sessionDestroyed里面:
public class WebListener implements HttpSessionListener
public void sessionCreated(HttpSessionEvent se)
public void sessionDestroyed(HttpSessionEvent se)
3. mysql数据库采用jdbc连接的步骤如下:
1 public class DBUtil {
2 private static String username = "root";
3 private static String password = "root";
4 private static String driver = "com.mysql.jdbc.Driver";
5 private static String url = "jdbc:mysql://localhost:3306/test";
6
7 // 得到数据库连接
8 public static Connection getConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
9 Class.forName(driver).newInstance();
10 return DriverManager.getConnection(url, username, password);
11 }
12
13 }
// 建立数据库连接
Connection conn = DBUtil.getConnection();
// 定义查询语句
String sql = "select * from user where `username`=? and `password`=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
// 查询获得结果集
ResultSet rs = pstmt.executeQuery();
rs.close();
pstmt.close();
conn.close();
4. jsp页面除了少量的if语句,基本上都是输出语句,将数据计算放到对应的JavaBean或者控制器内部完成。
完整程序下载页面:http://u.115.com/file/f8930734df