一:示例
//model层(Student.java)
- package com.model;
- public class Student {
- private int id;
- private String userName;
- private String userPwd;
- public Student(int id, String userName, String userPwd) {
- super();
- this.id = id;
- this.userName = userName;
- this.userPwd = userPwd;
- }
- public Student(String userName, String userPwd) {
- super();
- this.userName = userName;
- this.userPwd = userPwd;
- }
- 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 getUserPwd() {
- return userPwd;
- }
- public void setUserPwd(String userPwd) {
- this.userPwd = userPwd;
- }
- }
//dao层(DbManager.java)
用数据源连接数据库,注意要将数据库驱动包添加到Tomcat ,lib目录下。
- package com.dao;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import javax.naming.Context;
- import javax.naming.InitialContext;
- import javax.naming.NamingException;
- import javax.sql.DataSource;
- public class DbManager {
- public static Connection getConnection(){
- Connection conn = null;
- try {
- Context context = new InitialContext();
- DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/test");
- conn = ds.getConnection();
- } catch (NamingException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return conn;
- }
- public static void closeConnection(Connection conn, PreparedStatement pst,ResultSet rs){
- try{
- if(rs !=null){
- rs.close();
- }
- if(pst !=null){
- pst.close();
- }
- if(conn !=null){
- conn.close();
- }
- }catch(SQLException e){
- e.printStackTrace();
- }
- }
- }
//StudentDao.java
- package com.dao;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
- import com.model.Student;
- public class StudentDao {
- public List<Student> findName(Student student){
- Connection conn = null;
- PreparedStatement pst = null;
- ResultSet rs = null;
- List<Student> list = new ArrayList<Student>();
- try {
- conn = DbManager.getConnection();
- conn.setAutoCommit(false);
- pst = conn.prepareStatement("select * from student where userName=? and userPwd=?");
- pst.setString(1, student.getUserName());
- pst.setString(2, student.getUserPwd());
- rs = pst.executeQuery();
- while (rs.next()){
- list.add(new Student(rs.getString(1),rs.getString(2)));
- }
- conn.commit();
- } catch (SQLException e) {
- try {
- conn.rollback();
- } catch (SQLException e1) {
- e1.printStackTrace();
- }
- e.printStackTrace();
- }finally{
- DbManager.closeConnection(conn, pst, rs);
- }
- return list;
- }
- public int create(Student student){
- Connection conn = null;
- PreparedStatement pst = null;
- int state = 0;
- try {
- conn = DbManager.getConnection();
- conn.setAutoCommit(false);
- pst = conn.prepareStatement("insert into student values(?,?)");
- pst.setString(1, student.getUserName());
- pst.setString(2, student.getUserPwd());
- state = pst.executeUpdate();
- conn.commit();
- }catch (SQLException e) {
- try {
- conn.rollback();
- } catch (SQLException e1) {
- e1.printStackTrace();
- }
- e.printStackTrace();
- } finally {
- DbManager.closeConnection(conn, pst, null);
- }
- return state;
- }
- }
//服务层service(StudentService.java)
- package com.service;
- import java.util.List;
- import com.model.Student;
- public interface StudentService {
- public List<Student> findName(Student student);
- public int create(Student student);
- }
//实现层(StudentServiceImpl.java)
- package com.service.impl;
- import java.util.List;
- import com.dao.StudentDao;
- import com.model.Student;
- import com.service.StudentService;
- public class StudentServiceImpl implements StudentService {
- private StudentDao studentDao;
- public StudentServiceImpl() {
- studentDao = new StudentDao();
- }
- public List<Student> findName(Student student) {
- return studentDao.findName(student);
- }
- public int create(Student student) {
- return studentDao.create(student);
- }
- }
//action层
//StringUtil.java
- package com.action;
- public class StringUtil {
- public static boolean isBlank(String str) {
- return str == null || str.trim().length() == 0;
- }
- }
//StudentServlet.java
- package com.action;
- import java.io.IOException;
- import java.util.List;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import com.model.Student;
- import com.service.StudentService;
- import com.service.impl.StudentServiceImpl;
- public class StudentServlet extends HttpServlet {
- private StudentService studentService;
- public StudentServlet() {
- studentService = new StudentServiceImpl();
- }
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request, response);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html");
- request.setCharacterEncoding("utf-8");
- response.setCharacterEncoding("utf-8");
- String userName = request.getParameter("userName");
- String userPwd = request.getParameter("userPwd");
- System.out.println(userName);
- System.out.println(userPwd);
- if(StringUtil.isBlank(userName)&&(StringUtil.isBlank(userPwd))){
- request.setAttribute("error","姓名和密碼錯誤!");
- request.getSession().setAttribute("login", "/login");
- request.getRequestDispatcher("/login").forward(request, response);
- return;
- }
- List<Student> list = studentService.findName(new Student(userName,userPwd));
- if(list.size()>0){
- request.getSession().setAttribute("login", list.get(0));
- request.getRequestDispatcher("/chapter1.jsp").forward(request, response);
- }else{
- request.setAttribute("error", "账号和密码错误!");
- request.getSession().setAttribute("login2", "login2");
- request.getRequestDispatcher("/login").forward(request, response);
- return;
- }
- }
- }
//RigesterServlet.java
- package com.action;
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import com.model.Student;
- import com.service.StudentService;
- import com.service.impl.StudentServiceImpl;
- public class RigesterServlet extends HttpServlet {
- private StudentService studentService;
- public RigesterServlet() {
- studentService = new StudentServiceImpl();
- }
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request, response);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html");
- request.setCharacterEncoding("utf-8");
- response.setCharacterEncoding("utf-8");
- String userName = request.getParameter("userName");
- String userPwd = request.getParameter("userPwd");
- String pwd2 = request.getParameter("pwd2");
- request.setAttribute("userName", userName);
- request.setAttribute("userPwd", userPwd);
- request.setAttribute("pwd2", pwd2);
- if(StringUtil.isBlank(userName)){
- request.setAttribute("userName", userName);
- request.getRequestDispatcher("/register").forward(request, response);
- return;
- }
- if(StringUtil.isBlank(userPwd)){
- request.setAttribute("userPwd", userPwd);
- request.getRequestDispatcher("/register").forward(request, response);
- return;
- }
- if(StringUtil.isBlank(pwd2)){
- request.setAttribute("pwd2", pwd2);
- request.getRequestDispatcher("/register").forward(request, response);
- return;
- }
- Student student = new Student(userName,userPwd);
- if(studentService.create(student)>0){
- request.getRequestDispatcher("/chapter2.jsp").forward(request, response);
- }
- }
- }
//context.xml 数据源配置文件
- <Context>
- <Resource name="jdbc/test" auth="Container"
- type="javax.sql.DataSource" maxActive="100" maxIdle="30"
- maxWait="10000" username="sa" password="admin"
- driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
- url="jdbc:sqlserver://localhost:1433;DatabaseName=test" />
- </Context>
//login.jsp
- <%@ page language="java" pageEncoding="utf-8"%>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <c:set var="bathPath" value="${pageContext.request.contextPath}"/>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- </head>
- <body>
- <div>
- <form action="${bathPath}/StudentServlet" method="post">
- <div>
- <label>用户名:</label>
- <label><input type="text" name="userName" /></label><br />
- <label>密 碼:</label>
- <label><input type="password" name="userPwd" /></label>
- </div>
- <div>
- <label><input type="submit" value="登錄" /></label>
- <label><input type="button" value="註冊" οnclick="window.location='${bathPath}/register'"/></label>
- </div>
- </form>
- </div>
- </body>
- </html>
//register.jsp
- <%@ page language="java" pageEncoding="utf-8"%>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <c:set var="bathPath" value="${pageContext.request.contextPath}"/>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- </head>
- <body>
- <div>
- <form action="${bathPath}/RigesterServlet" method="post">
- <div>
- <label for="username" class="label">用 户 名:</label>
- <input type="text" name="userName"/>
- <label id="chage1"></label><br/>
- <label for="username">*正确填写用户名,6-12位之间请用英文小写、下划线、数字。</label><br/>
- <label for="pwd1">用户密码:</label>
- <input type="password" name="userPwd" /><br/>
- <label for="pwd1">*正确填写密码,6-12位之间请用英文小写、下划线、数字。</label><br/>
- <label for="pwd2">确认密码:</label>
- <input type="password" name="pwd2"/><br/>
- <label for="pwd2">*两次密码要一致,请用英文小写、下划线、数字。</label><br/>
- </div>
- <div>
- <label><input type="submit" value="註冊" /></label>
- <label><input type="reset" value="取消" /></label>
- </div>
- </form>
- </div>
- </body>
- </html>