web实验报告——MVC模式

实验十 MVC 的实现
一、实验目的
通过实验掌握下列知识 :
1 、掌握 MVC 的基本概念
2 、掌握符合 MVC 架构的 web 应用的开发方法
 
二、实验内容及步骤
1 MVC 的实现
1 )按照下图设计并实现网页内容:
  
                              图( 1
a)          开发符合 MVC 架构的 web 应用以实现以上页面功能及流向;
b)          首页包含用户登录表单以及用户注册的链接
c)                 用户登录时,使用 js 技术对用户填写的信息进行简单检查( onSubm
it=”return  调用函数名 >… ),若检查出错需在首页上提示错误信息;若语法检查通过,则判断用户名是否存在数据库中等,若出现错误则显示报错页面( failed.jsp );若无错误发生则显示欢迎页面,显示 欢迎您, ***”
d)         (补充, 2-3 人小组完成)
注册页面包含新用户信息注册表单,用户提交后能使用 js 技术对用户填写的信息进行简单检查,若检查出错在注册页面上提示错误信息;若语法检查通过,则判断用户名是否已存在数据库中等,若出现错误则显示报错页面( failed.jsp );若无错误发生则将新用户记录在数据库中,并显示欢迎页面,显示 欢迎您, ***”
不知为何,我用 MyEclipse 编写的 js 总是不能使用,所以第 c 题和第 d 题,我现在采用了是判断直接写到 servlet 中,用它来做相关判断
 
 
一.登录模块:

登录界面:

源代码:
<%@  page language="java" contentType="text/html; charset=GB2312"
    pageEncoding="GB2312"%>
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=GB2312">
< title > 用户登录 title >
head >
< body >
 
 
< form  id="mainform" action="/TestMVC/servlet/CheckLogin" method="post">
用户名: < input  type=text name=loginName size=20><br>
密码:     < input  type=password name=password size=20><br>
< input  type=submit value=" 登录 "  onclick="">
form >
< a  href ="Register.jsp"> 注册
a >
body >
html >
 
用于调度的 Servlet
import  java.io.IOException;
import  java.io.PrintWriter;
 
import  javax.servlet.RequestDispatcher;
import  javax.servlet.ServletException;
import  javax.servlet.http.HttpServlet;
import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;
import  javax.servlet.http.HttpSession;
import  user.User;
 
 
public class  CheckLogin  extends  HttpServlet {
 
     /**
      * Constructor of the object.
      */
     public  CheckLogin() {
        super ();
    }
 
     /**
      * Destruction of the servlet .
      */
     public void  destroy() {
        super .destroy();  // Just puts "destroy" string in log
        // Put your code here
    }
 
     /**
      * The doGet method of the servlet .
      *
      * This method is called when a form has its tag value method equals to get.
      *
      * @param request the request send by the client to the server
      * @param response the response send by the server to the client
      * @throws ServletException if an error occurred
      * @throws IOException if an error occurred
      */
     public void  doGet(HttpServletRequest request, HttpServletResponse response)
            throws  ServletException, IOException {
        /*
       String loginName = request.getParameter("loginName");
       String password = request.getParameter("password");
       response.setContentType("text/html");
       PrintWriter out = response.getWriter();
       User user = new User(loginName,password);
       if(user.login()){
           out.println("Login OK");
       }
       else{
           out.println("Failed to Login");
       }
       */
       PrintWriter out = response.getWriter();
       out.println( "hgioahogia" );
          
    }
 
     /**
      * The doPost method of the servlet .
      *
      * This method is called when a form has its tag value method equals to post.
      *
      * @param request the request send by the client to the server
      * @param response the response send by the server to the client
      * @throws ServletException if an error occurred
      * @throws IOException if an error occurred
      */
     public void  doPost(HttpServletRequest request, HttpServletResponse response)
            throws  ServletException, IOException {
       String loginName = request.getParameter( "loginName" );
       String password = request.getParameter( "password" );
        // 加入数据为空 , 则直接返回登录界面
        if (loginName== null ||loginName.equals( "" )||password== null ||password.equals( "" )){
           response.sendRedirect( "/TestMVC/Login.jsp" ); 
       }
        else {
           response.setContentType( "text/html" );
           PrintWriter out = response.getWriter();
           User user =  new  User(loginName,password);
           out.println(user.getLoginName());
            if (ManageUser.userLogin(user)){
              out.println( "Login OK" );
              HttpSession session = request.getSession();
              session.setAttribute( "key" , user);
             
              RequestDispatcher dispatcher = request.getRequestDispatcher( "/Welcome.jsp" );
              dispatcher.forward(request, response);
           }
            else {
              RequestDispatcher dispatcher = request.getRequestDispatcher( "/Failed.jsp" );
              dispatcher.forward(request, response);
           }
       }
      
    }
 
