首页 > 代码库 > Java Web Model2实战

Java Web Model2实战

本文进行model2模式的实战--登录模块的实现

采用MVC模式开发,具体模块分别如下:

JavaBean组件(Model)

User:封装用户对象

UserDao:封装用户数据库操作

DataBaseUtil:数据库连接工具类

JSP页面(View)

index.jsp:主页

reg.jsp:用户注册页面

login.jsp:用户登录页面

message.jsp:提示信息页面

Servlet(Controller)

RegServlet:用户注册Servlet类

LoginServlet:用户登录Servlet类

UserExitServlet:用户退出Servlet类

JavaBean设计

1、用户实体对象(User类)

User.java

public class User {
 private int id;
 private String username;
 private String password;
 private String sex;
 private String tel;
 private String photo;
 private String email;
 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;
 }
 public String getSex() {
 return sex;
 }
 public void setSex(String sex) {
 this.sex = sex;
 }
 public String getTel() {
 return tel;
 }
 public void setTel(String tel) {
 this.tel = tel;
 }
 public String getPhoto() {
 return photo;
 }
 public void setPhoto(String photo) {
 this.photo = photo;
 }
 public String getEmail() {
 return email;
 }
 public void setEmail(String email) {
 this.email = email;
 }
}

 

2、数据库连接工具类

DataBaseUtil.java

package com.wuyudong.util;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
public class DataBaseUtil {
 public static ConnectiongetConnection() {
 Connectionconn = null;
 try {
 Class.forName("com.mysql.jdbc.Driver");
 String url = "jdbc:mysql://localhost:3306/db_database05";
 conn = DriverManager.getConnection(url, "root", "wuyudong");
 } catch (Exception e) {
 e.printStackTrace();
 }
 return conn;
 }
 
 public static void closeConnection(Connectionconn) {
 if (conn != null) {
 try {
 conn.close();
 } catch (SQLException e) {
 e.printStackTrace();
 }
 }
 }
}

 

3、用户数据库操作

与用户相关的数据库操作方法被封装在UserDao类中

UserDao.java

package com.wuyudong.model.dao;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
 
import com.wuyudong.model.User;
import com.wuyudong.util.DataBaseUtil;
 
public class UserDao {
 public boolean userIsExist(String username) {
 Connectionconn = DataBaseUtil.getConnection();
 String sql = "select * from tb_user where username=?";
 try {
 // 获取PreparedStatement对象
 PreparedStatementps = conn.prepareStatement(sql);
 // 对用户对象属性赋值
 ps.setString(1, username);
 // 执行查询获取结果集
 ResultSetrs = ps.executeQuery();
 // 判断结果集是否有效
 if (!rs.next()) {
 return true;
 }
 rs.close();
 ps.close();
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 DataBaseUtil.closeConnection(conn);
 }
 return false;
 }
 
 public void saveUser(Useruser) {
 Connectionconn = DataBaseUtil.getConnection();
 String sql = "insert into tb_user(username,password,sex,tel,photo,email)values(?,?,?,?,?,?)";
 try {
 PreparedStatementps = conn.prepareStatement(sql);
 ps.setString(1, user.getUsername());
 ps.setString(2, user.getPassword());
 ps.setString(3, user.getSex());
 ps.setString(4, user.getTel());
 ps.setString(5, user.getPhoto());
 ps.setString(6, user.getEmail());
 ps.executeUpdate();
 ps.close();
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 DataBaseUtil.closeConnection(conn);
 }
 }
 public Userlogin(String username, String password) {
 Useruser=null;
 Connectionconn=DataBaseUtil.getConnection();
 String sql="select * from tb_user where username=? and password=?";
 try{
 PreparedStatementps=conn.prepareStatement(sql);
 ps.setString(1, username);
 ps.setString(2, password);
 ResultSetrs=ps.executeQuery();
 if(rs.next()){
 user=new User();
 user.setId(rs.getInt("id"));
 user.setUsername(rs.getString("username"));
 user.setPassword(rs.getString("password"));
 user.setSex(rs.getString("sex"));
 user.setTel(rs.getString("tel"));
 user.setPhoto(rs.getString("photo"));
 user.setEmail(rs.getString("email")); 
 }
 rs.close();
 ps.close();
 } catch(Exception e){
 e.printStackTrace();
 }finally{
 DataBaseUtil.closeConnection(conn);
 }
 return user;
 }
}

 

