MVC
M | model,模型 | 功能 | JavaBean实现 |
---|---|---|---|
V | view,视图 | 用于展示,以及用户交互 | html,jsp,js,css,jquery等 |
C | control,控制器 | 接受各种请求,将请求跳转到模型,进行响应的处理,模型处理完毕之后,将结果返回给页面 | 可以jsp实现,但是一般使用servlet实现控制器 |
servlet
什么是servlet:
1.必须继承 Javax.servlet.http.HttpServlet
2.必须重写其中的doGet()或者doPost()方法
doGet(); 接受并处理所有get方式的请求
doPost(); 接受并处理所有post方式的请求
代码演示(servlet2.5):
WelcomeServlet.java
package cn.edu;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class WelcomeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println( "doget();" );
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//一般get和post方法只用写一个
//System.out.println( "dopost();" );
this.doGet( req,resp );
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
//利用servlet-name绑定相关的服务
<servlet>
<servlet-name>a</servlet-name>
<servlet-class>cn.edu.WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>a</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
//注意这个地方的斜杠
</servlet-mapping>
</web-app>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="WelcomeServlet">welcomeservlet</a>
<form action="WelcomeServlet" method="post">
<input type="submit">
</form>
</body>
</html>
代码演示(servlet2.5):
3.0不需要修改web.xml
package cn.edu;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/WelcomeServlet") //3.0的映射
public class WelcomeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println( "servlet3.0" );
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//System.out.println( "dopost();" );
this.doGet( req,resp );
}
}
这里十分需要强调的一点就是@WebServlet("/WelcomeServlet")这里的/
这个地方的“/”十分重要,大家千万不要忘记了,不然改代码真的非常麻烦,有一次我改了一个通宵,就是因为这个斜杠