     /**
      * Initialization of the servlet .
      *
      * @throws ServletException if an error occurs
      */
     public void  init()  throws  ServletException {
        // Put your code here
    }
}
 
Javabean
User.java ,用来暂时存储用户的相关信息,相当于程序和数据库数据的中间层
package  user;
public class  User {
    String  loginName = "" ;
    String  password = "" ;
    String  username = "" ;
    String  sex = "" ;
    String  age = "" ;
    String  home = "" ;
    String  Email = "" ;
    String  phone = "" ;
    String  location = "" ;
    String  QQNumber = "" ;
   
     public  User(){}
   
     // 注册时候的构造函数
     public  User(String loginName, String password, String username, String sex,
           String age, String home, String email, String phone,
           String location, String number) {
        super ();
        this . loginName  = loginName;
        this . password  = password;
        this . username  = username;
        this . sex  = sex;
        this . age  = age;
        this . home  = home;
        Email  = email;
        this . phone  = phone;
        this . location  = location;
        QQNumber  = number;
    }
   
     // 判断时候可以登录时的构造函数
     public  User(String loginName, String password) {
        super ();
        this . loginName  = loginName;
        this . password  = password;
    }
   
     public  String getLoginName() {
        return loginName ;
    }
     public void  setLoginName(String loginName) {
        this . loginName  = loginName;
    }
     public  String getPassword() {
        return password ;
    }
     public void  setPassword(String password) {
        this . password  = password;
    }
     public  String getUsername() {
        return username ;
    }
     public void  setUsername(String username) {
        this . username  = username;
    }
     public  String getSex() {
        return sex ;
    }
     public void  setSex(String sex) {
        this . sex  = sex;
    }
     public  String getAge() {
        return age ;
    }
     public void  setAge(String age) {
        this . age  = age;
    }
     public  String getHome() {
        return home ;
    }
     public void  setHome(String home) {
        this . home  = home;
    }
     public  String getEmail() {
        return Email ;
    }
     public void  setEmail(String email) {
        Email  = email;
    }
     public  String getPhone() {
        return phone ;
    }
     public void  setPhone(String phone) {
        this . phone  = phone;
    }
     public  String getLocation() {
        return location ;
    }
     public void  setLocation(String location) {
        this . location  = location;
    }
     public  String getQQNumber() {
        return QQNumber ;
    }
     public void  setQQNumber(String number) {
        QQNumber  = number;
    }
   
}
 
ManageUser .java ,用来管理对用户的相关操作
import  java.sql.Connection;
import  java.sql.ResultSet;
import  java.sql.SQLException;
import  java.sql.Statement;
 
import  user.User;
 
 
public class  ManageUser {
     public static boolean  userLogin(User user){
        boolean  flag =  true ;
       String loginName = user.getLoginName();
       String password = user.getPassword();
       Connection conn = UserDB.getConn();
       Statement stmt = UserDB.getStatement(conn);
       String sql =  "select * from TUser where loginName='" +loginName+ "' and password='" +password+ "'" ;
       ResultSet rs = UserDB.getResultSet(stmt, sql);
 
        try  {
            if (rs.next()){
              flag =  true ;
           }
            else {
              flag =  false ;
           }
       }  catch  (SQLException e) {
           e.printStackTrace();
       }
          
       UserDB.close(rs);
       UserDB.close(stmt);
       UserDB.close(conn);
        return  flag;
    }
   
