自定义MVC框架(一)-(没有基于xml的)
0.创建oracle的sql语句如下
--创建表
create table userinfo(id number primary key,uname varchar2(20),password varchar2(20),age number);
--创建序列
create sequence seq_userinfo;
--添加数据
insert into userinfo values(seq_userinfo.nextval,'holly','123',18);
insert into userinfo values(seq_userinfo.nextval,'石头','123',18);
insert into userinfo values(seq_userinfo.nextval,'朱亚楠','123',18);
--提交事务
commit;
1.创建如下项目结构
2.在com.entity包下创建实体类UserInfo.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.entity; 2 /** 3 * 用户信息表 4 * @author Holly老师 5 * 6 */ 7 public class UserInfo { 8 private Integer id; 9 private String uname; 10 private String password; 11 private Integer age; 12 13 14 15 public UserInfo(Integer id, String uname, String password, Integer age) { 16 this.id = id; 17 this.uname = uname; 18 this.password = password; 19 this.age = age; 20 } 21 22 public UserInfo() { 23 } 24 25 public Integer getId() { 26 return id; 27 } 28 29 public void setId(Integer id) { 30 this.id = id; 31 } 32 33 public String getUname() { 34 return uname; 35 } 36 37 public void setUname(String uname) { 38 this.uname = uname; 39 } 40 41 public String getPassword() { 42 return password; 43 } 44 45 public void setPassword(String password) { 46 this.password = password; 47 } 48 49 public Integer getAge() { 50 return age; 51 } 52 53 public void setAge(Integer age) { 54 this.age = age; 55 } 56 57 58 }
3.在com.dao包下创建操作数据库的BaseDao.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.dao; 2 3 import java.sql.Connection; 4 import java.sql.Driver; 5 import java.sql.DriverManager; 6 import java.sql.PreparedStatement; 7 import java.sql.ResultSet; 8 import java.sql.SQLException; 9 /** 10 * 链接数据库工具类 11 * @author Holly老师 12 * 13 */ 14 public class BaseDao{ 15 //1. 定义连接所需要的字符串 16 private static final String DRIVER="oracle.jdbc.driver.OracleDriver"; 17 private static final String URL="jdbc:oracle:thin:@127.0.0.1:1521:orcl"; 18 private static final String USER="holly"; 19 private static final String PASSWORD="sys"; 20 21 public static Connection conn=null; 22 public static PreparedStatement pstm=null; 23 public static ResultSet rs=null; 24 25 26 static { 27 try { 28 Class.forName(DRIVER); 29 } catch (ClassNotFoundException e) { 30 e.printStackTrace(); 31 } 32 } 33 34 public Connection getConnection(){ 35 try { 36 conn=DriverManager.getConnection(URL, USER, PASSWORD); 37 } catch (SQLException e) { 38 e.printStackTrace(); 39 } 40 return conn; 41 } 42 43 public ResultSet executeQuery(String sql,Object[] param){ 44 conn=this.getConnection(); 45 try { 46 pstm=conn.prepareStatement(sql); 47 if(param!=null){ 48 for (int i = 0; i < param.length; i++) { 49 pstm.setObject(i+1, param[i]); 50 } 51 } 52 rs=pstm.executeQuery(); 53 } catch (SQLException e) { 54 e.printStackTrace(); 55 } 56 return rs; 57 } 58 59 public void closeAll(ResultSet rs,PreparedStatement pstm,Connection conn){ 60 try { 61 if(rs!=null){ 62 rs.close(); 63 } 64 } catch (SQLException e) { 65 e.printStackTrace(); 66 } 67 try { 68 if(pstm!=null){ 69 pstm.close(); 70 } 71 } catch (SQLException e) { 72 e.printStackTrace(); 73 } 74 try { 75 if(conn!=null){ 76 conn.close(); 77 } 78 } catch (SQLException e) { 79 e.printStackTrace(); 80 } 81 } 82 83 }
4.在com.dao包下创建UserInfoDao.java接口
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.dao; 2 3 import com.entity.UserInfo; 4 /** 5 * 增删改接口 6 * @author Holly老师 7 * 8 */ 9 public interface UserInfoDao { 10 public UserInfo getUserByNamePwd(String name,String pwd); 11 }
5.在com.dao.impl包下创建接口的实现类UserInfoDaoImpl.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.dao.impl; 2 3 import java.sql.SQLException; 4 5 import com.dao.BaseDao; 6 import com.dao.UserInfoDao; 7 import com.entity.UserInfo; 8 /** 9 * 增删改接口实现类 10 * @author Holly老师 11 * 12 */ 13 public class UserInfoDaoImpl extends BaseDao implements UserInfoDao { 14 15 public UserInfo getUserByNamePwd(String name, String pwd) { 16 UserInfo user=null; 17 String sql="select * from userinfo where uname=? and password=?"; 18 Object[] param={name,pwd}; 19 rs=this.executeQuery(sql, param); 20 try { 21 if(rs.next()){ 22 user=new UserInfo(rs.getInt("id"), rs.getString("uname"), rs.getString("password"), rs.getInt("age")); 23 } 24 } catch (SQLException e) { 25 e.printStackTrace(); 26 }finally{ 27 this.closeAll(rs, pstm, conn); 28 } 29 return user; 30 } 31 32 }
6.在com.service包下创建业务接口UserInfoService.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.service; 2 3 import com.entity.UserInfo; 4 /** 5 * 服务接口 6 * @author Dell 7 * 8 */ 9 public interface UserInfoService{ 10 public UserInfo login(String name,String pwd); 11 }
7.在com.service.impl包下创建业务接口实现类UserInfoServiceImpl.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.service.impl; 2 3 import com.dao.UserInfoDao; 4 import com.dao.impl.UserInfoDaoImpl; 5 import com.entity.UserInfo; 6 import com.service.UserInfoService; 7 /** 8 * 服务实现类 9 * @author Holly老师 10 * 11 */ 12 public class UserInfoServiceImpl implements UserInfoService{ 13 14 public UserInfo login(String name, String pwd) { 15 UserInfoDao dao=new UserInfoDaoImpl(); 16 return dao.getUserByNamePwd(name, pwd); 17 } 18 19 }
8.在com.action包下创建Action.java接口
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 1.定义主控制器,用于分发请求 * @author Holly老师 * */ public interface Action { /** * 用于分发拦截的请求 * @param request 请 求 * @param response 响应 * @return 执行完操作要跳转的页面,“success”跳转到成功页面,“fail”跳转到失败页面 */ public String execute(HttpServletRequest request,HttpServletResponse response); }
9.在com.action包下创建LoginAction.java实现类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.action; 2 3 import javax.servlet.http.HttpServletRequest; 4 import javax.servlet.http.HttpServletResponse; 5 6 import com.entity.UserInfo; 7 import com.service.UserInfoService; 8 import com.service.impl.UserInfoServiceImpl; 9 /** 10 * 2.每个action表示用户请求的一个操作 11 * 该Action控制登录 12 * @author holly老师 13 * 14 */ 15 public class LoginAction implements Action { 16 /** 17 * 控制页面跳转的方法 18 * request获取页面输入,然后调用业务方法得到结果 , 19 * 如果登录失败则将结果保存到request对象中, 20 * 如果登录成功,将用户信息保存到session中 21 */ 22 public String execute(HttpServletRequest request, 23 HttpServletResponse response) { 24 //1.获得页面请求参数 25 String username=request.getParameter("username"); 26 System.out.println("username"+username); 27 String password=request.getParameter("password"); 28 System.out.println("password"+password); 29 30 //2.业务处理 31 UserInfoService userservice=new UserInfoServiceImpl(); 32 UserInfo userinfo=userservice.login(username, password); 33 34 if(userinfo==null){ 35 System.out.println("没查到"); 36 request.setAttribute("message", "用户名或密码错误"); 37 return "/page/login.jsp"; 38 }else{ 39 System.out.println("查到了"); 40 request.getSession().setAttribute("login",userinfo ); 41 return "/page/show.jsp"; 42 43 } 44 } 45 46 }
10.在com.filter包下创建ActionFilter.java核心过滤器类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.filter; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 import com.action.Action; 15 import com.action.LoginAction; 16 /** 17 * 核心控制器=过滤器 18 * 在处理每次请求时首先根据请求路径找到将要被执行后的Action,然后调用Action的execute方法, 19 * 根据execute方法返回的转发路径转发到对应的JSP页面 20 * @author Holly老师 21 * 22 */ 23 public class ActionFilter implements Filter { 24 //定义接受过滤器节点里param的参数 25 private String encode = null; 26 27 //定义过滤器参数变量 28 private FilterConfig config; 29 /** 30 * 销毁 31 */ 32 public void destroy() { 33 encode = null; 34 } 35 /** 36 * 初始化 37 */ 38 public void init(FilterConfig config) throws ServletException { 39 //接受web.xml文件中配置的参数 40 String encode = config.getInitParameter("encode"); 41 if (this.encode == null) { 42 this.encode = encode; 43 } 44 45 } 46 /** 47 * 请求处理 48 */ 49 public void doFilter(ServletRequest request, ServletResponse response, 50 FilterChain chain) throws IOException, ServletException { 51 52 //乱码处理 53 if (null == request.getCharacterEncoding()) { 54 request.setCharacterEncoding(encode); 55 } 56 57 58 //1.将请求转换成HtpServlet请求 59 HttpServletRequest hsr=(HttpServletRequest) request; 60 HttpServletResponse hsp= (HttpServletResponse) response; 61 62 //2.获得Action 63 //Action action=new LoginAction(); 64 Action action=this.getAction(hsr); 65 66 //3.调用Action的execute方法 67 //定义接受Action中execute方法返回值的变量 68 String resultView=null; 69 try { 70 //得到某个action请求的页面地址 71 resultView=action.execute(hsr,hsp); 72 } catch (Exception e) { 73 e.printStackTrace(); 74 } 75 76 //4.页面跳转 77 if(null!=resultView){ 78 //请求下发 79 request.getRequestDispatcher(resultView).forward(request, response); 80 } 81 82 } 83 /** 84 * 获取请求中的Action 85 * @param hsr 86 * @return 87 * 88 */ 89 private Action getAction(HttpServletRequest request) { 90 //1.获取请求中的uri:项目名/Xxx.action 91 //Stuts2_Part1__C1_MyMVC/login.action 92 String uri=request.getRequestURI(); 93 System.out.println("uri:"+uri); 94 95 //2.获取上下文路径:项目名 96 //Stuts2_Part1__C1_MyMVC/ 97 String contextPath=request.getContextPath(); 98 System.out.println("contextPath:"+contextPath); 99 100 //3.获取Xxx.action,从某个位置截取到最后 101 String actionPath=uri.substring(contextPath.length()); 102 System.out.println("actionPath:"+actionPath); 103 104 //4.获取Action的名字:Xxx 105 String actionName=actionPath.substring(1,actionPath.lastIndexOf('.')).trim(); 106 System.out.println("actionName:"+actionName); 107 108 //5.获取某个Action类对象 109 Action action=null; 110 if("login".equals(actionName)){ 111 action=new LoginAction(); 112 } 113 //返回拦截的某个action对象 114 return action; 115 } 116 117 118 }
11.编辑WebRoot先的WEB-INF下的web.xml文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 7 <welcome-file-list> 8 <welcome-file>page/login.jsp</welcome-file> 9 </welcome-file-list> 10 11 <!-- 以.action结束的请求都会派发到ActionFilter中进行过滤 --> 12 <filter> 13 <filter-name>requestFilter</filter-name> 14 <filter-class>com.filter.ActionFilter</filter-class> 15 <init-param> 16 <param-name>encode</param-name> 17 <param-value>UTF-8</param-value> 18 </init-param> 19 </filter> 20 <filter-mapping> 21 <filter-name>requestFilter</filter-name> 22 <url-pattern>*.action</url-pattern> 23 </filter-mapping> 24 25 </web-app>
12.在WebRoot下创建page文件夹,并创建login.jsp页面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'index.jsp' starting page</title> 13 <meta http-equiv="pragma" content="no-cache"> 14 <meta http-equiv="cache-control" content="no-cache"> 15 <meta http-equiv="expires" content="0"> 16 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 17 <meta http-equiv="description" content="This is my page"> 18 <!-- 19 <link rel="stylesheet" type="text/css" href="styles.css"> 20 --> 21 </head> 22 23 <body> 24 <fieldset style="width:400px; height=400px;"> 25 <legend>登录</legend> 26 <form action="login.action"> 27 <table> 28 <tr><td>用户名:</td><td><input type="text" id="username" name="username"/></td></tr> 29 <tr><td>密 码:</td><td><input type="password" id="password" name="password"/></td></tr> 30 <tr><td><input type="submit" value="登录"/></td><td><input type="reset" value="重置"/></td></tr> 31 </table> 32 </form> 33 </fieldset> 34 </body> 35 </html>
13.在WebRoot下创建page文件夹,并创建show.jsp页面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'index.jsp' starting page</title> 13 <meta http-equiv="pragma" content="no-cache"> 14 <meta http-equiv="cache-control" content="no-cache"> 15 <meta http-equiv="expires" content="0"> 16 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 17 <meta http-equiv="description" content="This is my page"> 18 <!-- 19 <link rel="stylesheet" type="text/css" href="styles.css"> 20 --> 21 </head> 22 23 <body> 24 登录成功!欢迎来到首页 25 </body> 26 </html>
14.可以运行了!
中文用户名登录