JSP基於MVC 使用者登入的例子(JavaBean + Servlet)

來源:互聯網
上載者:User

 

我們來看互動圖

例子一,

基於MVC 使用者登入的實現(JavaBean + Servlet + JSP)

1、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>
<servlet-name>loginServlet</servlet-name>
<servlet-class>org.zxj.mvcdemo.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>

 

2、User

 

package org.zxj.mvcdemo.vo;

public class User{
private String userid;
private String name;
private String password;
public void setUSerid(String userid){
this.userid = userid;
}
public void setName (String name){
this.name = name;
}
public void setPassword(String password){
this.password = password;
}
public String getUserid(){
return this.userid;
}
public String getName(){
return this.name;
}
public String getPassword(){
return this.password;
}

}

 

3、DatabaseConnection

 

package org.zxj.mvcdemo.dbc;

import java.sql.*;

public class DatabaseConnection{

private static final String DBDRIVER = “com.mysql.jdbc.Driver”;
private static final String DBURL = “jdbc:mysql://localhost:3306/zxj”;
private static final String DBUSER = “root”;
private static final String DBPASSWORD =”pf”;
private static Connection con = null;
public DatabaseConnection() throws Exception{
try{
Class.forName(DBDRIVER);
this.con = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD);
}catch(Exception e){
throw e;
}
}
public Connection getConnection(){
return this.con;
}
public void close() throws Exception {
if(this.con != null){
try{
this.con.close();
}catch(Exception e){
throw e;
}
}
}
}

 

4、IUserDAO

 

package org.zxj.mvcdemo.dao;

import org.zxj.mvcdemo.vo.User;

public interface IUserDAO{
public boolean findLogin(User user) throws Exception;
}

 

5、UserDAOImpl

 

package org.zxj.mvcdemo.dao.impl;

import org.zxj.mvcdemo.vo.User;
import org.zxj.mvcdemo.dao.*;
import java.sql.*;

public class UserDAOImpl implements IUserDAO{
private Connection conn = null;
private PreparedStatement pstmt = null;
public UserDAOImpl(Connection conn){
this.conn = conn;
}
public boolean findLogin(User user) throws Exception{
boolean flag = false;
String sql = “select name from user where userid= ? and password = ?”;
this.pstmt = this.conn.prepareStatement(sql);
this.pstmt.setString(1,user.getUserid());
this.pstmt.setString(2,user.getPassword());
ResultSet rs = this.pstmt.executeQuery();
if(rs.next()){
user.setName(rs.getString(“name”));
flag = true;
}
this.pstmt.close();
return flag;
}
}

 

6、UserDAOProxy

 

package org.zxj.mvcdemo.dao.proxy;

import org.zxj.mvcdemo.vo.User;
import org.zxj.mvcdemo.dbc.*;
import org.zxj.mvcdemo.dao.*;
import org.zxj.mvcdemo.dao.impl.*;
import java.sql.*;

public class UserDAOProxy implements IUserDAO{
private DatabaseConnection dbc = null;
private IUserDAO dao = null;
private PreparedStatement pstmt = null;
public UserDAOProxy(){
try{
this.dbc = new DatabaseConnection();
}catch(Exception e){
e.printStackTrace();
}
this.dao = new UserDAOImpl(dbc.getConnection());
}
public boolean findLogin(User user) throws Exception{
boolean flag = false;
try{
flag = this.dao.findLogin(user);
}catch(Exception e){
throw e;
}finally{
this.dbc.close();
}
return flag;
}
}

 

7、DAOFactory

 

 

package org.zxj.mvcdemo.factory;

import org.zxj.mvcdemo.dao.*;
import org.zxj.mvcdemo.dao.proxy.*;
public class DAOFactory{
public static IUserDAO getIUserDAOInstance(){
return new UserDAOProxy();
}
}

 

8、LoginServlet

package org.zxj.mvcdemo.servlet;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.zxj.mvcdemo.factory.*;
import org.zxj.mvcdemo.vo.*;

public class LoginServlet extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException {
String path = “login.jsp”;
String userid = req.getParameter(“userid”);
String userpass = req.getParameter(“userpass”);
List<String> info = new ArrayList<String>();
if(userid == null || “”.equals(userid)){
info.add(“使用者id不可為空”);
}
if(userpass == null || “”.equals(userpass)){
info.add(“密碼不可為空”);
}
if(info.size() == 0){
User user = new User();
user.setUSerid(userid);
user.setPassword(userpass);
try{
if(DAOFactory.getIUserDAOInstance().findLogin(user)){
info.add(“使用者登入成功,歡迎”+user.getName()+ “登入”);
}else{
info.add(“使用者登入失敗”);
}
}catch(Exception e){
e.printStackTrace();
}
}
req.setAttribute(“info”,info);
req.getRequestDispatcher(path).forward(req,res);
//RequestDispatcher rd = null;
//rd = req.getRequestDispatcher(path);
//rd.forward(req,res);

}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException {
doGet(req,res);
}
}

 

9、Login.jsp

 

 

 

<%@ page language=”java” contentType=”text/html” pageEncoding=”GBK” %>
<%@ page import=”java.util.*”%>
<html>
<head>
<title>登入</title>
<meta http-equiv=”content-type” content=”text/html;charset=gbk”>
</head>

<body>
<%
request.setCharacterEncoding(“GBK”);
List<String> info = (List<String>)request.getAttribute(“info”);
if(info != null){
Iterator<String> iter = info.iterator();
while(iter.hasNext()){
out.println(iter.next());
}
}
%>
<form action=”LoginServlet” method=”post”>
使用者:<input type=”text” name=”userid” /> <br />
密碼:<input type=”password” name=”userpass” /><br />
<input type=”submit” value=”登入” />
<input type=”reset” value=”重設” />
</body
</html>

例子二,

第一:JSP:由頁面指令和HTML組成的查詢介面query_condention.jsp,也就是咱們現在的html頁和asp頁面類似。


<%@ page language="java" contentType="text/html;charset=GBK"%>
<html>
 <head>
  <title>學生資訊</title>
 </head>
 <body>
  <form action="SearchStudentServlet" method="post">
   出生日期:<input type="text" name="beginDate">至<input type="text" name="endDate">
   <input type="submit" value="查詢學生">
  </form>
 </body>
</html>


第二:控制層 SearchStudentServlet用來接受客戶的請求,來處理流程,調用Model(StudentManager.java),轉寄到要請求的後台伺服器的student_list.jsp頁面

import java.text.*;
import java.util.*;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;

import com.bjpowernode.exam.model.*;
import com.bjpowernode.exam.manager.*;

public class SearchStudentServlet extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response) 
 throws ServletException, IOException {
  doPost(request, response);
 }
 
 public void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
  
  String sBeginDate = request.getParameter("beginDate");
  String sEndDate = request.getParameter("endDate");
  
  Date beginDate = new Date();
  Date endDate = new Date();
  try {
   beginDate = new SimpleDateFormat("yyyy-MM-dd").parse(sBeginDate);
    endDate = new SimpleDateFormat("yyyy-MM-dd").parse(sEndDate);
   }catch(Exception e) {
   e.printStackTrace();  
   } 
  
  StudentManager studentManager = new StudentManagerImpl();
  List<Student> studentList = studentManager.findStudentList(beginDate, endDate);
  
  //將學生列表設定到requet範圍中
  //request.setAttribute("student_list", studentList);
  
  //轉寄,轉寄是在伺服器端轉寄的,用戶端是不知道的
  //request.getRequestDispatcher("/student_list.jsp").forward(request, response);
  
  
  //將studentList放到session中
  HttpSession session = request.getSession();
  session.setAttribute("student_list", studentList);
  
  //重新導向,不會共用request
  //以下寫法錯誤,該 "/"代表了8080連接埠
  //response.sendRedirect("/student_list.jsp");
  response.sendRedirect(request.getContextPath() + "/student_list.jsp");
 }
}

第三 :student_list.jsp頁面接收資料形成html,返回到瀏覽器,渲染在介面上

<%@ page language="java" contentType="text/html;charset=GBK"%>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<%@ page import="com.bjpowernode.exam.model.*"%>
<%@ page import="com.bjpowernode.exam.manager.*"%>
<html>
 <head>
  <title>學生資訊</title>
  <style type="text/css">
   /*表格寬度為1px,實線,黑色*/
     table{
       border:1px solid black;  
       border-collapse:collapse;   
     }

     td {
       border:1px solid black;  
       border-collapse:collapse;   
     }
    
  </style>  
 </head>
 <body>
  <table border="1">
   <tr>
    <td>學生代碼</td>
    <td>姓名</td>
    <td>性別</td>
    <td>出生日期</td>
    <td>聯絡電話</td>
    <td>家庭住址</td>
    <td>班級名稱</td>
    <td>年齡</td>
   </tr>
   <%
    //List<Student>  studentList = (List)request.getAttribute("student_list");
    List<Student>  studentList = (List)session.getAttribute("student_list");
    for (Iterator<Student> iter=studentList.iterator(); iter.hasNext();) {
     Student student = iter.next();
   %>
   <tr>
    <td><%=student.getStudentId()%></td>
    <td><%=student.getStudentName()%></td>
    <td><%=student.getSex()%></td>
    <td><%=new SimpleDateFormat("yyyy-MM-dd").format(student.getBirthday())%></td>
    <td><%=student.getContactTel()%></td>
    <td><%=student.getAddress()%></td>
    <td><%=student.getClasses().getClassesName()%></td>
    <%
     long b = 1000L*60L*60L*24L*365L;
     long a = System.currentTimeMillis() - student.getBirthday().getTime();
    %>
    <td><%=a/b%></td>
   </tr>
   <%
    }
   %>
  </table>
 </body>
</html>

在View的student_list.jsp頁面中是大量的html和java代碼的混合,在查詢條件介面query_condention.jsp主要是html,因為不涉及後台資料的互動.


第四:xml配置Servlet:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
 <servlet>
  <servlet-name>SearchStudentServlet</servlet-name>
  <servlet-class>SearchStudentServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>SearchStudentServlet</servlet-name>
  <url-pattern>/SearchStudentServlet</url-pattern>
 </servlet-mapping>
 
</web-app>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.