Servlet & Jsp | 3: MVC development projects under the idea

 

table of Contents

Servlet & Jsp MVC pattern in the world:

First, create a JavaWeb project, complete html page

1. Create a project 

2, the preparation home side 

Second, the web.xml configuration file, url mapped to the servlet

Third, to implement a Java servlet class

1, create a model of the servlet

2, in order to implement a Java servlet class

Fourth, implement the corresponding Jsp view file

end 



Servlet & Jsp MVC pattern in the world:

Servlet in the controller (control), Jsp display view (view), plain Java classes model (model).

Behind each of these services (request + response), it should be a mode MVC formula:

More specific:

A user issues a request from the browser, is transmitted to the web server via the http protocol, which is a web server dynamic discovery request, it will process the request to tomcat container. tomcat container to find the instruction corresponding servlet .class file, start its service () function runs. In the course of this operation will be called Java class model to achieve the request pass over, and the results transmitted to a request through the jsp file, this will eventually tomcat jsp page through the vessel returned to the user.


This article will create a very simple JavaWeb applications, mainly to get started familiar with the MVC pattern of development projects under the idea development environment. The main Note: In the Tomcat Servlet and Jsp container management component, how do we deploy an application.

Note: jsp is the actual html page and then insert a java code, that's it! 


First, create a JavaWeb project, complete html page

1. Create a project 

First of all, the right to create a new project in JavaWeb idea, named JeffChang's Concert. Specific operations can refer to: IDEA a configuration item JavaWeb

The project is mainly used to query information Jeff Chang first 11 World Tour, the home will have a form to select the year, after the user submits the form results page will pop up, telling the user what information the concert with the city during the year. So cool!

2, the preparation home side 

Modify the index.jsp file (this is the default page of our project), as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>

<head>
    <title>JeffChang's Concert</title>
</head>

<body>
<h1 align="center">Welcome to JeffChang's Concert Page!</h1>
<h2 align="center">Year Select Page</h2>
<form method="POST" action="query.do">   <!-- action即当用户提交这个表单时,将传递给url名为query.do的servlet -->
    Select year:
    <p>
        <!-- 创建一个下拉菜单-->
        <select name="year" size="1">
            <option value="2018"> 2018 </option>
            <option value="2019"> 2019 </option>
            <option value="2020"> 2020 </option>
        </select>
    <br><br>
    <div style="text-align: center;">
        <input type="SUBMIT">
    </div>
</form>
</body>

</html>

After written, direct run to see if there is wrong. Web page should appear as follows:

 

The Select a year to submit the form, there will be 404 ❗. Because we did not realize the form action attribute points to the servlet, so when you submit the form, tomcat will pass your request to the action attribute points to the servlet, but can not find, so there are 404.


Second, the web.xml configuration file, url mapped to the servlet

web.xml file is a deployment file tomcat container. When a user sends a request to the url is passed a web server, the url is to be mapped to a particular servlet to respond accordingly by tomcat.

web.xml file code is as follows:

<?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>
        <!-- 对应mapping中某一个servlet的内部名 -->
        <servlet-name>name1</servlet-name>
        <!-- 当收到请求时,要调用的Java类的相对路径(相对classes文件) -->
        <servlet-class></servlet-class>
    </servlet>

    <servlet-mapping>
        <!-- 为了方便部署,给这个servlet取一个内部名 -->
        <servlet-name>name1</servlet-name>
        <!-- 在index.jsp页面中对应的某表单action属性 -->
        <url-pattern>/query.do</url-pattern>
    </servlet-mapping>

</web-app>

Notice that the servlet-class will not join, because we have not written correspondence --Java servlet class. It will be added later.

In this case, run it, just choose a time, try to submit the form:

500 at this time will complain, but not before the 404! Because we have deployed servlet url and mapping, but this has not been achieved a java servlet class ~


Third, to implement a Java servlet class

1, create a model of the servlet

MVC, which represents the model M, a bunch of back-end pure Java code . The Java servlet class to call this model is implemented to calculate the request sent to the user, to give the corresponding results . So, you want to implement a Java servlet class, it must implement a corresponding model.

In the project's src directory , create a new class Concert, and implementation of a getConcertList:

import java.util.ArrayList;
import java.util.List;

public class Concert {
    private String time;  //演唱会的时间
    private String region;  //演唱会的地区
    private int num;  //巡演的场次

    public Concert() { }
    
    public Concert (int num, String time, String region) {
        this.num = num;
        this.region = region;
        this.time = time;
    }

