• Eclipse+Servlet+jsp+MySql


    一、JSP和Servlet的简单介绍:

      Java开发Web应用程序时用到的技术主要有两种,即Servlet和JSP,Servlet是在服务器端执行的Java程序,一个被称为Servlet容器的程序(其实就是服务器) 负责执行Java程序,而JSP(Java Server Page)则是一个页面, 由JSP容器负责执行。

    Servlet以Java程序为主, 输出HTML代码时需要使用out.println函数,也就是说Java中内嵌HTML; 而JSP则以HTML页面为主,需要写Java代码时则在页面中直接插入Java代码, 即HTML中内嵌Java。

    MVC模型

    MVC模型就是将数据、逻辑处理、用户界面分离的一种方法。

    1)、M(Model, 模型):用于数据处理、逻辑处理

    2)、V(View,视图):用于显示用户界面

    3)、C(Controller,控制器):根据客户端的请求控制逻辑走向和画面

    而在Java中,MVC这三个部分则分别对应于 JavaBeans、JSP和Servlet

    1)、M = JavaBeans:用于传递数据,拥有与数据相关的逻辑处理 

    2)、V = JSP:从Model接收数据并生成HTML 

    3)、C = Servlet:接收HTTP请求并控制Model和View

    web的运行机制:

                  数据首先在jsp上被展示出来,用户看到页面后触发一些事件,并可能传递数据,这些数据和请求被控制器接收到,然后开始处理(往往会需要有一些数据库的操作(查询,修改数据库数据)),当这些处理结束后,我们就需要将数据反馈到JSP上显示给用户看,完成一次完整的交互过程。

    下面描述这个例子, 用的Tomcat7.0, mysql用的是5.17版本,下面是工程结构:

    Util---DBUtil.java用来连接JDBC数据库

    user---User用来定义用户数据类型

    servlet---用来处理用户业务求情和逻辑控制

    dao---UserDao用来处理与数据库相关的操作,例如添加用户、查找用户等

    大家看一下运行效果:

    下面描述详细code:

    User.Java

     1 package user;
     2 
     3 public class User {
     4     private Integer id;
     5     private String name;
     6     private String password;
     7     private int role;
     8     /**
     9      * @return the id
    10      */
    11     public Integer getId() {
    12         return id;
    13     }
    14     /**
    15      * @param id the id to set
    16      */
    17     public void setId(Integer id) {
    18         this.id = id;
    19     }
    20     /**
    21      * @return the name
    22      */
    23     public String getName() {
    24         return name;
    25     }
    26     /**
    27      * @param name the name to set
    28      */
    29     public void setName(String name) {
    30         this.name = name;
    31     }
    32     /**
    33      * @return the password
    34      */
    35     public String getPassword() {
    36         return password;
    37     }
    38     /**
    39      * @param password the password to set
    40      */
    41     public void setPassword(String password) {
    42         this.password = password;
    43     }
    44     /**
    45      * @return the role
    46      */
    47     public int getRole() {
    48         return role;
    49     }
    50     /**
    51      * @param role the role to set
    52      */
    53     public void setRole(int role) {
    54         this.role = role;
    55     }
    56     
    57 
    58 }

    DBUtil.java  连接数据库

     1 package util;
     2 
     3 import java.sql.Connection;
     4 import java.sql.DriverManager;
     5 import java.sql.Driver;
     6 import java.sql.SQLException;
     7 import java.sql.Statement;
     8 
     9 public class DBUtil {
    10 
    11     public static final String driver="com.mysql.jdbc.Driver";
    12     public static final String url="jdbc:mysql://localhost:3306/user?characterEncoding=utf8&useSSL=true";
    13     public static final String username="root";
    14     public static final String password="root";
    15     public static Connection con=null;
    16 
    17 
    18     static{
    19         try {
    20             Class.forName(driver);//得到DriverManager,在下面建立连接时使用
    21         } catch (ClassNotFoundException e) {
    22             e.printStackTrace();
    23         }
    24     }
    25     
    26     public static Connection getCon(){
    27         
    28         if(con == null){
    29             try {
    30                 con = DriverManager.getConnection(url, username, password);
    31             } catch (SQLException e) {
    32                 e.printStackTrace();
    33             }            
    34         }
    35         return con;        
    36     }
    37     
    38     //关闭的方法
    39         public static void close(Statement statement,Connection conn){
    40                if(statement !=null){
    41                    try {
    42                     statement.close();
    43                 } catch (SQLException e) {
    44                     // TODO Auto-generated catch block
    45                     e.printStackTrace();
    46                 }
    47                }
    48                
    49                if(conn !=null){
    50                    try {
    51                     conn.close();
    52                 } catch (SQLException e) {
    53                     // TODO Auto-generated catch block
    54                     e.printStackTrace();
    55                 }
    56                }
    57         }
    58         
    59         public static void main(String args[]){            
    60             new DBUtil().getCon();    
    61         }
    62 }

    dao---UserDao.java   处理数据库相关操作

     1 package dao;
     2 
     3 import java.sql.Connection;
     4 import java.sql.PreparedStatement;
     5 import java.sql.ResultSet;
     6 import java.sql.SQLException;
     7 
     8 import user.User;
     9 import util.DBUtil;
    10 
    11 public class UserDao {
    12 
    13     //数据库连接对象
    14     public  User  login(String username,String password) {
    15        User u=null;
    16        Connection connection =null;
    17        PreparedStatement pstmt=null;
    18        ResultSet resultSet=null;
    19  
    20       //赋值
    21       try {
    22          connection=DBUtil.getCon();
    23           //静态sql语句
    24          String sql = "select * from user where name=? and password=?"; 
    25          pstmt = (PreparedStatement) connection.prepareStatement(sql);
    26          pstmt.setString(1, username);
    27          pstmt.setString(2, password);  
    28          resultSet = pstmt.executeQuery();
    29          if(resultSet.next()){
    30             u=new User();
    31             u.setName(resultSet.getString("name"));
    32             u.setPassword(resultSet.getString("password"));
    33             System.out.println("登录成功!");
    34          }else{
    35             System.out.println("用户名或者密码错误!");
    36          }  
    37       } catch (SQLException e) {
    38         e.printStackTrace();
    39       }finally {    
    40          // DBUtil.close(pstmt, connection);    
    41       }
    42       return u;
    43  
    44     }
    45     
    46     public boolean addUser(User user) {
    47         Connection connection = null;
    48         PreparedStatement psmt = null;
    49         try {
    50              connection = DBUtil.getCon();
    51              
    52              String sql  ="insert into user(id,name,password,role)values(?,?,?,?);";
    53              
    54              psmt = (PreparedStatement) connection.prepareStatement(sql);
    55              
    56              //运用实体对象进行参数赋值
    57              psmt.setInt(1, user.getId());
    58              psmt.setString(2, user.getName());
    59              psmt.setString(3,user.getPassword());
    60              psmt.setInt(4, user.getRole());
    61              psmt.executeUpdate();         
    62         } catch (SQLException e) {
    63             e.printStackTrace();
    64             return false;
    65         }finally {
    66             //DBUtil.close(psmt, connection);
    67         }
    68         return true;        
    69     }
    70 }

    Servlet---处理相关用户业务逻辑  LoginServlet和RegisterServlet.java

     1 package servlet;
     2 
     3 import java.io.IOException;
     4 
     5 import javax.servlet.ServletException;
     6 import javax.servlet.annotation.WebServlet;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 import javax.servlet.http.HttpSession;
    11 
    12 import dao.UserDao;
    13 import user.User;
    14 
    15 /**
    16  * Servlet implementation class LoginServlet
    17  */
    18 @WebServlet("/LoginServlet")
    19 public class LoginServlet extends HttpServlet {
    20     private static final long serialVersionUID = 1L;
    21        
    22     /**
    23      * @see HttpServlet#HttpServlet()
    24      */
    25     public LoginServlet() {
    26         super();
    27         // TODO Auto-generated constructor stub
    28     }
    29 
    30     /**
    31      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    32      */
    33     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    34         // TODO Auto-generated method stub
    35         response.getWriter().append("Served at: ").append(request.getContextPath());
    36     }
    37 
    38     /**
    39      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    40      */
    41     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    42         // TODO Auto-generated method stub
    43         request.setCharacterEncoding("utf-8");
    44         response.setContentType("text/html;charset=utf-8");
    45         HttpSession sessionzxl = request.getSession();
    46         String username = request.getParameter("username");
    47         String password = request.getParameter("password");
    48         UserDao userDAO=new UserDao(); 
    49         User user=userDAO.login(username, password);
    50         if(user!=null){
    51             sessionzxl.setAttribute("user", user);
    52             request.getRequestDispatcher("success.jsp").forward(request, response);;
    53         }else{
    54             request.getRequestDispatcher("error.jsp").forward(request, response);
    55         }
    56     }
    57 
    58 }
     1 package servlet;
     2 
     3 import java.io.IOException;
     4 
     5 import javax.servlet.ServletException;
     6 import javax.servlet.annotation.WebServlet;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 import javax.servlet.http.HttpSession;
    11 
    12 import dao.UserDao;
    13 import user.User;
    14 
    15 /**
    16  * Servlet implementation class RegisterServlet
    17  */
    18 @WebServlet("/RegisterServlet")
    19 public class RegisterServlet extends HttpServlet {
    20     private static final long serialVersionUID = 1L;
    21        
    22     /**
    23      * @see HttpServlet#HttpServlet()
    24      */
    25     public RegisterServlet() {
    26         super();
    27         // TODO Auto-generated constructor stub
    28     }
    29 
    30     /**
    31      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    32      */
    33     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    34         // TODO Auto-generated method stub
    35         response.getWriter().append("Served at: ").append(request.getContextPath());
    36     }
    37 
    38     /**
    39      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    40      */
    41     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    42         request.setCharacterEncoding("utf-8");
    43         response.setContentType("text/html;charset=utf-8");    
    44         request.setCharacterEncoding("utf-8");  
    45          int id=Integer.valueOf(request.getParameter("id"));  
    46          String name=request.getParameter("name");  
    47          String password=request.getParameter("password");
    48          int role=Integer.valueOf(request.getParameter("role"));
    49          User user=new User();
    50          user.setId(id);
    51          user.setName(name);
    52          user.setPassword(password);
    53          user.setRole(role);
    54          UserDao userDAO=new UserDao(); 
    55          boolean result = userDAO.addUser(user);
    56          if(result){
    57              System.out.println("注册成功!");
    58              HttpSession session = request.getSession();
    59              session.setAttribute("user", user);
    60              String loginSuccess = "LoginSuccess.jsp";
    61              response.sendRedirect(loginSuccess);
    62          }else{
    63              System.out.println("注册失败!");
    64              String loginFail = "LoginFail.jsp";
    65              response.sendRedirect(loginFail);
    66          }         
    67          //request.getRequestDispatcher("Login.jsp").forward(request, response);    
    68     }
    69 }

    下面是jsp脚本控制:

    首先看一下登录脚本Login.jsp

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
     7 <title>登录界面</title>
     8  <style type="text/css">
     9      body{
    10          background-image:url(images/login.jpg);
    11          background-position:center;
    12             background-repeat:no-repeat;
    13        }     
    14  </style>
    15 
    16 </head>
    17 <body>
    18   <div style="text-align:center;margin-top:120px">  
    19     <h2>诗远的主页</h2>  
    20     <form action="LoginServlet" method="post">  
    21         <table style="margin-left:40%">  
    22              <marquee width="200"scrolldelay="250">用户登录</marquee> 
    23             <tr>  
    24                 <td>登录名:</td>  
    25                 <td><input name="username" type="text" size="21"></td>  
    26             </tr>  
    27             <tr>  
    28                 <td>密码:</td>  
    29                 <td><input name="password" type="password" size="21"></td>  
    30             </tr>
    31         </table>   
    32         <input type="submit" value="登录">  
    33         <input type="reset" value="重置">   
    34     </form>  
    35     <br>  
    36     <a href="Register.jsp">注册</a>  
    37     </div>  
    38 </body>
    39 </html>

    注册页面Register.jsp

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
     7 <title>注册界面</title>
     8     <style type="text/css">
     9      body{
    10          background-image:url(images/register.jpg);
    11          background-position:center;
    12         background-repeat:no-repeat;
    13      }     
    14  </style>
    15 
    16 </head>
    17 <body>
    18 <div style="text-align:center;margin-top:120px">  
    19     <h1 >请注册</h1>  
    20     <form action="RegisterServlet" method="post">  
    21         <table style="margin-left:40%">  
    22             <caption>用户注册</caption>  
    23             <tr>  
    24                 <td>ID:</td>  
    25                 <td><input name="id" type="text" size="20"></td>  
    26             </tr>  
    27             <tr>  
    28                 <td>登录名:</td>  
    29                 <td><input name="name" type="text" size="20"></td>  
    30             </tr>  
    31             <tr>  
    32                 <td>密码:</td>  
    33                 <td><input name="password" type="password" size="20"></td>  
    34             </tr>  
    35              <tr>  
    36                 <td>角色:</td>  
    37                 <td><input name="role" type="text" size="20"></td>  
    38             </tr>  
    39         </table>   
    40         <input type="submit" value="注册">  
    41         <input type="reset" value="重置">   
    42     </form>  
    43     <br>  
    44     <a href="Login.jsp">登录</a>  
    45     </div>  
    46 </body>
    47 </html>

     登录成功界面,这个比较简单,是后面自己修改的success.jsp:

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <%@ page import="user.User"%>
     5 
     6 <%
     7 String path = request.getContextPath();
     8 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     9 %>
    10 
    11 <html>
    12 <head>
    13 <base href="<%=basePath%>">
    14 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    15 <title>My JSP 'success.jsp' starting page</title>
    16 </head>
    17 <body>
    18 <%User user = (User)session.getAttribute("user");%>
    19 "Congratulations! Login success!";<br>
    20 username:<%= user.getName()%> <br>
    21 password:<%= user.getPassword() %> <br>
    22 basePath: <%=basePath%><br>
    23 path:<%=path%><br>
    24 </body>
    25 </html>

    登录失败后的界面error.jsp:

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <%
     5 String path = request.getContextPath();
     6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     7 %>
     8 
     9 <html>
    10 <head>
    11 <base href="<%=basePath%>">
    12 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    13 <title>My JSP 'fail.jsp' starting page</title>
    14 </head>
    15 <body>
    16     Login Failed! <br>
    17     basePath: <%=basePath%><br>
    18     path:<%=path%><br>
    19     <a href="Login.jsp">请重新登录</a>  
    20 </body>
    21 </html>

    注册成功后的界面LoginSuccess.jsp:

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <%@ page import="user.User"%>
     5 
     6 <%
     7 String path = request.getContextPath();
     8 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     9 %>
    10 
    11 <html>
    12 <head>
    13 <base href="<%=basePath%>">
    14 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    15 <title>My JSP 'Loginsuccess.jsp' starting page</title>
    16 </head>
    17 <body>
    18 <%User user = (User)session.getAttribute("user");%>
    19 "Congratulations! Register success!";<br>
    20 username:<%= user.getName()%> <br>
    21 password:<%= user.getPassword() %> <br>
    22 basePath: <%=basePath%><br>
    23 path:<%=path%><br>
    24 <a href="Login.jsp">点击登录</a>  
    25 </body>
    26 </html>

    注册失败后的界面LoginFail.jsp

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <%
     5 String path = request.getContextPath();
     6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     7 %>
     8 
     9 <html>
    10 <head>
    11 <base href="<%=basePath%>">
    12 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    13 <title>My JSP 'LoginFail.jsp' starting page</title>
    14 </head>
    15 <body>
    16     Register Failed! <br>
    17     basePath: <%=basePath%><br>
    18     path:<%=path%><br>
    19     <a href="Register.jsp">重新注册</a> 
    20 </body>
    21 </html>

    所有的jsp脚本到此结束。

    下面看web.xml配置:如果是比较旧的tomcat版本,不支持WebServlet注解方式,就需要在web.xml里面配置servlet-mapping映射。

    我用的是Tomcat7.0,Servlet是3.0, 支持servlet注解。所以不需要在web.xml里面配置servlet.你可以在Servlet的java文件里面看到这样自动生成的注解:

    @WebServlet("/LoginServlet")

    @WebServlet("/RegisterServlet")

    但是在web.xml里面需要在webclme-file-list配置登录界面,如下:

    1 <?xml version="1.0" encoding="UTF-8"?>
    2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    3   <display-name>ServletWebDemo</display-name>
    4   <welcome-file-list>
    5     <welcome-file>Login.jsp</welcome-file>
    6   </welcome-file-list>
    7 </web-app>

    最后看一下数据库操作,我装的是Mysql5.7版本,装过最新的Mysql8.15版本,可是装不成功,所以直接装的5.7版本。然后还装了一个SQLyog软件来界面控制SQL。

    从DBUtil里面可以看到,连接的数据库是user, 后面在UserDao操作的数据表是user。mysql登录用户名和密码是root和root。下面接了个Mysql的数据结构:

    在上面数据表定义中,把id声明为主键,下面是我注册过几次后数据表的结构,

     注意一下,在上面工程中要导入两个包,一个是servlet-api.jar, 一个是mysql-connector-java-5.1.47.jar

    背景图片放在:images下面。到此整个工程code介绍完了。按照上面code应该是能够运行起来。

    主要参考博客有:

    https://blog.csdn.net/yjx568135132/article/details/73896240

    https://blog.csdn.net/blackplus28/article/details/80603863

  • 相关阅读:
    61个下拉菜单实例
    简单图片放大效果
    QQ,MSN,Skype在线客服代码
    codesmith自定义模板之实体层
    如何利用缓存提高ASP.NET网站速度
    10+Jquery Tooltip Plugins and Tutorial Collection
    10个ajax 上传插件
    ASP.NET 中 “返回上一页”,“上一步”的实现方法
    执行多条SQL语句,事务处理
    [Asp.Net+C#]Datagrid使用技巧四(怎样控制在一个单元格中放置多个操作按钮及删除数据)
  • 原文地址:https://www.cnblogs.com/beilou310/p/10497137.html
Copyright © 2020-2023  润新知