JSP+Servlet+JDBC简单例子

这是非常简单的小例子。用来简单了解和体会servlet的应用。我使用的是MyEclipse。

第一步:新建web Project,命名为servletTest。项目的总结构图如下

这里写图片描述

第二步:引入jar包。这个例子只需Mysql-connector-java-5.0.4-bin.jar和servlet-api.jar这两个包。
第三步:新建src/com.tgb.servlet/User.java
package com.tgb.servlet;

public class User{
    private int id;
    private String username;
    private String password;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    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;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
    }

}
第四步:新建src/com.tgb.servlet/UserDao.java

这个类里面涉及到了JDBC 的创建和使用。

package com.tgb.servlet;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.tgb.servlet.User;

public class UserDao {
     private static User user =null;
     private static Connection conn =null;
    public static User login(String username, String password) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(//创建数据库连接
                    "jdbc:mysql://127.0.0.1:3306/servletTest", "root", "123456");
            String sql =" select * from user where username = ? and password = ? ";

            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                user = new User();
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
            }
            conn.close();
            ps.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return user;
    }

}

第五步:新建src/com.tgb.servlet/LoginServlet.java
package com.tgb.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mchange.v2.c3p0.impl.NewPooledConnection;
import com.tgb.servlet.User;
import com.tgb.servlet.UserDao;

/**
 * login验证servlet类
 * 
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private static final String username = null;
    private static final String password = null;
    private static final HttpServletRequest request = null;
    private static final ServletResponse response = null;

    @SuppressWarnings("unused")
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        //这是连数据库,判断账号的存在登录进行简单的登陆/计算 
         String username = request.getParameter("username");
         String password = request.getParameter("password"); 
             User user = new User();
             user =  UserDao.login(username, password);
             if (user != null) {
                 HttpSession session = request.getSession();
                 session.setAttribute("username", username);
                 /*将username保存到session中。session的key值为“username”
                 value值就是username真实的值,或者引用值. 
                 这样以后你可以通session.getAttribute("username")的方法获得这个对象. */
              //页面重定向
              // response.sendRedirect("/MyWeb_04/success.jsp");
             //页面转发 
                 request.getRequestDispatcher("/success.jsp").forward(request, response);
             } else {
                 request.setAttribute("error", "您的账号和密码不匹配,请重新输入");
                 request.getRequestDispatcher("/login.jsp").forward(request, response);
             }
    }
}
第六步:新建src/com.tgb.servlet/CalcServlet.java
package com.tgb.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/CalcServlet")
public class CalcServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String num1 = request.getParameter("num1");
        String num2 = request.getParameter("num2");
        int n1 = Integer.parseInt(num1);
        int n2 = Integer.parseInt(num2);
        int sum = n1 + n2;


        request.setAttribute("sum", sum);
        request.getRequestDispatcher("/result.jsp").forward(request, response);
      //response.sendRedirect("/result.jsp");
    }

}
第七步:新建WebRoot/login.jsp(登录页面)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录页面</title>
        <style type="text/css">
            #span{
                color:red;
                font-wight:bold;
            }   
        </style>
</head>
<body>
    <%
        String message = "";
        String error = (String) request.getAttribute("error");
        if(message != null){
            message = error;
        }
    %>
    <span id="msg"><%=message %></span>

<!--这里使用form表单,post请求 -->
    <form action="/servlettest/login" method="post">
        用 户:<input type="text" name="username" /><br/>
        密 码:<input type="password" name="password" /><br/>
            <input type="submit" value="登录" />
    </form>

</body>
</html>
第八步:新建WebRoot/success.jsp(登录成功页面)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录成功页面</title>
</head>
<body>
    <%
    String username =(String)session.getAttribute("username");
    if(username == null){
        request.setAttribute("error", "您还未登录,登录后再来吧!");
        request.getRequestDispatcher("/login.jsp").forward(request, response);
        return;
    }
    %>
    欢迎用户<%=username %>到来

    <form action="/servletTest/CalcServlet" method="post">
    请输入数值:<input type="text" name="num1" /><br/>
    请输入数值:<input type="text" name="num2" /><br/>
            <input type="submit" value="计算" />
    </form>     
</body>
</html>
第九步:新建WebRoot/result.jsp(计算结果页面)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>计算结果页面</title>
</head>
<body>
    <%
    String username =(String)session.getAttribute("username");
    if(username == null){
        request.setAttribute("error", "您还未登录,登录后再来吧!");
        request.getRequestDispatcher("/login.jsp").forward(request, response);
        return;
    }
    %>
    欢迎用户<%=username %>到来<br/>
    <%
     Integer sum = (Integer)request.getAttribute("sum");
    %>
    计算的结果为:<%=sum %>
</body>
</html>
第十步:配置web文件。路径:WebRoot/WEB-INF/web.xml

这里是学习servlet的重点内容。如何定义servlet.

<?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>
       <description>This is the description of my J2EE component</description>
       <display-name>This is the display name of my J2EE component</display-name>
         <!-- 定义servlet的处理器名称和处理器所在路径。定义的名称必须和下面的映射器写的名称一致 -->
         <servlet-name>myloginServlet</servlet-name>
       <servlet-class>loginServlet</servlet-class>
     </servlet>
<!-- 定义映射器,拦截URL请求,映射到定义的控制器loginServlet中,去找到对应的处理方法 -->
     <servlet-mapping>
       <servlet-name>myloginServlet</servlet-name>
       <!-- servlet 的url-pattern规则 -->
       <url-pattern>/</url-pattern>
     </servlet-mapping>

</web-app>
第十一步:把项目配置到tomcat,

输入:http://localhost:8080/servletTest/login.jsp

进入登录页面
这里写图片描述
输入用户名和密码:
这里写图片描述
跳转到登录成功页面:
这里写图片描述
输入计算的数值 3+2
这里写图片描述
跳转到计算结果页面:
这里写图片描述

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值