     public static boolean  usrRegister(User user){
        boolean  flag =  true ;
       String loginName = user.getLoginName();
       Connection conn = UserDB.getConn();
       Statement stmt = UserDB.getStatement(conn);
       String sql =  "select * from TUser where loginName='" +loginName+ "' " ;
       ResultSet rs = UserDB.getResultSet(stmt, sql);
 
        try  {
            if (rs.next()){
              flag =  true ;
           }
            else {
              flag =  false ;
           }
       }  catch  (SQLException e) {
           e.printStackTrace();
       }
          
       UserDB.close(rs);
       UserDB.close(stmt);
       UserDB.close(conn);
        return  flag;
    }
   
     public static void  storeToDB(User user){
       String loginName = user.getLoginName();
       String password = user.getPassword();
       String username = user.getUsername();
       String sex = user.getSex();
       String age = user.getAge();
       String home = user.getHome();
       String Email = user.getEmail();
       String phone = user.getPhone();
       String location = user.getLocation();
       String QQNumber = user.getQQNumber();
      
      
      
       Connection conn = UserDB.getConn();
      
       Statement stmt = UserDB.getStatement(conn);
       String sql =  "insert into TUser(loginName,password,username,sex,age,home,Email,phone,location,QQNumber) values('" +loginName+ "','" +password+ "','" +username+ "','" +sex+ "','" +age+ "','" +home+ "','" +Email+ "','" +phone+ "','" +location+ "','" +QQNumber+ "') " ;
       System. out .println(sql);
        /*
       String sql = "insert into TUser(loginName,password,username,sex,age,home,Email,phone,location,QQNumber)"
                      +"values('IAMNO1','123456','wade','male','24','zhejiang','wade428@163.com','15068860574','zjut','1111')";
       */
       UserDB.executeUpdate(stmt, sql);
      
       UserDB.close(stmt);
       UserDB.close(conn);
    }
   
     // 判断是否是合格的 Email 格式
     public static boolean  isEmail(String Email){
        boolean  flag =  true ;
        int  locationDot = Email.indexOf( "." );
        int  locationAt = Email.indexOf( "@" );
        //.  @ 中至少一个不存在
        if (locationDot<0||locationAt<0){
           flag =  false ;
       }
        //@ 前面没有任何字符
        else if (locationAt==0){
           flag =  false ;
       }
        //. @ 前面,或者 @ . 之间没有任何字符
        else if (locationDot-1<=locationAt){
           flag =  false ;
       }
        //. 后面没有字符了
        else if (locationDot==Email.length()-1){
           flag =  false ;
       }  
        return  flag;     
    }
 
}
 
ManageUser .java ,对 JDBC 进行了相应地封装,用于从数据库中读取和存放数据,
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  user.User;
 
 
public class  UserDB {
     public static  Connection getConn() {
       Connection conn =  null ;
        try  {
           Class.forName( "com.microsoft.jdbc.sqlserver.SQLServerDriver" );
           conn = DriverManager.getConnection( "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=User" , "test" , "test" );
       }  catch  (ClassNotFoundException e) {
           e.printStackTrace();
       }  catch  (SQLException e) {
           e.printStackTrace();
       }  
        return  conn;
    }
   
     public static  PreparedStatement prepare(Connection conn, String sql) {
       PreparedStatement pstmt =  null ;
        try  {
            if (conn !=  null ) {
              pstmt = conn.prepareStatement(sql);
           }
       }  catch  (SQLException e) {
           e.printStackTrace();
       }
        return  pstmt;
    }
   
 
   
     public static  Statement getStatement(Connection conn) {
       Statement stmt =  null ;
        try  {
            if (conn !=  null ) {
              stmt = conn.createStatement();
           }
       }  catch  (SQLException e) {
           e.printStackTrace();
       }
        return  stmt;
    }
   
   
     public static  ResultSet getResultSet(Statement stmt, String sql) {
       ResultSet rs =  null ;
        try  {
            if (stmt !=  null ) {
              rs = stmt.executeQuery(sql);
           }
       }  catch  (SQLException e) {
           e.printStackTrace();
            return null ;
       }
        return  rs;
    }
   
     public static void  executeUpdate(Statement stmt, String sql) {
        try  {
            if (stmt !=  null ) {
              stmt.executeUpdate(sql);
           }
       }  catch  (SQLException e) {
           e.printStackTrace();
       }
    }
   
