JSP+Servlet+Javabean+JDBC MVC Demo 。 在贴上代码之前,先讲下整个Demo的结构。如右图:整个工程可由MVC模式划分为三部分:
<%@ 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=”styles.css”>
–>
</head>
<!–好吧上面可以不用理,都怪myeclipse太人性化…–>
<body>
<!–故事就是从这里开始的,这个表单召唤了login这个action,
带着username和password两个参数的request对象便飞了过去–>
<form id=”login” method=”post” action=”login”>
用户名:<input type=”text” name=”username” /><br/>
密 码:<input type=”password” name=”password” /><br/>
<input type=”submit” value=”登录” />
</form>
</body>
</html>
package Servlet;
import java.io.IOException;
import java.sql.*;
import javax.servlet.RequestDispatcher;
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 Beam.DbDao;
public class LoginServlet extends HttpServlet {
@Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String errMsg=”";
RequestDispatcher rd;
//上面那个request降落在这里
String username=request.getParameter(“username”);
String password=request.getParameter(“password”);
try{
///*Servlet只是处理控制逻辑,简单说就是起到一个分配任务的作用
*而真正处理业务逻辑的是Model层,也就是Javabean
*在这里,Servlet调用了DbDao,创建实例,并将请求所带的参数()
*/
DbDao dd=new DbDao(“com.mysql.jdbc.Driver”,”jdbc:mysql://localhost:3306/user”,
“root”,”some_pass”);
ResultSet rs=dd.query(“select password from user where username=?”, username);
if(rs.next()){
if(rs.getString(“password”).equals(password)){
HttpSession session=request.getSession(true);
session.setAttribute(“name”, username);
rd=request.getRequestDispatcher(“/welcome.jsp”);
rd.forward(request, response);
}
else{
errMsg+=”您输入的用户名或密码不对。”;
}
}
else{
errMsg+=”用户名不存在。”;
}
}
catch(Exception e){
e.printStackTrace();
}
if(errMsg!=null&&!errMsg.equals(“”)){
rd=request.getRequestDispatcher(“/login.jsp”);
request.setAttribute(“err”, errMsg);
rd.forward(request, response);
}
}
}
package Beam;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DbDao {
private Connection conn;
private String driver;
private String username;
private String password;
private String url;
public DbDao(){}
public DbDao(String driver,String url,String username,String password){
this.driver=driver;
this.username=username;
this.password=password;
this.url=url;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
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 getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
//获得数据库连接
public Connection getConnection() throws Exception{
if(conn==null){
///*JDBC常见错误:
*错误信息:java.lang.ClassNotFoundException:com.mysql.jdbc.Driver
Class.forName(this.driver); conn=DriverManager.getConnection(url, username, this.password); } return conn; } //插入记录 public boolean insert(String sql,Object... args) throws Exception{ PreparedStatement pstmt=getConnection().prepareStatement(sql); for(int i=0;i<args.length;i++){ pstmt.setObject(i+1, args[i]); } if(pstmt.executeUpdate()!=1){ return false; } return true; } //执行查询 public ResultSet query(String sql,Object... args) throws Exception{ PreparedStatement pstmt=getConnection().prepareStatement(sql); for(int i=0;i<args.length;i++){ pstmt.setObject(i+1, args[i]); } return pstmt.executeQuery(); } //执行修改 public void modify(String sql,Object... args) throws Exception{ PreparedStatement pstmt=getConnection().prepareStatement(sql); for(int i=0;i<args.length;i++){ pstmt.setObject(i+1, args[i]); } pstmt.executeUpdate(); pstmt.close(); } //关闭数据库连接的方法 public void closeConn() throws Exception{ if(conn!=null&&!conn.isClosed()){ conn.close(); } } }
Demo/WebRoot/WEB-INF/web.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app version=”2.5″
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_2_5.xsd”>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<!–在这里指定了拦截请求的Servlet
没错,在login.jsp中的login就是通过这里的映射关系找到他对应的Servlet–Servlet.LoginServlet–>
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>Servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>