首页 > 代码库 > 简单案列完美搞定Mvc设计模式
简单案列完美搞定Mvc设计模式
一个小列子搞定Mvc模式,包括数据库以及如何提高用户体验度
1.首先来web.xml配置servlet的访问路径:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>HeadFirstJspServletChap05</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!--配置servlet的名字--->
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>com.java.filter.LoginFilter</filter-class>
</filter>
<!--配置servlet的访问路径--->
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
mvc及三层架构编程,模型城(M)、控制层(C)、显示层(V)
2.后台分包放代码,是代码看起来更有结构性
2-1.model.存放java实体类:
package com.java.model;
public class User {//创建user实体类
private int id;//id
private String userName;//用户名
private String password;//密码
public User() {
super();
}
public User(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}
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;
}
}
2-2dao层存放操作数据库的类
package com.java.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.java.model.User;
public class UserDao {
public User login(Connection con,User user)throws Exception{
User resultUser=null;
String sql="select * from t_user where userName=? and password=?";//sql语句
PreparedStatement pstmt=con.prepareStatement(sql);//预编译处理
pstmt.setString(1, user.getUserName());//为预编译设置参数
pstmt.setString(2, user.getPassword());
ResultSet rs=pstmt.executeQuery();//执行sql语句并将结果返回到resultSet结果集中
if(rs.next()){//如果结果集不为空
resultUser=new User();//封装user
resultUser.setUserName(rs.getString("userName"));
resultUser.setPassword(rs.getString("password"));
}
return resultUser;
}
}
2-3.控制层存放servlet
package com.java.web;
import java.io.IOException;
import java.sql.Connection;
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 com.java.dao.UserDao;
import com.java.model.User;
import com.java.util.DbUtil;
public class LoginServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
DbUtil dbUtil=new DbUtil();
UserDao userDao=new UserDao();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName=request.getParameter("userName");//获取登陆页面传来的值
String password=request.getParameter("password");
Connection con=null;
try {
User user=new User(userName,password);
con=dbUtil.getCon();
User currentUser=userDao.login(con, user);
if(currentUser==null){//登陆的逻辑处理
request.setAttribute("error", "用户名或密码错误");
request.setAttribute("userName", userName);
request.setAttribute("password", password);
request.getRequestDispatcher("login.jsp").forward(request, response);//跳转到登陆页面,为了更友好,我们把用户名和面传回登录页面,然后通过el表达式取出来
}else{
HttpSession session=request.getSession();
session.setAttribute("currentUser", currentUser);
response.sendRedirect("main.jsp");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2-4.util存放我们的工具类:
package com.java.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbUtil {
private String dbUrl="jdbc:mysql://localhost:3306/db_jsp";//数据库连接地址
private String dbUserName="root";//用户名
private String dbPassword="56";//密码
private String jdbcName="com.mysql.jdbc.Driver";//驱动
public Connection getCon()throws Exception{
Class.forName(jdbcName);
Connection con=DriverManager.getConnection(dbUrl, dbUserName, dbPassword);//得到连接
return con;
}
public void closeCon(Connection con)throws Exception{//关闭连接
if(con!=null){
con.close();
}
}
public static void main(String[] args) {//测试连接
DbUtil dbUtil=new DbUtil();
try {
dbUtil.getCon();
System.out.println("连接成功");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
到目前为止我们的后台模块就搭建完成,接下来我们搭建数据库和页面
3.我们创建数据库:
/*
SQLyog 企业版 - MySQL GUI v8.14
MySQL - 5.1.49-community : Database - db_jsp
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=‘‘*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=‘NO_AUTO_VALUE_ON_ZERO‘ */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`db_jsp` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `db_jsp`;
/*Table structure for table `t_user` */
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*Data for the table `t_user` */
insert into `t_user`(`id`,`userName`,`password`) values (1,‘java‘,‘56‘);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
4.我们搭建前台的页面:
4-1.登陆页面:login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
<table>
<tr>
<th colspan="2">用户登录</th>
</tr>
<tr>
<td>用户名:</td>
<td><input type="text" id="userName" name="userName" value="http://www.mamicode.com/${userName }"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" id="password" name="password" value="http://www.mamicode.com/${password }"/></td>
</tr>
<tr>
<td><input type="submit" value="http://www.mamicode.com/登录"/></td>
<!---此处为el表达式我们后面在学习哈,看看效果---->
<td><font color="red">${error }</font></td>
</tr>
</table>
</form>
</body>
</html>
4-2.我们登陆成功后跳转的页面:main.jsp
简单案列完美搞定Mvc设计模式