在web.xml中配置Servlet时或者在注解中配置Servlet时,可以配置一些初始化参数,而在Servlet中可以通过
ServletConfig接口提供的方法来取得这些参数。
例子:ServletDemo:
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServletDemmo
*/
@WebServlet(name="ServletDemo" ,urlPatterns={"/ServletDemo"},
initParams={
@WebInitParam(name="username",value="admin"),
@WebInitParam(name="password",value="123456")
})
public class ServletDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* @see HttpServlet#HttpServlet()
*/
public ServletDemo() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
this.username = config.getInitParameter("username");
this.password = config.getInitParameter("password");
}
/**
* @see Servlet#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("<h1>用户名:"+this.getUsername()+"</h1>");
out.print("<h1>密码:"+this.getPassword()+"</h1>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
index.jsp页面源码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Servlet编程</title> </head> <body> <h1>获取初始化参数</h1> <hr/> <a href="ServletDemo">获取初始化参数ServletDemo</a> </body> </html>
运行结果:
MVC简介
MVC模式:MVC的全称是Model View Controller,是软件开发过程中比较流行的设计思想,旨在分离模型、控
制、视图。是一种分层思想的体现。
MVC模式示意图:
Model1模型示意图:
Model2模型示意图:
Java Web的Model2开发模型就是NVC思想的体现。
1)JSP页面充当的是视图层
2)Servlet是控制层
3)JavaBean是模型层
4)DB数据库层
未完待续。。。
原文:http://blog.csdn.net/erlian1992/article/details/52129813