     public static void  close(Connection conn) {
        try  {
            if (conn !=  null ) {
              conn.close();
              conn =  null ;
           }
       }  catch  (SQLException e) {
           e.printStackTrace();
       }
    }
   
     public static void  close(Statement stmt) {
        try  {
            if (stmt !=  null ) {
              stmt.close();
              stmt =  null ;
           }
       }  catch  (SQLException e) {
           e.printStackTrace();
       }
    }
   
     public static void  close(ResultSet rs) {
        try  {
            if (rs !=  null ) {
              rs.close();
              rs =  null ;
           }
       }  catch  (SQLException e) {
           e.printStackTrace();
       }
    }
     /*
    public static void main(String[] args) throws SQLException{
       Connection conn = UserDB.getConn();
       Statement stmt = UserDB.getStatement(conn);
       ResultSet rs = UserDB.getResultSet(stmt, "select * from TUser ");
       while(rs.next())
       {
           System.out.println(rs.getString("loginName"));
          
       }
    }
    */  
}
 
数据库中的具体信息

 

 
注册模块
注册界面:
 
源代码:
<%@  page language="java" import="java.util.*" pageEncoding="gbk"%>
 
< html >
  < head >
     < title > 注册 title >
  head >  
  < body >
 
  < form  name ="register" action="/TestMVC/servlet/CheckRegister" method="post">
  < table >
   < tr >
        < td > 用户登陆名 td >
        < td >
           < input  name="loginName" type="text" size=20 >
        td >
   tr >
      < tr >
        < td > 密码 td >
        < td >
           < input  name=password type="password" size=20 >
        td >
   tr >
      < tr >
        < td > 确认密码 td >
        < td >
           < input  name="passwordConfirm" type="password" size=20 >
        td >
   tr >
      < tr >
        < td > 真实姓名 td >
        < td >
           < input  name="username" type="text" size=20 >
        td >
   tr >
      < tr >
        < td > 性别 td >
        < td >
           < input  name="sex" type="radio" value="man" checked="checked">   
           < input  name="sex" type="radio" value="woman">
        td >
   tr >
      < tr >
        < td > 出生年月 td >
        < td >
            < input  name="age" type="text" size=20>
        td >
   tr >  
    < tr >
        < td > 籍贯 td >
        < td >
            < input  name="home" type="text" size=20>
        td >
   tr >
      < tr >
        < td > Email td >
        < td >
            < input  name="Email" type="text" size=20>
        td >
   tr >
   < tr >
        < td > 联系电话 td >
        < td >
            < input  name="phone" type="text" size=20>
        td >
   tr >
   < tr >
        < td > 联系地址 td >
         < td >
            < input  name="location" type="text" size=20>
        td >
   tr >
   < tr >
        < td > QQ td >
        < td >
            < input  name="QQNumber" type="text" size=20>
        td >
   tr >
  
      
   < tr >
        < td >
        < input  name="submit" type="submit" value=" 提交 " >
        td >
   tr >
 
  table >
  form >
  body >
html >
 
 
Servlet
CheckRegister.java
 
import  java.io.IOException;
import  java.io.PrintWriter;
 
import  javax.servlet.RequestDispatcher;
import  javax.servlet.ServletException;
import  javax.servlet.http.HttpServlet;
import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;
import  javax.servlet.http.HttpSession;
import  user.User;
 
 
public class  CheckRegister  extends  HttpServlet {
 
     /**
      * Constructor of the object.
      */
     public  CheckRegister() {
        super ();
    }
 
     /**
      * Destruction of the servlet .
      */
     public void  destroy() {
        super .destroy();  // Just puts "destroy" string in log
        // Put your code here
    }
 
