文章目录
Servlet
作用:把处理业务逻辑,数据库交互的java代码从jsp文件中拿出去
使用
在java Resource/src下创建包,再创建HttpServlet子类:
public class LoginServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String cu_name = req.getParameter("username");
String cu_pass = req.getParameter("userpassword");
if("jack".equals(cu_name)&&"333".equals(cu_pass)) {
Cookie cookie = new Cookie("cu_name",cu_name);
cookie.setMaxAge(60*5);
resp.addCookie(cookie);
HttpSession session = req.getSession();
session.setAttribute("cu_name", cu_name);
resp.sendRedirect("/web03/welcome.jsp");
}else {
resp.sendRedirect("/web03");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
注意:
1.创建的是HttpServlet的子类
2.在doPost方法中调用doGet方法
3.req代替之前的request,resp代替response
在web.xml文件中添加
<servlet>
<servlet-name>loginServlet</servlet-name> <!--3.起个名字-->
<servlet-class>com.java.servlet.LoginServlet</servlet-class> <!--4.要声明的Servlet的绝对路径-->
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name> <!--2.找到指定你的Servlet-->
<url-pattern>/loginServlet</url-pattern> <!--1.你的请求地址-->
</servlet-mapping>
注意:
在表单提交时,服务器查找顺序:1->2->3->4
在登录页面(注意跳转)
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<%
String name = "";
Cookie[] cookies = request.getCookies();
if(cookies!=null&&cookies.length>0){
for(Cookie c:cookies){
if("cu_name".equals(c.getName())){
name=c.getValue();
}
}
}
%>
</head>
<body>
<form action="/web03/loginServlet" method="post">
姓名:<input type="text" name="username" value=<%=name %>>>
密码:<input type="password" name="userpassword">
<input type="button" value="登录">
</form>
</body>
欢迎页面
<body>
<h1>
欢迎您!<%=(String)session.getAttribute("cu_name") %>
</h1>
<a href="/web03/loginOut">点我取消免登陆</a>
</body>
MVC设计模式(Model View Controller)
Model 模型层:将我们的数据库中的数据表,映射成java类
(工具层)
(DAO)数据访问对象 ,应该都是接口
View 视图层(jsp)
Controller 控制层,解决业务逻辑的处理
Model层
以commoditytype表和commodity表为例,创建对象。此处为了简洁,省略了set和get方法,实际应用中需要加上
public class Commoditytype {
private String ct_id;
private String ct_name;
public Commoditytype() {
}
public Commoditytype(String ct_id, String ct_name) {
this.ct_id = ct_id;
this.ct_name = ct_name;
}
@Override
public String toString() {
return "Commoditytype [ct_id=" + ct_id + ", ct_name=" + ct_name + "]";
}
}
public class Commodity {
private String c_id;
private String c_name;
private String c_madein;
private String c_type;
private Commoditytype ct;
private Integer c_inprice;
private Integer c_outprice;
private Integer c_num;
public Commodity() {
}
public Commodity(String c_id, String c_name, String c_madein, String c_type, Commoditytype ct, Integer c_inprice,
Integer c_outprice, Integer c_num) {
super();
this.c_id = c_id;
this.c_name = c_name;
this.c_madein = c_madein;
this.c_type = c_type;
this.ct = ct;
this.c_inprice = c_inprice;
this.c_outprice = c_outprice;
this.c_num = c_num;
}
@Override
public String toString() {
return "Commodity [c_id=" + c_id + ", c_name=" + c_name + ", c_madein=" + c_madein + ", c_type=" + c_type
+ ", ct=" + ct + ", c_inprice=" + c_inprice + ", c_outprice=" + c_outprice + ", c_num=" + c_num + "]";
}
}
工具层
创建一个包,将连接数据库完成增删改查的功能封装
public class DBHelper {
private static String url = "jdbc:mysql://localhost:3306/ishopn?characterEncoding=utf8";
private static String user = "root";
private static String password = "1234";
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user,password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static ResultSet executeQuery(Connection conn,String sql,List para) {
ResultSet rs = null;
try {
PreparedStatement ps = conn.prepareStatement(sql);
if(para!=null&¶.size()>0) {
for(int i=0;i<para.size();i++) {
ps.setObject(i+1, para.get(i));
}
}
rs = ps.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
public static int executeUpdate(Connection conn,String sql,List para) {
int line=0;
try {
PreparedStatement ps = conn.prepareStatement(sql);
if(para!=null&¶.size()>0) {
for(int i=0;i<para.size();i++) {
ps.setObject(i+1, para.get(i));
}
}
line = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return line;
}
public static void closeConnection(Connection c) {
if(c!=null) {
try {
c.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
DAO层(数据库访问层)
以customer为例,封装对此对象进行操作的抽象方法
public interface CustomerDao {
int getCountCustomerByNameAndPhone(Customer c);
int insCustomer(Customer c);
}
定义相应的子类实现
public class CustomerDaoImpl implements CustomerDao {
@Override
public int getCountCustomerByNameAndPhone(Customer cu) {
int count=0;
try {
//获取数据库连接
Connection conn = DBHelper.getConnection();
String sql = "select count(*) from customer where cu_name=? and cu_phone=?;";
List para = new List();
para.add(cu.getCu_name());
para.add(cu.getCu_phone());
ResultSet rs = DBHelper.executeQuery(conn,sql,para);
rs.next();
count = rs.getInt(1);
DBHelper.closeConnection(conn);
}catch(Exception e) {
e.printStackTrace();
}
return 0;
}
@Override
public int insCustomer(Customer cu) {
// TODO Auto-generated method stub
return 0;
}
}
controller
import com.ishopn.dao.CustomerDao;
import com.ishopn.dao.impl.CustomerDaoImpl;
import com.java.ishopmodel.Customer;
public class CustomerController {
private CustomerDao customerDao;
public CustomerController() {
customerDao = new CustomerDaoImpl();
}
public int getCountCustomerByNameAndPhone(String cu_name,String cu_phone) {
Customer cu = new Customer();
cu.setCu_name(cu_name);
cu.setCu_phone(cu_phone);
return customerDao.getCountCustomerByNameAndPhone(cu);
}
}
在LoginServlet中调用
public class LoginServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String cu_name = req.getParameter("cu_name");
String cu_phone = req.getParameter("cu_phone");
CustomerController cc = new CustomerController();
int count = cc.getCountCustomerByNameAndPhone(cu_name, cu_phone);
if(count>0) {
Cookie cookie = new Cookie("cu_name",cu_name);
cookie.setMaxAge(60*10);
resp.addCookie(cookie);
HttpSession session = req.getSession();
session.setAttribute("cu_name", cu_name);
}else {
resp.sendRedirect("/web04");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}