    public List getConcertList(String year) {
        List concertList = new ArrayList();
        if(year.equals("2018")) {
            concertList.add(new Concert(1,"2018-10-13","北京-五棵松体育馆"));
            concertList.add(new Concert(2,"2018-10-14","北京-五棵松体育馆"));
            concertList.add(new Concert(3,"2018-11-02","澳门-金光综艺馆"));
            concertList.add(new Concert(4,"2018-12-22","深圳-深圳湾体育中心"));
        }
        else if(year.equals("2019")) {
            concertList.add(new Concert(5,"2019-01-19","成都-成都大魔方"));
            concertList.add(new Concert(6,"2019-04-06","台北-小巨蛋"));
            concertList.add(new Concert(7,"2019-04-13","广州-广州宝能体育中心"));
            concertList.add(new Concert(8,"2019-04-27","南京-青奥体育公园体育馆"));
            concertList.add(new Concert(9,"2019-05-11","新加坡-室内体育馆"));
            concertList.add(new Concert(10,"2019-6-08","济南-济南奥体中心体育馆"));
            concertList.add(new Concert(11,"2019-6-22","苏州-苏州奥体中心体育馆"));
            concertList.add(new Concert(12,"2019-6-29","福州-海峡奥体综合体育馆"));
            concertList.add(new Concert(13,"2019-7-13","马来西亚-云顶云星剧场"));
            concertList.add(new Concert(14,"2019-7-14","马来西亚-云顶云星剧场"));
            concertList.add(new Concert(15,"2019-7-26","大连-大连体育中心体育馆"));
            concertList.add(new Concert(16,"2019-8-17","重庆-华熙文化体育中心"));
            concertList.add(new Concert(17,"2019-11-16","佛山-国际体育文化演艺中心"));
            concertList.add(new Concert(18,"2019-11-23","宁波-奥体中心体育馆"));
            concertList.add(new Concert(19,"2019-11-30","长沙-国际会展中心"));
            concertList.add(new Concert(20,"2019-12-14","上海-梅赛德斯奔驰体育中心"));
            concertList.add(new Concert(21,"2019-12-15","上海-梅赛德斯奔驰体育中心"));
            concertList.add(new Concert(22,"2019-12-22","沈阳-辽宁省体育馆"));
        } else if(year.equals("2020")) {
            concertList.add(new Concert(23,"2020-01-01","无锡-无锡市体育馆"));
            concertList.add(new Concert(24,"2020-04-28","英国-伦敦皇家阿尔伯特音乐厅"));
        }
        return concertList;
    }

    public String toString() {
        return "第"+this.num+"场 - " + this.time + " :    " + this.region + "\n";
    }
}

2, in order to implement a Java servlet class

In the project's src directory , create a new YearQueryServlet class must inherit HttpServlet, and override the doPost method ( do not leave super.doPost (req, resp); this statement ). And obtain information from Concert.java model, passed to the view jsp page.

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class YearQueryServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        /* 从模型获取答案*/
        String year = req.getParameter("year");  //从请求的信息(表单)内,找到name属性为year的表单,并获取用户提交的结果
        Concert concert = new Concert();
        List ans = concert.getConcertList(year);

        /* 将模型组件的贵大增加到请求对象 */
        req.setAttribute("styles", ans);  //为请求对象增加一个属性,其值为ans,供给jsp使用
        RequestDispatcher view = req.getRequestDispatcher("YearQueryResult.jsp"); //为jsp实例化一个请求分派器
        view.forward(req, resp); //使用请求分派器要求容器准备好jsp,并向jsp发送请求和响应
    }
}

The Servlet inherited position corresponding Java class HttpServlet complement to the servlet-class:

<!-- 当收到请求时,要调用的Java类的相对路径(相对classes文件) -->
<servlet-class>YearQueryServlet</servlet-class>

 Note: There have not written "YearQueryResult.jsp" view file, just build a servlet using the model and the results come jsp file transfer bridge.

At this point, and then run the program, just select a year and submit the form. Can see a 404 error, the error page as described in detail: /JeffChang%20Concert/YearQueryResult.jsp , i.e. not find the corresponding files jsp view. ok, that we bridge has been built successfully, but the lack of a view jsp files.


Fourth, implement the corresponding Jsp view file

Jsp to create a file in the web directory of the project - YearQueryResult.jsp file. We need to go back and view code is written:

Preceded by stressed: JSP is the actual html page and then insert a java code . Java code at the time of writing, we write the symbol <%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>JeffChang's Concert</title>
</head>
<body>
<h1 align="center">张信哲第11轮世界巡回演唱会 - 未来式</h1>
<p>
    <%
        List styles = (List)request.getAttribute("styles");  //从请求对象得到一个属性(就是答案)
        /* 将结果显示在网页上 */
        Iterator it = styles.iterator();
        while (it.hasNext())
            out.println(it.next() + "<br>");
    %>
</p>
</body>
</html>

This item file directory as follows: 


A simple MVC program is complete, simply following test:

Run directly away from the -

2018,2019,2020 are respectively supplied form the following results:

yeah! It's done -

 



end 

No personal welcome attention to the public " chicken wings Programming" , here is a serious and well-behaved code agricultural one.

---- do the most well-behaved blog er, do the most solid programmer ----

Aims to carefully write each article, usually aggregated into notes will push updates -

Here Insert Picture Description

 

Published 138 original articles · won praise 63 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_43787043/article/details/104604359
Recommended