     /**
      * The doGet method of the servlet .
      *
      * This method is called when a form has its tag value method equals to get.
      *
      * @param request the request send by the client to the server
      * @param response the response send by the server to the client
      * @throws ServletException if an error occurred
      * @throws IOException if an error occurred
      */
     public void  doGet(HttpServletRequest request, HttpServletResponse response)
            throws  ServletException, IOException {
 
       response.setContentType( "text/html" );
       PrintWriter out = response.getWriter();
       out
              .println( "" );
       out.println( "" );
       out.println( A Servlet" );
       out.println( " " );
       out.print( "    This is " );
       out.print( this .getClass());
       out.println( ", using the GET method" );
       out.println( " " );
       out.println( "" );
       out.flush();
       out.close();
    }
 
     /**
      * The doPost method of the servlet .
      *
      * This method is called when a form has its tag value method equals to post.
      *
      * @param request the request send by the client to the server
      * @param response the response send by the server to the client
      * @throws ServletException if an error occurred
      * @throws IOException if an error occurred
      */
     public void  doPost(HttpServletRequest request, HttpServletResponse response)
            throws  ServletException, IOException {
 
       response.setContentType( "text/html" );
       PrintWriter out = response.getWriter();
       request.setCharacterEncoding( "gb2312" );
 
        // 得到各个各个参数
       String StrLoginName = request.getParameter( "loginName" );
       String StrPassword = request.getParameter( "password" );
       String StrpasswordConfirm = request.getParameter( "passwordConfirm" );
       String Strusername = request.getParameter( "username" );
        String StrSex = request.getParameter( "sex" );
       String StrAge = request.getParameter( "age" );
       String StrHome = request.getParameter( "home" );
       String StrEmail = request.getParameter( "Email" );
       String Strphone = request.getParameter( "phone" );
       String StrLocation = request.getParameter( "location" );
       String StrQQNumber = request.getParameter( "QQNumber" );
      
        // 判断输入进来的格式是否正确
        // 用户名为空
        if (StrLoginName== null ||StrLoginName.equals( "" )){
           response.sendRedirect( "/TestMVC/Register.jsp" ); 
       }
        // 密码或确认密码为空,或者两者不一致
        else if (StrPassword== null ||StrPassword.equals( "" )||
              StrpasswordConfirm== null ||StrpasswordConfirm.equals( "" )||
              !StrpasswordConfirm.equals(StrPassword)){
           response.sendRedirect( "/TestMVC/Register.jsp" );     
       }
        else if (!ManageUser.isEmail(StrEmail)){
           response.sendRedirect( "/TestMVC/Register.jsp" ); 
       }
      
        else {
           User user =  new  User(StrLoginName,StrPassword,Strusername,StrSex,StrAge,
                  StrHome,StrEmail,Strphone,StrLocation,StrQQNumber);
          
          
            if (!ManageUser.usrRegister(user)){
              ManageUser.storeToDB(user);
              HttpSession session = request.getSession();
              session.setAttribute( "key" , user);
             
              RequestDispatcher dispatcher = request.getRequestDispatcher( "/Welcome.jsp" );
              dispatcher.forward(request, response);
           }
            else {
              RequestDispatcher dispatcher = request.getRequestDispatcher( "/Failed.jsp" );
              dispatcher.forward(request, response);
           }
       }
    }
 
     /**
      * Initialization of the servlet .
      *
      * @throws ServletException if an error occurs
      */
     public void  init()  throws  ServletException {
        // Put your code here
    }
 
}
 
JavaBean:
注册用的 JavaBean 与登录时的是一样的,这里就不再复述了
 
 
欢迎界面:
Welcome.jsp
运行效果:

 

源代码:
<%@  page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@  page contentType="text/html;charset=gb2312" %>
<%@  page import="user.User"%>
 
 
DOCTYPE  HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
< html >
  < head >
  head >
 
  < body >
   
 
     < br > You are Welcomed,
     < jsp:useBean  id="key" type="user.User" scope="session"/>
     < jsp:getProperty  name="key" property="loginName"/>
   < br >
   
  body >
html >
 
报错界面:
Failed.jsp

运行效果:

<%@  page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@  page contentType="text/html;charset=gb2312" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+ "://" +request.getServerName()+ ":" +request.getServerPort()+path+ "/" ;
%>
 
DOCTYPE  HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
< html >
  < head >
     < base  href="<%=basePath%>">
   
     < title > My JSP 'Failed.jsp' starting page title >
   
     < meta  http-equiv="pragma" content="no-cache">
     < meta  http-equiv="cache-control" content="no-cache">
     < meta  http-equiv="expires" content="0">   
     < meta  http-equiv="keywords" content="keyword1,keyword2,keyword3">
     < meta  http-equiv="description" content="This is my page">
    
 
  head >
 
  < body >
    Failed to login < br >
  body >
html >

你可能感兴趣的:(JAVA)