JSP + JavaBean + Servlet实现MVC设计模式
参照:https://www.cnblogs.com/ShawnYang/p/7443528.html
用户登录页面
代码如下:
1 DROP TABLE IF EXISTS `user`; 2 3 CREATE TABLE `user` ( 4 `userid` varchar(30) NOT NULL, 5 `name` varchar(30) NOT NULL, 6 `password` varchar(30) NOT NULL, 7 PRIMARY KEY (`userid`) 8 ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 9 10 INSERT INTO `user` VALUES ('admin', 'administrator', 'admin');
1 public class User { 2 private String userId; 3 private String name; 4 private String passWord; 5 6 public String getUserId() { 7 return userId; 8 } 9 10 public void setUserId(String userId) { 11 this.userId = userId; 12 } 13 14 public String getName() { 15 return name; 16 } 17 18 public void setName(String name) { 19 this.name = name; 20 } 21 22 public String getPassWord() { 23 return passWord; 24 } 25 26 public void setPassWord(String passWord) { 27 this.passWord = passWord; 28 } 29 }
public class DatabaseConnection { public static final String DBDRIVER="com.mysql.jdbc.Driver"; public static final String DBURL="jdbc:mysql://localhost:3306/test"; public static final String DBUSER="root"; public static final String DBPASSWORD="123456"; private Connection conn= null; public Connection getConnection() { return conn; } public DatabaseConnection() throws Exception { try{ Class.forName(DBDRIVER); this.conn= DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD); }catch (Exception e){ throw e; } } public void close() throws Exception { if(this.conn !=null){ try { conn.close(); }catch (Exception e){ throw e; } } } public static void main(String[] arg){ try{ System.out.println(new DatabaseConnection()); }catch (Exception e ){ e.printStackTrace(); } } }
1 public interface IUserDao { 2 public boolean findLogin(User user) throws Exception; 3 }
1 public class UserDaoImpl implements IUserDao { 2 3 @Override 4 public boolean findLogin(User user) throws Exception { 5 boolean flag = false; 6 DatabaseConnection dbconn=null; 7 Connection connection =null; 8 PreparedStatement ps =null; 9 try { 10 dbconn = new DatabaseConnection(); 11 connection = dbconn.getConnection(); 12 String sql="select name from user where userid=? and password = ?"; 13 ps = connection.prepareStatement(sql); 14 ps.setString(0,user.getUserId()); 15 ps.setString(1,user.getPassWord()); 16 ResultSet rs = ps.executeQuery(); 17 if(rs.next()){ 18 user.setName(rs.getString("name")); 19 flag=true; 20 } 21 }catch (Exception e){ 22 throw e; 23 }finally { 24 if(ps!=null){ 25 ps.close(); 26 } 27 if(connection!=null){ 28 connection.close(); 29 } 30 } 31 return flag; 32 } 33 }
1 public class LoginServlet extends HttpServlet{ 2 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException{ 3 String path = "/webapps/login.jsp"; 4 String userID = req.getParameter("userID"); 5 String password = req.getParameter("password"); 6 List<String> info = new ArrayList<String>();//收集错误信息 7 if(userID == null || "".equals(userID)){ 8 info.add("用户id不能为空!"); 9 } 10 if(password == null || "".equals(password)){ 11 info.add("密码不能为空!"); 12 } 13 if(info.size() == 0){//里面没有记录任何的错误 14 User user = new User(); 15 user.setUserId(userID); 16 user.setPassWord(password); 17 try{ 18 if(new UserDaoImpl().findLogin(user)){ 19 info.add("用户登陆成功,欢迎" + user.getName() + "光临!"); 20 System.out.println(1); 21 } else { 22 info.add("用户登录失败,错误的用户名和密码!"); 23 System.out.println(2); 24 } 25 }catch(Exception e){ 26 e.printStackTrace(); 27 } 28 } 29 req.setAttribute("info",info); 30 req.getRequestDispatcher(path).forward(req,res); 31 } 32 public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException{ 33 doGet(req,res); 34 } 35 }
1 <%-- 2 Created by IntelliJ IDEA. 3 User: Administrator 4 Date: 2018/6/12 5 Time: 18:23 6 To change this template use File | Settings | File Templates. 7 --%> 8 <%@ page contentType="text/html" pageEncoding="utf-8" import="java.util.*"%> 9 <html> 10 <head> 11 <title>www.mldnjava.cn, MLDN高端Java培训</title> 12 <% 13 request.setCharacterEncoding("utf-8"); 14 %> 15 <% 16 List<String> info = (ArrayList<String>)request.getAttribute("info"); 17 String userID = request.getParameter("userID"); 18 String password = request.getParameter("password"); 19 %> 20 <script> 21 window.onload = function(){ 22 var objForm = document.getElementById("form1"); 23 24 objForm.onsubmit = function(){ 25 if(!(/^\w{5,15}$/.test(this.userID.value))){ 26 alert("用户ID必须是5~15位!"); 27 this.userID.focus(); 28 return false; 29 } 30 31 if(!(/^\w{5,15}$/.test(this.password.value))){ 32 alert("密码必须是5~15位!"); 33 this.password.focus(); 34 return false; 35 } 36 } 37 38 } 39 40 </script> 41 </head> 42 43 <body> 44 <form id="form1" action="login" method="post"> 45 用户ID:<input type="text" name="userID" value="<%= (userID == null) ? "" : userID %>" /><br> 46 密 码:<input type="password" name="password" value="<%= (password == null) ? "" : password %>" /><br> 47 <input type="submit" value="登录" /> 48 <input type="reset" value="重置" /> 49 </form> 50 <% 51 if(info != null){ 52 for(String str : info){ 53 %> 54 <h3><%=str %></h3> 55 <% 56 } 57 } 58 %> 59 </body> 60 </html>
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 5 version="3.1" > 6 <display-name>web01_exec</display-name> 7 <welcome-file-list> 8 <welcome-file>index.html</welcome-file> 9 <welcome-file>index.htm</welcome-file> 10 <welcome-file>index.jsp</welcome-file> 11 <welcome-file>default.html</welcome-file> 12 <welcome-file>default.htm</welcome-file> 13 <welcome-file>default.jsp</welcome-file> 14 </welcome-file-list> 15 <servlet> 16 <servlet-name>default</servlet-name> 17 <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class> 18 <init-param> 19 <param-name>debug</param-name> 20 <param-value>0</param-value> 21 </init-param> 22 <init-param> 23 <param-name>listings</param-name> 24 <param-value>false</param-value> 25 </init-param> 26 <load-on-startup>1</load-on-startup> 27 </servlet> 28 29 <servlet> 30 <servlet-name>jsp</servlet-name> 31 <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class> 32 <init-param> 33 <param-name>fork</param-name> 34 <param-value>false</param-value> 35 </init-param> 36 <init-param> 37 <param-name>xpoweredBy</param-name> 38 <param-value>false</param-value> 39 </init-param> 40 <load-on-startup>3</load-on-startup> 41 </servlet> 42 43 <servlet-mapping> 44 <servlet-name>default</servlet-name> 45 <url-pattern>/</url-pattern> 46 </servlet-mapping> 47 48 <servlet-mapping> 49 <servlet-name>jsp</servlet-name> 50 <url-pattern>*.jsp</url-pattern> 51 <url-pattern>*.jspx</url-pattern> 52 </servlet-mapping> 53 54 <session-config> 55 <session-timeout>30</session-timeout> 56 </session-config> 57 <servlet> 58 <servlet> 59 <servlet-name>login</servlet-name> 60 <servlet-class>web.LoginServlet</servlet-class> 61 </servlet> 62 <servlet-mapping> 63 <servlet-name>login</servlet-name> 64 <url-pattern>/login</url-pattern> 65 </servlet-mapping> 66 67 </web-app>
工程目录如下

扩展:
1、mysql的jdbc连接说明
driver:com.mysql.jdbc.Driver
url:jdbc:mysql://localhost:3306/test
MySQL url格式:jdbc:mysql://[host:port]/[database][?参数名1][=参数值1][&参数名2][=参数值2]…
| 参数名称 | 参数说明 | 缺省值 | 最低版本要求 |
|---|---|---|---|
| user | 数据库用户名 | / | ALL |
| password | 用户密码 | / | ALL |
| useUnicode | 是否使用Unicode字符集,如果参数characterEncoding设置为gb2312或gbk,本参数值必须设置为true | false | 1.1g |
| characterEncoding | 当useUnicode设置为true时,指定字符编码。比如可设置为utf8、gb2312或gbk | false | 1.1g |
| autoReconnect | 当数据库连接异常中断时,是否自动重新连接? | false | 1.1 |
| autoReconnectForPools | 是否使用针对数据库连接池的重连策略 | false | 3.1.3 |
| failOverReadOnly | 自动重连成功后,连接是否设置为只读? | true | 3.0.12 |
| maxReconnects | autoReconnect设置为true时,重试连接的次数 | 3 | 1.1 |
| initialTimeout | autoReconnect设置为true时,两次重连之间的时间间隔,单位:秒 | 2 | 1.1 |
| connectTimeout | 和数据库服务器建立socket连接时的超时,单位:毫秒。 0表示永不超时,适用于JDK 1.4及更高版本 | 0 | 3.0.1 |
| socketTimeout | socket操作(读写)超时,单位:毫秒。 0表示永不超时 | 0 | 3.0.1 |
| zeroDateTimeBehavior | timestamp类型值为0情况的对策。属性值有三个。exception:默认值,即抛出SQL state [S1009]. Cannot convert value....的异常;
convertToNull:将日期转换成NULL值; round:替换成最近的日期即0001-01-01。 |
在使用数据库连接池的情况下,最好设置如下两个参数:autoReconnect=true&failOverReadOnly=false
参照 zeroDateTimeBehavior,http://blog.sina.com.cn/s/blog_6940cab30101hn9j.html
2、其他数据库jdbc连接串
Oracle
driver:oracle.jdbc.driver.OracleDriver
url:jdbc:oracle:thin:@127.0.0.1:1521:dbname
PostgreSQL
driver:org.postgresql.Driver
url:jdbc:postgresql://localhost/dbname
SQL Server 2005
driver:com.microsoft.sqlserver.jdbc.SQLServerDriver
url:jdbc:sqlserver://localhost:1433; databasename=testt
SQL Server 2008
driver:com.microsoft.jdbc.sqlserver.SQLServerDriver
url:jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test
DB2
driverC:com.ibm.db2.jcc.DB2Driver
url:jdbc:db2://127.0.0.1:50000/dbname
sybase
driver:com.sybase.jdbc.SybDriver
url:jdbc:sybase:Tds:localhost:5007/dbname
Informix
driver:com.informix.jdbc.IfxDriver
url:
jdbc:informix-sqli://123.45.67.89:1533/myDB:INFORMIXSERVER=myserver
odbc桥接
driver:sun.jdbc.odbc.JdbcOdbcDriver
url:jdbc:odbc:Test_DB – 设置数据库连接字符串
url:jdbc:odbc:;Driver={Microsoft Access Driver (*.mdb)};DBQ=路径\数据库名称 – 匿名连接,不需要配置ODBC数据源
url:jdbc:odbc:;Driver={SQL Server};server=主机名\实例名;database=数据库名称 – 匿名连接,不需要配置ODBC数据源
参照 各数据库对应驱动,https://blog.csdn.net/zhliro/article/details/45464375
1 package com.shawn.mvcdemo.vo;
2
3 public class User{
4 private String userID;
5
6 private String name;
7
8 private String password;
9
10 public String getUserID(){
11 return this.userID;
12 }
13
14 public String getName(){
15 return this.name;
16 }
17
18 public String getPassword(){
19 return this.password;
20 }
21
22 public void setUserID(String userID){
23 this.userID = userID;
24 }
25
26 public void setName(String name){
27 this.name = name;
28 }
29
30 public void setPassword(String password){
31 this.password = password;
32 }
33
34 }
posted on 2018-06-13 13:00 helloJava小白 阅读(167) 评论(0) 收藏 举报

浙公网安备 33010602011771号