JavaWeb复习

JavaWeb复习

java与web数据库必考知识点:
1、struts2框架中action类的配置文件怎么写
2、JDBC数据库连接代码,preparedstatement接口查询数据库的代码
3、javabeans类的编写
4、如何通过EL表达式语言访问javabeans对象的属性
5、java servlet中如何获取用户通过表单发送的参数?

6、jsp:useBean jsp:setProperty和jsp:getProperty标签 的基本使用

说明:上述问题不是考简答题,而是以编程题的形式出现。

1、struts2框架中action类的配置文件怎么写?

首先struts2的框架是用来做视图渲染的,和SpringMVC差不多的功能,无非就是将Http请求转发到相应的方法,然后根据方法的返回值来进行对应的视图渲染并且返回给用户。

所以,action类就是对应的这里的方法,struts2会将用户的请求转发到action类,并且筛选相应的方法处理。那么,如何精准定位到准确的action类,这就需要配置文件了:

<struts>
	<package name="demo" extends="struts-default" namespace="/demo">
        
    	<action name="demoAction" class="cn.bestrivenlf.demo.DemoAction" >
            
        	<result name="helloworld" type="dispatcher" >helloWorld.jspresult>
            
        	<result name="error" type="dispatcher" >error.jspresult>
            <result >default.jspresult>
        action>
    package>
struts>

下面写一个测试用例:

package demo
    public class DemoAction{
		public String param2;
        public String getParam2(){
            return this.param2;
        }
        public void getParam2(String p){
            this.param2=p;
        }
        public String helloworld(){
            return "helloworld";//会返回helloWorld.jsp页面
        }
        public String error(){
            return "error";//会返回error.jsp页面
        }
        public String default(){
            return "default";//会返回default.jsp页面
        }
        
    } 

前台跳转方式:

<a href="demo/demoAction!helloworld">进入helloworld.jsp页面a>
<a href="demo/demoAction!error">进入error.jsp页面a>
<a href="demo/demoAction!default">进入defaultd.jsp页面a>

2、JDBC数据库连接代码,preparedstatement接口查询数据库的代码

package demo;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JDBCdemo {
	public static void main(String[] args)throws Exception {
		//驱动包
		Class.forName("com.mysql.jdbc.Driver");
		//连接信息 :地址、用户名、密码
		String url = "jdbc:mysql://120.78.209.159:3306/myWebsite?characterEncoding=utf-8";
		String username = "myWebsite";
		String password = "60085040";
		Connection connection = DriverManager.getConnection(url, username, password);
		//System.out.println(connection);
		//查询语句
		String selectSql = "select * from user_account_tb ";
		//插入语句
		String insertSql = "insert into user_account_tb values(?,?,?,?,?,?,1)";
		//更新语句
		String updateSql = "update user_account_tb set username=? where id=?";
		//删除语句
		String deleteSql = "delete from user_account_tb where id = 'test'";
		//执行插入
		insert(connection, insertSql);
		//执行查询
		select(connection, selectSql);
		//执行更新
		update(connection, updateSql);
		//查询验证
		select(connection, selectSql);
		//执行删除
		delete(connection, deleteSql);
		//查询验证
		select(connection, selectSql);		
		//关闭连接
		connection.close();
	}
	public static void insert(Connection connection,String insertSql)throws Exception {
		
		PreparedStatement preparedStatement = connection.prepareStatement(insertSql);
		preparedStatement.setString(1, "test");
		preparedStatement.setString(2, "test");
		preparedStatement.setString(3, "test");
		preparedStatement.setString(4, "test");
		preparedStatement.setString(5, "test");
		preparedStatement.setString(6, "test");
		int row = preparedStatement.executeUpdate();
		if(row>0) {
			System.out.println("插入成功");
		}
		preparedStatement.close();
	}
	public static List<User> select(Connection connection,String selectSql)throws Exception {
		
		PreparedStatement statement = connection.prepareStatement(selectSql);
		ResultSet resultSet = statement.executeQuery(selectSql);
		List<User> userList = new ArrayList<>();
		System.out.println("-----------查询结果-------------");
		while(resultSet.next()) {
			User user = new User();
			user.setId(resultSet.getString(1));
			user.setUsername(resultSet.getString(2));
			user.setPassword(resultSet.getString(3));
			user.setSalt(resultSet.getString(4));
			user.setDate(resultSet.getString(5));
			user.setNewdate(resultSet.getString(6));
			user.setDel_flag(resultSet.getInt(7));
			userList.add(user);
			System.out.println(user.toString());
		}
		statement.close();
		System.out.println("------------------------------");
		return userList;
		
	}
	public static void update(Connection connection,String updateSql)throws Exception {
		
		PreparedStatement updatePs = connection.prepareStatement(updateSql);
		updatePs.setString(1, "updateTest");
		updatePs.setString(2, "test");
		updatePs.executeUpdate();
		System.out.println("更新成功");
		updatePs.close();
	}
	
	public static void delete(Connection connection,String deleteSql)throws Exception {
		PreparedStatement deletePs = connection.prepareStatement(deleteSql);
		//deletePs.setString(1, "test");
		int row = deletePs.executeUpdate(deleteSql);
		if(row>0) {
			System.out.println("删除成功");
		}
		deletePs.close();
	}


}

运行截图

3/4/6、javabeans类的编写/如何通过EL表达式语言访问javabeans对象的属性/jsp:useBean> jsp:setProperty和jsp:getProperty标签 的基本使用

首先javaBean是什么?其实它就是一个java对象,用来具体它干啥的,书上讲的很详细。

然后javabean怎么用?既然它是一个java类,那肯定需要写java类,那我们先写一个java类User,它是用来存储用户信息的。这里我们就用到了id、username、password(ID在BaseEntity里面,这里是直接从项目里拿出来的代码,所以继承关系没有改,反正很好理解)

package demo;

/**
 * 
 *

title:User

*

Description:用户信息类与数据库中User_tb对应

*

college:HYIT

* @author 刘凡 * @date */
public class User extends BaseEntity { private String username; private String password; private String salt; private String newdate; public User(String id) { super(id); } public User() { super(); } @Override public String toString() { return "User [username=" + username + ", password=" + password + ", salt=" + salt + ", newdate=" + newdate + "]"; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public String getNewdate() { return newdate; } public void setNewdate(String newdate) { this.newdate = newdate; } 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; } }

然后javaBean可以用在JSP里面,这样可以减少jsp中的java代码,提高代码可阅读性:

首先我们按照书上的例子来写一个表单提交:

 <form action="display.jsp" >
 	I  D:<input name="id" ><br><br>
 	昵称:<input name="username"><br><br>
 	密码:<input name="password"><br><br>
 	<input type="submit" value="提交">
 form>

单击提交按钮以后发生了什么?这里表单没有指定method,默认采用get方法提交,会看到地址后面接上问号然后带上参数,就这样把数据提交到了display.jsp页面

然后看display.jsp页面代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<jsp:useBean id="user" class="demo.User">
	<jsp:setProperty name="user" property="*"/>
jsp:useBean>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>标题title>
head>
<body>

	
 <h1>使用标签获取javaBean属性h1>
    
 ID:<jsp:getProperty property="id" name="user"/><br>
 昵称:<jsp:getProperty property="username" name="user"/><br>
 密码:<jsp:getProperty property="password" name="user"/><br>
  <h1>使用EL表达式获取javaBean属性h1>
 ID:${user.getId()}<br>
 昵称:${user.getUsername()}<br>
 密码:${user.getPassword()}<br>
body>
html>

5、java servlet中如何获取用户通过表单发送的参数?

首先servlet是啥?其实servlet也是一个java类,不过它是实现了HttpServlet接口的java类,它用来干啥呢?其实就是处理Http请求的,还是以表单提交为例,当用户提交一个表单请求后,进入servlet处理会发生啥??

首先我们要注册一个Servlet,在哪里注册?我选择注解方式,其实用IDE自动创建servlet就会自动注册了

package demo;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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 ProcessFormServlet
 */
@WebServlet("/ProcessFormServlet")//注册servlet注解方式
public class ProcessFormServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProcessFormServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		//处理表单请求
		request.setCharacterEncoding("UTF-8");
		String id = request.getParameter("id");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User user = new User();
		user.setId(id);
		user.setUsername(username);
		user.setPassword(password);
		//response.getWriter().append("Served at: ").append(request.getContextPath()).append("\n"+user.toString());
		request.setAttribute("user", user);
		RequestDispatcher requestDispatcher = request.getRequestDispatcher("display.jsp");
		requestDispatcher.forward(request, response);
	}

	/**
	 * @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);
	}

}

重点看doGet方法,因为我表单默认使用get提交请求,请求进来后表单页面提交的数据会根据name属性存放在request域中,使用request的getParameter方法取出来注入到User类,这就完成了业务逻辑的模拟,然后接下来我们将user返回给页面,只需要将user放回request域中,进行页面的一个转发,转发到display.jsp页面显示即可。

来看一下表单页面index.jsp代码:

 
<form action="ProcessFormServlet" >
 	I  D:<input name="id" ><br><br>
 	昵称:<input name="username"><br><br>
 	密码:<input name="password"><br><br>
 	<input type="submit" value="提交">
 form>

然后再display.jsp页面使用JavaBean的获取数据的方式来获取user对象的数据就可以了

 <h1>使用标签获取javaBean属性h1>
 ID:<jsp:getProperty property="id" name="user"/><br>
 昵称:<jsp:getProperty property="username" name="user"/><br>
 密码:<jsp:getProperty property="password" name="user"/><br>
  <h1>使用EL表达式获取javaBean属性h1>
 ID:${user.getId()}<br>
 昵称:${user.getUsername()}<br>
 密码:${user.getPassword()}<br>

当然了如果表单提交采用post的方式的话那么自然要实现servlet的doPost方法。

你可能感兴趣的:(javaweb)