servlet+jsp+java實現Web 應用


servlet+jsp+java實現Web 應用

  用java來構建一個web應用是特別容易的事情,jsp和php很像,可以嵌套在html中。程序的結構很簡單,也很清楚,本文主要記錄下大概的開發過程和環境的搭建。

環境搭建

下載:

  1. eclipse 
  2. tomcat
  3. eclipse tomcat 插件

開發過程

1.建立一個Dynamic Web Project

2.創建一個歡迎頁面

  頁面可以是jsp/html,我們選擇一個jsp頁面(放在WebContent內)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Do you come in?</h1>
<form method="post" action="hello.do">
    Select:<br>
    <select>
        <option>yes
        <option>no
    </select>
    <center>
        <input type="submit">
    </center>
</form>
</body>
</html>

2.向工程添加一個servlet文件

package com.example;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Welcome
 */
@WebServlet("/Welcome")
public class Welcome extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String c = request.getParameter("select");
        if(c.equals("yes"))
            out.print("Welcome!");
        else
            out.print("I don't like you!");
    }

}

3.創建一個web.xml

  web.xml用來建立servlet與jsp的關系(需要放在WEB-INF內)。

  根據不同的url來調用不同的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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name></display-name>
  <servlet>
    <servlet-name>Welcome</servlet-name>//要與下面的名稱相同
    <servlet-class>com.example.Welcome</servlet-class>//調用的類的位置
   </servlet>
   <servlet-mapping>
    <servlet-name>Welcome</servlet-name>
    <url-pattern>/hello.do</url-pattern>//url標識
  </servlet-mapping>
</web-app>

什么是MVC

  MVC全名是Model View Controller,是模型(model)-視圖(view)-控制器(controller)的縮寫。其實上面的結構就是一種MVC,頁面用jsp來展現,控制用servlet,而模型就是用普通的JAVA類來實現不同的處理過程。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM