<%%> 与 <%!%> 和 <%=%>的区别
名称 | 作用 | |
---|---|---|
<%%> | 脚本片段 | 其内容会翻译在Servlet的Service方法中;可以定义局部变量或者调用方法,但不能定义方法 |
<%!%> | 声明 | 其内容会直接翻译在Servlet类中,可以定义方法、属性、全局变量 |
<%=%> | JSP表达式 | 将已经声明的变量或者表达式输出到页面 |
参考资料:https://www.cnblogs.com/mark5/p/11596435.html
JSP页面执行过程
- 客户端发送Request请求
- JSP Container将JSP转译成Servlet源代码
- 将产生的Servlet源代码经过编译后,加载到内存执行
- 把结果Response(响应)到客户端
jsp执行过程分两时期:转义时期和请求时期
转义时期
系统把.jsp文件转译为servlet源代码.java文件,
将java文件编译为.class字节码文件,
再将字节码文件交给JVM执行得到数据处理结果
请求时期
把服务端处理的结果返回给html文件中,响应给客户端浏览器,由浏览器对html文件进行解释并且展示其静态内容
简述Tomcat部署war包的过程
若是自动部署
则把war包复制到webapps目录
若未开启自动部署
则把war包拖入webapps目录后
到tomcat的bin目录下,先shutdown再startup
4. 某信息系统中涉及到汽车实体,汽车主要有品牌、型号、价格和座位数等属性,请编写该实体的Java Bean
package Entity;
public class Car {
private String brand;
private String model;
private double price;
private int seats;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getSeats() {
return seats;
}
public void setSeats(int seats) {
this.seats = seats;
}
}
5. 续上题编写表单可以填入汽车信息,提交到一个JSP,该JSP能显示出该汽车的信息。请使用userBean,setProperty和getProperty等动作。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<% request.setCharacterEncoding("UTF-8");%>
<form method="post" action="demo5.jsp">
品牌:<input type="text" name="brand"><br>
型号:<input type="text" name="model"><br>
价格:<input type="text" name="price"><br>
座位数:<input type="text" name="seats"><br>
<input type="submit" value="确定">
</form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="car" class="Entity.Car"></jsp:useBean>
<html>
<head>
<title>Title</title>
</head>
<body>
<% request.setCharacterEncoding("UTF-8");%>
<jsp:setProperty name="car" property="*"></jsp:setProperty>
<jsp:setProperty name="car" property="brand" value="fd" />
<jsp:setProperty name="car" property="model" value="fd" />
<jsp:setProperty name="car" property="price" value="789" />
<jsp:setProperty name="car" property="seats" value="6" />
<!--以上为自己写入,以下为从request获取-->
<p>您输入的车辆信息如下:</p>
<p>品牌:<jsp:getProperty name="car" property="brand"/></p>
<p>型号:<jsp:getProperty name="car" property="model"/></p>
<p>价钱:<jsp:getProperty name="car" property="price"/></p>
<p>座位数:<jsp:getProperty name="car" property="seats"/></p>
</body>
</html>
请使用JSP脚本,在浏览器上显示一个九九乘法表
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<table border="1">
<tr>
<td>乘法表</td>
<%
for(int i=1;i<10;i++){
%>
<td><%=i%></td>
<%
}
%>
</tr>
<%
for(int i=1;i<10;i++){
%>
<tr>
<td><%=i%></td>
<%
for(int j=1;j<i+1;j++){
%>
<td><%=i%>×<%=j%>=<%=i*j%></td>
<%
}
%>
</tr>
<%
}
%>
</table>
</body>
</html>
已知学生成绩数据存储在ArrayList<Map<String,Object>>对象中,数据包括学号、姓名、平时成绩、实验成绩和期末成绩。 期末成绩如果大于等于50分,总评成绩有公式 平时成绩10%+实验成绩20*+期末成绩*70%计算,如果期末成绩小于50分,则总评成绩为期末成绩,低于60分成绩显示红色。编写JSP成绩打印如下表格。(提示:ArrayList中的数据硬编码写入,写入数据要求大于5条,禁止使用println/print方法进行输出, 能使用标签的地方要使用标签)
<%@ page import="java.util.Map" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
HashMap map = new HashMap();
map.put("no", "1001");
map.put("name", "Tom");
map.put("ps",93); //平时成绩
map.put("sy",85); //实验成绩
map.put("qm",88); //期末成绩
list.add(map);
map = new HashMap();
map.put("no", "1002");
map.put("name", "Jack");
map.put("ps", 76);
map.put("sy",75); //实验成绩
map.put("qm",52); //期末成绩
list.add(map);
map = new HashMap();
map.put("no", "1003");
map.put("name", "Mary");
map.put("ps", 67);
map.put("sy",65); //实验成绩
map.put("qm",48); //期末成绩
list.add(map);
request.setAttribute("data", list);
list =(List<Map<String,Object>>) request.getAttribute("data");
%>
<table border="1">
<tr>
<th>学号</th>
<th>姓名</th>
<th>平时成绩</th>
<th>实验成绩</th>
<th>期末成绩</th>
<th>总评</th>
</tr>
<%
for(Map<String,Object> stu:list){
String no = (String) stu.get("no");
String name = (String) stu.get("name");
int ps = (int) stu.get("ps");
int sy = (int) stu.get("sy");
int qm = (int) stu.get("qm");
int zp = 0;
if(qm<50){
zp = qm;
}else {
zp = (int) (ps*0.1+sy*0.2+qm*0.7);
}
String color = "";
if (zp<60){
color = "style=\"color:red\"";
}
%>
<tr align="left">
<td><%=no%></td>
<td><%=name%></td>
<td><%=ps%></td>
<td><%=sy%></td>
<td><%=qm%></td>
<td <%=color%>><%=zp%></td>
</tr>
<%
}
%>
</table>
</body>
</html>
编写满足下面要求的程序:1. JSP页面,随机生成一个100内的加法题,用户输入答案,2.点击提交按钮,数据提交给一个servlet进行处理,该servlet判断用户答题是否正确 ,然后跳转掉一个结果JSP页面。3.结果JSP页面显示加法题并给出错误还是正确的信息。(MVC模式)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
int a = (int) (Math.random()*100);
int b = (int) (Math.random()*100);
session.setAttribute("a",a);
session.setAttribute("b",b);
%>
<form method="post" action="/demo8">
<%=a%>+<%=b%>=<input type="text" name="answer"><input type="submit">
</form>
</body>
</html>
<servlet>
<servlet-name>demo8</servlet-name>
<servlet-class>Servlet.demo8</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo8</servlet-name>
<url-pattern>/demo8</url-pattern>
</servlet-mapping>
package Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class demo8 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
int a = (int) session.getAttribute("a");
int b = (int) session.getAttribute("b");
String ans = req.getParameter("answer");
if(a + b == Integer.parseInt(ans)){
session.setAttribute("result","True");
}else {
session.setAttribute("result","False");
}
session.setAttribute("a",a);
session.setAttribute("b",b);
resp.sendRedirect("/demo8_res.jsp");
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
int a = (int) session.getAttribute("a");
int b = (int) session.getAttribute("b");
String result = (String) session.getAttribute("result");
%>
<p><%=a%>+<%=b%>=<%=a+b%></p>
<%
if(result.equals("True")){
%>
<h1>你答对了</h1>
<%
}else {
%>
<h1>你答错了</h1>
<%
}
%>
</body>
</html>
编写满足下面要求的程序:第一个JSP页面输入一个数组,点击提交按钮提交到一个servlet。 在Servlet中查找这个数组的最大值,跳转到第二个JSP。在第二个JSP中显示这个最大值(MVC)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form method="post" action="/demo9">
数字1:<input type="text" name="nums"><br>
数字2:<input type="text" name="nums"><br>
数字3:<input type="text" name="nums"><br>
<input type="submit">
</form>
</body>
</html>
<servlet>
<servlet-name>demo9</servlet-name>
<servlet-class>Servlet.demo9</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo9</servlet-name>
<url-pattern>/demo9</url-pattern>
</servlet-mapping>
package Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class demo9 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String[] nums = req.getParameterValues("nums");
int max = 0;
for(String s:nums){
int newNum = Integer.parseInt(s);
max = max>newNum ? max:newNum;
}
HttpSession session = req.getSession();
session.setAttribute("max",max);
resp.sendRedirect("/demo9_res.jsp");
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
int max = (int) session.getAttribute("max");
%>
<h1>输入的数字中最大值是:<%=max%></h1>
</body>
</html>
浏览器上要显示一个学生信息列表,学生主要有学号、姓名、性别、年龄、手机号码等信息,这些信息存储在数据库表student中。请给出一个实现该功能并且符合MVC模式及DAO模式的详细设计,列举出你将创建哪些源文件并说明每个源文件的作用
Student.jsp:显示学生信息JSP、
Student.jsp:学生实体类 JavaBean、
StudentDao:针对数据层操作的接口 Dao、
StudnetDaoImpl:实现dao层定义的接口,具体进行增删改查 DaoImplement、
StudentService:服务接口,具体业务逻辑 Service、
ServiceDaoImpl:实现dao层定义的接口,具体进行业务操作 ServiceImplement、
多个Servlet分别处理前端发来的业务请求
11. 设计一个过滤器,过滤掉以T开头的用户名登陆,使其登录到错误页面,其他则登录到成功界面。写出主要代码,并叙述设计思想及步骤
public class MyFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse) response;
String username = (String)req.getSession().getAttribute("username");
if(username.startsWith("T")){
resp.sendRedirect("error.jsp");
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>edu.just.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
设计实现一个监听器,当Web应用启动时,建立一个数据库连接,以备给整个应用使用,当应用销毁时,关闭连接。编写主要代码及叙述设计思想及实现步骤
监听器类
public class GetConnListener implements ServletContextListener
{
// 应该启动时,该方法被调用。
public void contextInitialized(ServletContextEvent sce)
{
try
{
// 取得该应用的ServletContext实例
ServletContext application = sce.getServletContext();
// 从配置参数中获取驱动
String driver = application.getInitParameter("driver");
// 从配置参数中获取数据库url
String url = application.getInitParameter("url");
// 从配置参数中获取用户名
String user = application.getInitParameter("user");
// 从配置参数中获取密码
String pass = application.getInitParameter("pass");
// 注册驱动
Class.forName(driver);
// 获取数据库连接
Connection conn = DriverManager.getConnection(url
, user , pass);
// 将数据库连接设置成application范围内的属性
application.setAttribute("conn" , conn);
}
catch (Exception ex)
{
System.out.println("Listener中获取数据库连接出现异常"
+ ex.getMessage());
}
}
// 应该关闭时,该方法被调用。
public void contextDestroyed(ServletContextEvent sce)
{
// 取得该应用的ServletContext实例
ServletContext application = sce.getServletContext();
Connection conn = (Connection)application.getAttribute("conn");
// 关闭数据库连接
if (conn != null)
{
try
{
conn.close();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
}
}
测试页面
<body>
下面是直接从application中取出数据库连接,<br/>
并执行查询后的结果<br/>
<%
Connection conn = (Connection)application.getAttribute("conn");
// 创建Statement对象
Statement stmt = conn.createStatement();
// 执行查询
ResultSet rs = stmt.executeQuery("select * from news_inf");
%>
<table bgcolor="#9999dd" border="1" width="300">
<%
// 遍历结果集
while(rs.next())
{
%>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
</tr>
<%
}
%>
<table>
</body>
MySQL数据库bank中有张数据库表account(ID:int,name:varchar(20), balance:decimal(20,4)),该表表示用户银行账户的余额,balance字段表示余额数。请编写一个方法将ID=1的用户账上的1000元转账到ID=2的用户账上,并提供事务支持
public static void main(String[] args){
Connection conn = null;
PreparedStatement updateSalary = null;
String updateStatement = "update student set score=score+? where id=?";
try {
conn=DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
conn.setAutoCommit(false); //关闭事务自动提交
updateSalary = conn.prepareStatement(updateStatement);
updateSalary.setDouble(1, 10);
updateSalary.setInt(2, 1002);
updateSalary.executeUpdate();
//if(1==1)throw new SQLException(); //抛出一个异常
updateSalary.setDouble(1, -10);
updateSalary.setInt(2, 1004);
updateSalary.executeUpdate();
conn.commit(); //提交事务
} catch (SQLException e) {
e.printStackTrace();
if (conn != null) {
try {
System.err.print("Transaction is being rolled back");
conn.rollback(); //有异常,回滚
} catch (SQLException excep) {
excep.printStackTrace();
}
}
} finally {
if (updateSalary != null) {
try {
updateSalary.close();
} catch (SQLException ex) {
Logger.getLogger(TransactionDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
conn.setAutoCommit(true);
} catch (SQLException ex) {
Logger.getLogger(TransactionDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
MySQL数据库Study中有张数据库表student(ID:int,name:varchar(20), age:int,score:double,birthday:date),请编写一个方法将该表中的所有记录存储到一个List<Map<String,Object>>对象中
public List<Map<String,Object>> findAll() throws Exception {
Connection conn = null;
Class.forName(DBDRIVER);// JDBC4.0后可自动加载
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
List<Map<String,Object>> allStudents = new ArrayList();
PreparedStatement pstmt = null;
String sql = "SELECT * FROM student ";
try {
pstmt = this.conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
Map s = null;
while (rs.next()) {
s = new HashMap<String,Object>();
s.put("id",rs.getInt("ID"));
s.put("name",rs.getString("name"));
s.put("age",rs.getInt("age"));
s.put("score",rs.getFloat("score"));
s.put("birthday",rs.getDate("birthday"));
allStudents.add(s);
}
rs.close();
} catch (Exception e) {
throw e;
} finally {
try {
conn.close
pstmt.close();
} catch (Exception e) {
}
}
return allStudents;
}