javaweb Servlet接口写法

接口核心流程

  • java
    • 1.建立Dynamic Web Project项目(javaweb)
    • 2.创建-包-servlet
      • [ ] 3.javaweb加入头部开启跨域
response.setHeader("Access-Control-Allow-Origin", "*");
  • 4.请求
    • doget 写get请求
      • [ ] 接取数据库信息
      • [ ] 转成json形式
      • 传到前台
    • dopost 写post请求
  • web
    • 调取接口
    • error问题
dataType: "json"//传值类型不对就算成功接取数据也会返回error

1.eclipse 创建项目

Dynamic Web Project

  1. 创建servlet
图片
package com.niu;

import java.io.IOException;
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 ServletTest
 */
@WebServlet("/ServletTest")
public class ServletTest extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletTest() {
        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
        //response.getWriter().append("Served at: ").append(request.getContextPath());
        response.setHeader("Access-Control-Allow-Origin", "*");
  response.setHeader("Content-type", "text/html;charset=UTF-8");        
        response.setCharacterEncoding("UTF-8");     
        /**      * 当多线程并发访问这个方法里面的代码时,会存在线程安全问题吗         
         * * i变量被多个线程并发访问,但是没有线程安全问题,因为i是doGet方法里面的局部变量,         
         * * 当有多个线程并发访问doGet方法时,每一个线程里面都有自己的i变量, 各个线程操作的都是自己的i变量,所以不存在线程安全问题         
         * * 多线程并发访问某一个方法的时候,如果在方法内部定义了一些资源(变量,集合等) 那么每一个线程都有这些东西,所以就不存在线程安全问题了      
         * */       
        String text = (String) request.getParameter("text");        
        System.out.println("结果已经传入后台:" + text);         
        String output = "后台返回的结果加上前台的结果" + text;        
        response.getWriter().write(output);
        
    }

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

}
package com.runoob.test;
import java.io.PrintWriter;
import java.sql.*;
import java.util.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
/**
 * Servlet implementation class DatabaseAccess
 */
@WebServlet("/DatabaseAccess")
public class DatabaseAccess extends HttpServlet {
    private static final long serialVersionUID = 1L;
    // JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/myigou?useSSL=false";  
    // 数据库的用户名与密码,需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "23629423";  
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DatabaseAccess() {
        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
        Connection conn = null;
        Statement stmt = null;
        // 设置响应内容类型
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("text/html;charset=UTF-8");
        
        try{
            // 注册 JDBC 驱动器
            Class.forName(JDBC_DRIVER);
            
            // 打开一个连接
            conn = DriverManager.getConnection(DB_URL,USER,PASS);

            // 执行 SQL 查询
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT address_id, addressinfo, addressarea FROM address";
            
            ResultSet rs = stmt.executeQuery(sql);
            JSONArray jsonData = JSONArray.fromObject(convertList(rs)); 
            System.out.println(jsonData.toString());
            PrintWriter out = response.getWriter();    //把json数据传递到前端,记着前端用ajax接收
            out.print(jsonData);
//            response.getWriter().write(rs);
            // 展开结果集数据库         
            /*while(rs.next()){
                // 通过字段检索
                // 通过字段检索
                int id  = rs.getInt("address_id");
                String name = rs.getString("addressinfo");
                String url = rs.getString("addressarea");
    
                // 输出数据
                out.println("ID: " + id);
                out.println(", 站点名称: " + name);
                out.println(", 站点 URL: " + url);
                out.println("
"); }*/ /*out = response.getWriter(); */ // 完成后关闭 rs.close(); stmt.close(); conn.close(); } catch(SQLException se) { // 处理 JDBC 错误 se.printStackTrace(); } catch(Exception e) { // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 最后是用于关闭资源的块 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ } try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } // ResultSet rs 转json private static List convertList(ResultSet rs) throws SQLException { List list = new ArrayList(); ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); while (rs.next()) { Map rowData = new HashMap(); for (int i = 1; i <= columnCount; i++) { rowData.put(md.getColumnName(i), rs.getObject(i)); } list.add(rowData); } return list; } /** * @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); } }

3.编写xml

图片


    gitTest
    
        index.html
        index.htm
        index.jsp
        default.html
        default.htm
        default.jsp
    
    
        default
        org.apache.catalina.servlets.DefaultServlet
        
            debug
            0
        
        
            listings
            false
        
        1
    
    
        ServletDemo1
        com.niu.ServletTest
    
    
        ServletDemo1
        /ajaxtest
    




4.项目内ajax调取接口








测试用例



    

测试例子

5.项目外调取接口





    
    
    
    Document





    
    




你可能感兴趣的:(javaweb Servlet接口写法)