《Head First Servlets & JSP》-3-1st servlet MVC demo
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《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的主要内容,如果未能解决你的问题,请参考以下文章
《Head First Servlets & JSP》-5-属性和监听
《Head First Servlets & JSP》-4-请求和响应
《Head First Servlets & JSP》-10-定制标记开发
《Head First Servlets & JSP》-6-会话管理