码迷,mamicode.com
首页 > 编程语言 > 详细

MVC模式在Java Web应用程序中的实例分析

时间:2017-05-06 15:53:38      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:代理类   normal   rda   arraylist   ons   statement   int   ati   sys   

一个简单的MVC实例

利用jsp+javabean+Servlet模拟一个用户登陆,实现对数据库的增删改查。

1,创建数据库

我使用的数据库是MySQL,创建一个Iuser表,具体如下

 

2,创建一个javabean类,对表中的3个属性进行封装

User.Java

 

package cn.jw.vo;

 

public class User {

private String username;

private String userspass;

private String userid;

public User(){

 

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getUserspass() {

return userspass;

}

public void setUserspass(String userspass) {

this.userspass = userspass;

}

public String getUserid() {

return userid;

}

public void setUserid(String userid) {

this.userid = userid;

}

}

3,创建一个名为DataBaseConnection.java的类,实现数据库的驱动

DataBaseConnection.java

package cn.jw.dbc;

 

import java.sql.*;

 

public class DataBaseConnection {

public static final String DBDRIVER="com.mysql.jdbc.Driver";

    public static final String DBURL="jdbc:mysql://localhost:3306/test";

    public static final String DBUSER="root";

    public static final String DBPASS="zhy1121";

private Connection conn=null;

public DataBaseConnection(){

try {

Class.forName(DBDRIVER);

this.conn=DriverManager.getConnection(DBURL,DBUSER,DBPASS);

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

    public Connection getConnection() {

// TODO Auto-generated method stub

return this.conn;

}

    public void close() {

// TODO Auto-generated method stub

        try {

this.conn.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

4,创建一个dao接口,并创建一个实现类和一个代理类,继承这个接口

接口用来定义一些方法,在下面会用到

UserDao.java

package cn.jw.dao;

 

import java.util.List;

 

import cn.jw.vo.User;

 

 

public interface UserDAO {

 

}

UserDaoImpl.java

public class UserDaoImpl implements UserDAO {

 

private Connection conn=null;

private PreparedStatement pstmt=null;

private int count=0;

 

public UserDaoImpl(Connection conn1){

    this.conn=conn1;

 }

}

UserDaoPoxy.java

package cn.jw.dao.poxy;

 

import java.util.ArrayList;

import java.util.List;

 

import cn.jw.dao.UserDAO;

import cn.jw.dao.impl.UserDaoImpl;

import cn.jw.dbc.DataBaseConnection;

import cn.jw.vo.User;

 

public class UserDaoPoxy implements UserDAO {

private DataBaseConnection dbc = null;

private UserDAO dao = null;

public UserDaoPoxy(){

this.dbc = new DataBaseConnection();

this.dao = new UserDaoImpl(this.dbc.getConnection());

}

}

具体的实现方法根据功能再添加。

5,创建一个工厂类

DaoFactory.java

package cn.jw.factory;

 

import cn.jw.dao.UserDAO;

import cn.jw.dao.poxy.UserDaoPoxy;

 

public class DaoFactory {

public static UserDAO getUserDaoInstance() throws Exception{

return new UserDaoPoxy();

}

 

}

6,实现第一个功能,用户登陆

(1)新建一个名为Login.jsp的jsp文件,来实现用户登录界面

 <form action="LoginServlet" method="post"

    用户ID:<input type="text" name="userid"><br>

    密码:<input type="text" name="userpass"><br>

    <input type="submit" value="登录">

  </form>

将表单数据提交到LoginServlet中进行处理

(2)新建一个名为LoginServlet的Servlet,重写重写doGet(),doPost()方法

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

 

this.doPost(request, response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

 

String path="findAll.jsp";

String userid1=request.getParameter("userid");

String password1=request.getParameter("userpass");

 

List<String> info=new ArrayList<String>();

if(userid1==null||"".equals(userid1)){

info.add("用户ID不能为空!");

}

if(password1==null||"".equals(password1)){

info.add("密码不能为空!");

}

 

        if(info.size()==0){

         User user=new User();

         user.setUserid(userid1);

         user.setUserspass(password1);

         try {

if(DaoFactory.getUserDaoInstance().findUser(user)){

  info.add("Login Success! welcome "+user.getUsername());

    

}else{

      info.add("Error username or password!");

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

        request.setAttribute("info1", info);

        request.getRequestDispatcher(path).forward(request,response);     

}

跳转到的findAll.jsp稍后再写

(3)在接口中添加相应的方法,再在实现类和代理中重写,实现用户登录

public interface UserDAO {

public boolean findUser(User user) throws Exception;

}

 

public class UserDaoImpl implements UserDAO {

......

public boolean findUser(User user) throws Exception {

// TODO Auto-generated method stub

boolean flag = false;

try{

String sql="select * from Iuser where userid=? and userpass=?";

pstmt = this.conn.prepareStatement(sql);

pstmt.setString(1,user.getUserid());

pstmt.setString(2,user.getUserspass());

ResultSet rs = pstmt.executeQuery();

if(rs.next()){

user.setUsername(rs.getString(2));

flag = true;

}

}catch(Exception e){

e.printStackTrace();

}finally{

try{

this.conn.close();

}catch(Exception e){

e.printStackTrace();

}

}

return flag;

}

......

}

 

public class UserDaoPoxy implements UserDAO {

......

public boolean findUser(User user) throws Exception {

// TODO Auto-generated method stub

boolean flag = false;

try{

flag=this.dao.findUser(user);

}catch(Exception e){

e.printStackTrace();

}finally{

this.dbc.close();

}

return flag;

}

......

}

7,用类似的方法实现注册(增),删除,修改的操作

 

代码略

 

8,实现查找与分页显示

(1)新建一个jsp页面用来显示,就是前面提到的findAll.jsp

  <body>

 <% 

        int pageSize=3;

        int currentPage=1;

        int total=DaoFactory.getUserDaoInstance().getCount();

        int lastpage;

        

        if(total%pageSize==0){

lastpage=total/pageSize;

}else{

lastpage=total/pageSize+1;

}

        if(currentPage<1){

           currentPage=1;

        }

        if(currentPage>lastpage)

        {

           currentPage=lastpage;

        }

        

 %>

  

    <%

      request.setCharacterEncoding("gb2312");

      List<String> info2=(List<String>)session.getAttribute("info1");

      if(info2!=null){

       Iterator<String> iter=info2.iterator();

       while(iter.hasNext()){

    %>

           <h1><%=iter.next()%></h1>

    <%     

       }

     }

  

     String keywords=(String)request.getAttribute("kw");

      if(keywords==null){

         keywords="";

      }

     // List<User> all=DaoFactory.getUserDaoInstance().findAll(keywords,currentPage,pageSize);

      List<User> userall=new ArrayList<User>();

      userall=(List<User>)request.getAttribute("userall1");

      Iterator<User> iter=userall.iterator();  

     //Iterator<User> iter=all.iterator();  

    %>

    

    <form action="FindAllServlet" method="post">

       请输入查询关键字:<input type="text" name="kw" value="<%=keywords%>">

       <input type="submit" value="查询"/>

    </form> <br>

    <br>

    <table border="1" >

      <tr>

        <td>Userid</td>

        <td>Username</td>

        <td>Userpass</td>

        <td>操作</td>

      </tr>

       <%

      while(iter.hasNext()){

      User user=iter.next();

   

  %> 

      <tr>

        <td><%=user.getUserid()%></td>

        <td><%=user.getUsername()%></td>

        <td><%=user.getUserspass()%></td>

        <td><a href="Delete.jsp">删除</a>     <a href="Update.jsp">修改</a></td>

      </tr>

     <%

       }    

     

     %>   

     <tr>

</td>

</tr>    

<tr>

 <td>

     共<%=lastpage%>页  

                  第<%=currentPage%>页    

    <a href="FindAllServlet?currentPage=1">首页</a>  

    <a href="FindAllServlet?currentPage=<%=currentPage-1%>">上一页</a>  

    <a href="FindAllServlet?currentPage=<%=currentPage+1%>">下一页</a>  

    <a href="FindAllServlet?currentPage=<%=lastpage%>">尾页</a>

</td>

</tr>    

     </table>

  </body>

(2),创建一个名为FindAllServlet的Servlet,重写doGet(),doPost()方法

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

 

this.doPost(request, response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

 

 

int pageSize=3;

int currentPage;

String page = request.getParameter("currentPage");

if(page!=null){

currentPage=Integer.parseInt(request.getParameter("currentPage"));

}else{

currentPage=1;

}

request.setCharacterEncoding("gb2312");

String keywords=request.getParameter("kw");

 

if(keywords==null){

         keywords="";

      }

String path="findAll.jsp";

List<User> userall = null;

try {

userall = DaoFactory.getUserDaoInstance().findAll(keywords,currentPage,pageSize);

request.setAttribute("userall1", userall);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

    request.setAttribute("kw", keywords);

request.getRequestDispatcher(path).forward(request,response);

}

(3),添加具体的方法来实现按条件查询,并且将结果分页显示

 

首先实现按条件查询

public interface UserDAO {

......

public List<User> findAll(String keyWord)throws Exception;

......

}

 

public class UserDaoImpl implements UserDAO {

......

List<User> all = new ArrayList<User>();

User user = null;

String sql="select * from Iuser where userid like ? or username like ?";

this.pstmt=this.conn.prepareStatement(sql);

pstmt.setString(1,"%"+keyWord+"%");

pstmt.setString(2,"%"+keyWord+"%");

ResultSet rs=this.pstmt.executeQuery();

while(rs.next()){

user=new User();

user.setUserid(rs.getString(1));

user.setUsername(rs.getString(2));

user.setUserspass(rs.getString(3));

all.add(user);

}

this.pstmt.close();

return all;

......

}

 

public class UserDaoPoxy implements UserDAO {

......

List<User> all=null;

try {

all=this.dao.findAll(keyWord);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

this.dbc.close();

}

return all;

......

}

 

然后利用上述方法返回的集合实现分页查询

实现的方法如下

public interface UserDAO {

......

public List<User> findAll(String keyWord,int currentPage,int pageSize)throws Exception;

......

}

 

public class UserDaoImpl implements UserDAO {

......

ist<User> all=new ArrayList<User>();

all=this.findAll(keyWord);

int total=all.size();

int lastpage;

if(total%pageSize==0){

lastpage=total/pageSize;

}else{

lastpage=total/pageSize+1;

}

if(currentPage<1){

currentPage=1;

}

if(currentPage>lastpage){

currentPage=lastpage;

}

int fromIndex=(currentPage-1)*pageSize;

     int toIndex=fromIndex+pageSize;

     if(toIndex>total){

     toIndex=total;

     }

all=all.subList(fromIndex, toIndex);

System.out.println(all.size());

return all;

......

}

 

public class UserDaoPoxy implements UserDAO {

......

ublic List<User> findAll(String keyWord, int currentPage, int pageSize)

throws Exception {

// TODO Auto-generated method stub

List<User> all=new ArrayList<User>();

all=this.dao.findAll(keyWord,currentPage,pageSize);

this.dbc.close();

return all;

}

......

}

这样能很好的实现控制器接收用户的请求,并决定应该调用哪个模型来进行处理,然后模型用业务逻辑来处理用户的请求并返回数据,最后控制器用相应的视图格式化模型返回的数据,并通过表示层呈现给用户。

MVC模式在Java Web应用程序中的实例分析

标签:代理类   normal   rda   arraylist   ons   statement   int   ati   sys   

原文地址:http://www.cnblogs.com/420Rock/p/6816863.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!