首页 > 代码库 > 《Head First Servlets & JSP》-3-1st servlet MVC demo
《Head First Servlets & JSP》-3-1st servlet MVC demo
项目结构
用户首页
form.html
<html>
<body>
<h1 align=‘center‘>Beer Selection Page</h1>
<form method="post"
action="SelectBeer.do">
Select
<p>
Color:
<select name="color" size="1">
<option value="light"> light</option>
<option value="amber"> amber</option>
<option value="brown"> brown</option>
<option value="dark"> dark</option>
<option value="red"> red</option>
</select>
<br/><br/>
<center>
<input type="submit">
</center>
</form>
</body>
</html>
MVC之C——Servlet
BeerSelect.java
package com.example.web;
import com.example.model.BeerExpert;
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;
/**
* Created by LTN on 2016/10/30.
*/
public class BeerSelect extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws IOException ,ServletException{
response.setContentType("text/html");
String c = request.getParameter("color");
BeerExpert expert = new BeerExpert();
List result = expert.getBrands(c);
request.setAttribute("styles", result);
RequestDispatcher view = request.getRequestDispatcher("result.jsp");
view.forward(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)throws IOException,ServletException {
doGet(request,response);
}
}
MVC之M——模型
BeerExpert.java
package com.example.model;
import java.util.ArrayList;
import java.util.List;
public class BeerExpert
{
public List getBrands(String color)
{
List<String> brands = new ArrayList<String>();
if ( color.equals("amber") )
{
brands.add("Jack Amber");
brands.add("Red Moose");
}
else
{
brands.add("Jail Pale Ale");
brands.add("Gout Stout");
}
return (brands);
}
}
MVC之V——JSP
result.jsp
<%@ page import="java.util.*" %>
<html>
<body>
<h1 align="center">Beer Recommendations JSP</h1>
<p>
<%
ArrayList styles = (ArrayList)request.getAttribute("styles");
Iterator it = styles.iterator();
while(it.hasNext()) {
out.print("<br>try " + it.next());
}
%>
</body>
</html>
配置文件
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Ch3 Beer</servlet-name>
<servlet-class>com.example.web.BeerSelect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Ch3 Beer</servlet-name>
<url-pattern>/SelectBeer.do</url-pattern>
</servlet-mapping>
</web-app>
附件列表
《Head First Servlets & JSP》-3-1st servlet MVC demo
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。