实现过程

1、用户注册

(1)创建RegServlet类对用户的注册进行处理

RegServlet.java

package com.wuyudong.service;
 
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.wuyudong.model.User;
import com.wuyudong.model.dao.UserDao;
 
public class RegServlet extends HttpServlet {
 private static final long serialVersionUID = -409981562297982450L;
 
 @Override
 protected void doPost(HttpServletRequestrequest,
 HttpServletResponseresponse) throws ServletException, IOException {
 // TODO Auto-generated method stub
 String username = request.getParameter("username");
 String password = request.getParameter("password");
 String sex = request.getParameter("sex");
 String photo = request.getParameter("photo");
 String tel = request.getParameter("tel");
 String email = request.getParameter("email");
 
 UserDaouserDao = new UserDao();
 if (username != null && !username.isEmpty()) {
 if (userDao.userIsExist(username)) {
 // 实例化一个对象
 Useruser = new User();
 // 对用户对象中的属性赋值
 user.setUsername(username);
 user.setPassword(password);
 user.setSex(sex);
 user.setPhoto(photo);
 user.setTel(tel);
 user.setEmail(email);
 // 保存用户注册信息
 userDao.saveUser(user);
 request.setAttribute("info", "恭喜,注册成功!<br>");
 } else {
 request.setAttribute("info", "错误:此用户名已存在!");
 }
 }
 // 转发到message.jsp页面
 request.getRequestDispatcher("message.jsp").forward(request, response);
 }
 
}

 

(2)创建视图层

reg.jsp

<%@ page language="java" contentType="text/html" pageEncoding="GBK"%>
<!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>用户注册</title>
    <linkrel="stylesheet" type="text/css" href="images/styles.css">
        <scripttype="text/javascript">
    function reg(form){
        if(form.username.value == ""){
        alert("用户不能为空!");
        return false;
        }
        if(form.password.value == ""){
        alert("密码不能为空!");
        return false;
        }
        if(form.repassword.value == ""){
        alert("确认密码不能为空!");
        return false;
        }
        if(form.password.value != form.repassword.value){
        alert("两次密码输入不一致!");
        return false;
        }
        if(form.tel.value == ""){
        alert("联系电话不能为空!");
        return false;
        }
        if(form.email.value == ""){
        alert("电子邮箱不能为空!");
        return false;
        }
    }
    function change(){
 var photo = document.getElementById("photo");
 var photoImg = document.getElementById("photoImg");
 photoImg.src = photo.value;
    }
    </script>
  </head>
  
  <body>
  <divalign="center">
  <divclass="div1">
  <divclass="top">用户登录</div>
  <divclass="bottom">
 <divclass="div2">
  <ul>
  <li><a href="reg.jsp">用户注册</a></li>
  <li><a href="login.jsp">用户登录</a></li>
  <li><a href="message.jsp">当前用户</a></li>
  <li><a href="UserExitServlet">用户退出</a></li>
  </ul>
  </div>
  <divclass="div3"> 
    <formaction="RegServlet" method="post" onsubmit="return reg(this);">
    <tablealign="center" width="450" border="0">
    <tr>
    <tdalign="right">用户名:</td>
    <td>
    <inputtype="text" name="username">
    </td>
    </tr>
    <tr>
    <tdalign="right">密 码:</td>
    <td>
    <inputtype="password" name="password">
    </td>
    </tr>
    <tr>
    <tdalign="right">确认密码:</td>
    <td>
    <inputtype="password" name="repassword">
    </td>
    </tr>
    <tr>
    <tdalign="right">性 别:</td>
    <td>
    <inputtype="radio" name="sex" value="男" checked="checked"><inputtype="radio" name="sex" value="女"></td>
    </tr>
    <tr>
    <tdalign="right">头 像:</td>
    <td>
    <selectname="photo" id="photo" onchange="change();">
    <optionvalue="images/1.gif" selected="selected">头像一</option>
    <optionvalue="images/2.gif">头像二</option>
    </select>
    <imgid="photoImg" src="images/1.gif">
    </td>
    </tr>
    <tr>
    <tdalign="right">联系电话:</td>
    <td>
    <inputtype="text" name="tel">
    </td>
    </tr>
    <tr>
    <tdalign="right">电子邮箱:</td>
    <td>
    <inputtype="text" name="email">
    </td>
    </tr>
    <tr>
    <tdcolspan="2" align="center">
    <inputtype="submit" value="注 册">
    <inputtype="reset" value="重 置">
    </td>
    </tr>
    </table>
    </form>
  </div>
 </div>
  </div>
  </div>
  </body>
</html>

 

2、用户登录

(1)创建LoginServlet类对用户的登录进行处理

LoginServlet.java

package com.wuyudong.service;
 
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.wuyudong.model.User;
import com.wuyudong.model.dao.UserDao;
 
public class LoginServlet extends HttpServlet {
 private static final long serialVersionUID = 1829331482363438909L;
 
 @Override
 protected void doPost(HttpServletRequestrequest,
 HttpServletResponseresponse) throws ServletException, IOException {
 // 获取用户名
 String username = request.getParameter("username");
 // 获取密码
 String password = request.getParameter("password");
 // 实例化DataDao对象
 UserDaouserDao = new UserDao();
 // 实例化User对象
 Useruser = userDao.login(username, password);
 if (user != null) {
 // 将用户对象放入Session中
 request.getSession().setAttribute("user", user);
 request.getRequestDispatcher("message.jsp").forward(request,
 response);
 } else {
 // 登录失败
 request.setAttribute("info", "错误:用户名或密码错误!");
 request.getRequestDispatcher("message.jsp").forward(request,
 response);
 }
 
 }
}

 

(2)创建视图

login.jsp

<%@ page language="java" contentType="text/html" pageEncoding="GBK"%>
<!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>用户登录</title>
    <linkrel="stylesheet" type="text/css" href="images/styles.css">
    <scripttype="text/javascript">
    function login(form){
        if(form.username.value == ""){
        alert("用户不能为空!");
        return false;
        }
        if(form.password.value == ""){
        alert("密码不能为空!");
        return false;
        }
    }
    </script>
  </head>
  
  <body>
  <divalign="center">
  <divclass="div1">
  <divclass="top">用户注册</div>
  <divclass="bottom">
 <divclass="div2">
  <ul>
  <li><a href="reg.jsp">用户注册</a></li>
  <li><a href="login.jsp">用户登录</a></li>
  <li><a href="message.jsp">当前用户</a></li>
  <li><a href="UserExitServlet">用户退出</a></li>
  </ul>
  </div>
  <divclass="div3"> 
    <formaction="LoginServlet" method="post" onSubmit="return login(this);">
    <tablealign="center" width="300" border="0" class="tb1">
    <tr>
    <tdalign="right">用户名:</td>
    <td>
    <inputtype="text" name="username">
    </td>
    </tr>
    <tr>
    <tdalign="right">密 码:</td>
    <td>
    <inputtype="password" name="password">
    </td>
    </tr>
    <tr>
    <tdcolspan="2" align="center" height="50">
    <inputtype="submit" value="登 录">
    <inputtype="reset" value="重 置">
    </td>
    </tr>
    </table>
 </form>
  </div>
 </div>
  </div>
  </div>
  </body>
</html>

 

3、用户退出

用户退出请求由UserExitServlet类进行处理

UserExitServlet.jsp

package com.wuyudong.service;
 
import java.io.IOException;
 
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 org.apache.catalina.User;
 
public class UserExitServlet extends HttpServlet {
 private static final long serialVersionUID = -1249523020574432559L;
 
 @Override
 protected void doPost(HttpServletRequestrequest,
 HttpServletResponseresponse) throws ServletException, IOException {
 // 获取session
 HttpSessionsession = request.getSession();
 // 获取用户对象
 Useruser = (User) session.getAttribute("user");
 // 判断用户是否有效
 if (user != null) {
 // 将用户对象逐出Session
 session.removeAttribute("user");
 // 设置提示信息
 session.setAttribute("info", user.getUsername() + "已经成功退出!");
 }
 // 转发到message.jsp页面
 request.getRequestDispatcher("message.jsp").forward(request, response);
 }
}

 

4、提示信息页面

程序在处理业务请求后,需要告知用户的处理结果

message.jsp

<%@ page language="java" contentType="text/html" pageEncoding="GBK"%>
<%@ page import="com.wuyudong.model.User" %>
<!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 <title>提示信息</title>
 <linkrel="stylesheet" type="text/css" href="images/styles.css">
 </head>
 
 <body>
 <divalign="center">
  <divclass="div1">
  <divclass="top">提示信息</div>
  <divclass="bottom">
 <divclass="div2">
  <ul>
  <li><a href="reg.jsp">用户注册</a></li>
  <li><a href="login.jsp">用户登录</a></li>
  <li><a href="message.jsp">当前用户</a></li>
  <li><a href="UserExitServlet">用户退出</a></li>
  </ul>
  </div>
  <divclass="div3"> 
    <% 
    // 获取提示信息
 String info = (String)request.getAttribute("info");
    // 如果提示信息不为空,则输出提示信息
 if(info != null){
 out.println(info);
 }
    // 获取登录的用户信息
 User user = (User)session.getAttribute("user");
    // 判断用户是否登录
 if(user != null){
 %>
 <tablealign="center" width="350" border="1" height="200" bordercolor="#E8F4CC">
 <tr>
    <tdalign="center" colspan="2">
    <spanstyle="font-weight: bold;font-size: 18px;"><%=user.getUsername() %></span>
    登录成功!
    </td>
    </tr>
    <tr>
    <tdalign="right" width="30%">头 像:</td>
    <td>
    <imgsrc="<%=user.getPhoto()%>">
    </td>
    </tr>
    <tr>
    <tdalign="right">性 别:</td>
    <td><%=user.getSex()%></td>
    </tr>
    <tr>
    <tdalign="right">联系电话:</td>
    <td><%=user.getTel()%></td>
    </tr>
    <tr>
    <tdalign="right">电子邮箱:</td>
    <td><%=user.getEmail()%></td>
    </tr>
 </table>
 <% 
 }else{
 out.println("<br>对不起,您还没有登录!");
 }
 %>
  </div>
 </div>
  </div>
  </div>
 </body>
</html>

 

5、Servlet配置

web.xml

<?xmlversion="1.0" encoding="UTF-8"?>
<web-appversion="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">
 <!-- 用户注册 -->
 <servlet>
 <servlet-name>RegServlet</servlet-name>
 <servlet-class>com.wuyudong.service.RegServlet</servlet-class>
 </servlet>
 <!-- 用户登录 -->
 <servlet>
 <servlet-name>LoginServlet</servlet-name>
 <servlet-class>com.wuyudong.service.LoginServlet</servlet-class>
 </servlet>
 <!-- 用户退出 -->
 <servlet>
 <servlet-name>UserExitServlet</servlet-name>
 <servlet-class>com.wuyudong.service.UserExitServlet</servlet-class>
 </servlet>
 <!-- Servlet映射 -->
 <servlet-mapping>
 <servlet-name>RegServlet</servlet-name>
 <url-pattern>/RegServlet</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
 <servlet-name>LoginServlet</servlet-name>
 <url-pattern>/LoginServlet</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
 <servlet-name>UserExitServlet</servlet-name>
 <url-pattern>/UserExitServlet</url-pattern>
 </servlet-mapping>
 <!-- 过滤器 -->
 <filter>
 <filter-name>CharacterEncodingFilter</filter-name>
 <filter-class>com.wuyudong.util.CharacterEncodingFilter</filter-class>
 <init-param>
 <param-name>encoding</param-name>
 <param-value>GBK</param-value>
 </init-param>
 </filter>
 <filter-mapping>
 <filter-name>CharacterEncodingFilter</filter-name>
 <url-pattern>/*</url-pattern>
 <dispatcher>REQUEST</dispatcher>
 <dispatcher>FORWARD</dispatcher>
 </filter-mapping>
 <!-- 主页 -->
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

 

6、字符编码过滤器

CharacterEncodingFilter.java

package com.wuyudong.util;
 
import java.io.IOException;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
 
/**
* 字符编码过滤器
*/
public class CharacterEncodingFilter implements Filter{
 
    protected String encoding = null;
    protected FilterConfigfilterConfig = null;
 
    public void init(FilterConfigfilterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
    }
 
    public void doFilter(ServletRequestrequest, ServletResponseresponse, FilterChainchain) throws IOException, ServletException {
        if (encoding != null) {
            request.setCharacterEncoding(encoding);
            response.setContentType("text/html; charset="+encoding);
        }
        chain.doFilter(request, response);
    }
 
    public void destroy() {
        this.encoding = null;
        this.filterConfig = null;
    }
}

 

最后运行的界面截图如下:

技术分享

作者:工学1号馆

出处: http://wuyudong.com/1569.html

Java Web Model2实战