Меню

Org apache jasper jasperexception произошла ошибка при обработке

geniusis

1 / 1 / 0

Регистрация: 12.06.2019

Сообщений: 7

1

11.11.2020, 02:48. Показов 1030. Ответов 2

Метки jsp, sql, tomcat (Все метки)


Добрый день, ошибка в передачи атрибутов в jsp странницу((

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    for(int i = 0; i < countTable; i++) {
        if(req.getParameter("key").equals(tables[i].getName())) {
            try {
                String[][] table = tables[i].getTable();
                int x = table.length;
                int y = table[0].length;
                req.setAttribute("table", table);
                req.setAttribute("x_atr", x);
                req.setAttribute("y_atr", y);
                req.getRequestDispatcher("/BD3-1/view.jsp").forward(req, resp);
            } catch (SQLException e) {}
            break;
        }
    }
}
HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%
    String[][] table = (String[][]) request.getAttribute("table");
    //int x = request.getAttribute("x_atr");
    //int y = request.getAttribute("y_atr");
    out.println("<table>");
    out.println("<tbody>");
    for(int k = 0; k < request.getAttribute("x_atr"); k++) {
        out.println("<tr>");
        for(int m = 0; m < request.getAttribute("y_atr"); m++) {
            out.println("<td>");
            out.println(table[k][m]);
            out.println("</td>");
        }
        out.println("</tr>");
    }
    out.println("</tbody>");
    out.println("</table>");
%>

И сама ошибка

Кликните здесь для просмотра всего текста

Type Exception Report

Message Unable to compile class for JSP:

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: [16] in the jsp file: [/view.jsp]
The operator < is undefined for the argument type(s) int, Object
13: //int y = request.getAttribute(«y_atr»);
14: out.println(«<table>»);
15: out.println(«<tbody>»);
16: for(int k = 0; k < request.getAttribute(«x_atr»); k++) {
17: out.println(«<tr>»);
18: for(int m = 0; m < request.getAttribute(«y_atr»); m++) {
19: out.println(«<td>»);

An error occurred at line: [18] in the jsp file: [/view.jsp]
The operator < is undefined for the argument type(s) int, Object
15: out.println(«<tbody>»);
16: for(int k = 0; k < request.getAttribute(«x_atr»); k++) {
17: out.println(«<tr>»);
18: for(int m = 0; m < request.getAttribute(«y_atr»); m++) {
19: out.println(«<td>»);
20: out.println(table[k][m]);
21: out.println(«</td>»);

Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.jav acError(DefaultErrorHandler.java:103)
org.apache.jasper.compiler.ErrorDispatcher.javacEr ror(ErrorDispatcher.java:213)
org.apache.jasper.compiler.JDTCompiler.generateCla ss(JDTCompiler.java:528)
org.apache.jasper.compiler.Compiler.compile(Compil er.java:392)
org.apache.jasper.compiler.Compiler.compile(Compil er.java:362)
org.apache.jasper.compiler.Compiler.compile(Compil er.java:346)
org.apache.jasper.JspCompilationContext.compile(Js pCompilationContext.java:605)
org.apache.jasper.servlet.JspServletWrapper.servic e(JspServletWrapper.java:400)
org.apache.jasper.servlet.JspServlet.serviceJspFil e(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.init(JspServl et.java:139)
org.apache.catalina.authenticator.AuthenticatorBas e.invoke(AuthenticatorBase.java:541)
org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve. invoke(AbstractAccessLogValve.java:690)
org.apache.catalina.connector.CoyoteAdapter.servic e(CoyoteAdapter.java:343)
org.apache.coyote.http11.Http11Processor.service(H ttp11Processor.java:374)
org.apache.coyote.AbstractProcessorLight.process(A bstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandl er.process(AbstractProtocol.java:868)
org.apache.tomcat.util.net.NioEndpoint$SocketProce ssor.doRun(NioEndpoint.java:1590)
org.apache.tomcat.util.net.SocketProcessorBase.run (SocketProcessorBase.java:49)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker( ThreadPoolExecutor.java:1130)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:630)
org.apache.tomcat.util.threads.TaskThread$Wrapping Runnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:832)
Note The full stack trace of the root cause is available in the server logs.

Долблюсь уже 2 дня, не понимаю в чем ошибка(

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Эксперт Java

3636 / 2968 / 918

Регистрация: 05.07.2013

Сообщений: 14,220

11.11.2020, 08:57

2

Цитата
Сообщение от geniusis
Посмотреть сообщение

request.getAttribute

видимо это возвращает Object, кастани в нужный класс



0



geniusis

1 / 1 / 0

Регистрация: 12.06.2019

Сообщений: 7

11.11.2020, 12:11

 [ТС]

3

Пробовал((
Но ошибка уже другая

Кликните здесь для просмотра всего текста

Type Exception Report

Message Произошла ошибка при обработке [/view.jsp] в строке [16]

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.apache.jasper.JasperException: Произошла ошибка при обработке [/view.jsp] в строке [16]

13: //int y = request.getAttribute(«y_atr»);
14: out.println(«<table>»);
15: out.println(«<tbody>»);
16: for(int k = 0; k < (int)request.getAttribute(«x_atr»); k++) {
17: out.println(«<tr>»);
18: for(int m = 0; m < (int)request.getAttribute(«y_atr»); m++) {
19: out.println(«<td>»);

Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handle JspException(JspServletWrapper.java:626)
org.apache.jasper.servlet.JspServletWrapper.servic e(JspServletWrapper.java:515)
org.apache.jasper.servlet.JspServlet.serviceJspFil e(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspSe rvlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet .java:750)
org.apache.tomcat.websocket.server.WsFilter.doFilt er(WsFilter.java:53)
Root Cause

java.lang.NullPointerException
org.apache.jsp.view_jsp._jspService(view_jsp.java: 132)
org.apache.jasper.runtime.HttpJspBase.service(Http JspBase.java:71)
javax.servlet.http.HttpServlet.service(HttpServlet .java:750)
org.apache.jasper.servlet.JspServletWrapper.servic e(JspServletWrapper.java:477)
org.apache.jasper.servlet.JspServlet.serviceJspFil e(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspSe rvlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet .java:750)
org.apache.tomcat.websocket.server.WsFilter.doFilt er(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.

Добавлено через 26 минут
Нашел ошибку, ошибка была очень тупая и допущена из-за невнимательности. Это web.xml файл

XML
1
2
3
4
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

Нужно было эту строчку воткнуть ((



0



У меня есть этот код jsp, где я пытаюсь редактировать информацию для пользователя на моей веб-странице. Я новичок в программировании jsp, и я испытываю ошибки. Вот мой код:

<%@page import="DatabaseTransactions.UserPhotosDataContext"%>
<%@page import="java.sql.ResultSet"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
            if (session.getAttribute("id") == null) {
                response.sendRedirect(request.getContextPath() + "/sign-in.jsp");
            }

            int userId = Integer.parseInt(session.getAttribute("id").toString());
            ResultSet userInfo = UserPhotosDataContext.getUserProfileInfo(userId);
%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Edit Information</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <!-- Bootstrap -->
        <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
        <link href="styles.css" rel="stylesheet">
    </head>

    <body class="bodybg">
        <jsp:include page="/navigation.jsp"/>
        <% userInfo.next();%>

        <div class="boxouter" style="margin-top:50px;">
            <h3 class="muted">Edit Information</h3>
            <!--- more code here---->

                <br><br>
                <form id="update-form" method="" action="">
                    <table style="margin:auto">
                        <tr>
                            <!--username-->
                            <td>
                                <label>Username <span id="uname-error" class="form-error"></span></label>
                                <input type="text" title="Use at least 6 characters"
                                       name="username" id="uname"
                                       value="<%=userInfo.getString("username")%>"
                                       placeholder="Username" disabled="true">
                            </td>

                            <!--email-->
                            <td>
                                <label>Email <span id="email-error" class="form-error"></span></label>
                                <input type="text"
                                       name="email" id="email"
                                       value="<%=userInfo.getString("email")%>"
                                       placeholder="Email" disabled="true">
                            </td>
                        </tr>

                        <!--- more code here---->

                    </table>

                    <center/>
                    <button class="btn btn-info" onclick="enablefields();" id="enablebtn" style="visibility:visible">Edit Information</button>

                    <a id="savelink" href="#" style="color:white;">
                        <button class="btn btn-info" id="savebtn" type="submit" style="visibility:hidden">Save</button>
                    </a>

                    <a href="#" style="color:white">
                        <button class="btn btn-info" id="deactivatebtn" style="visibility:visible">Deactivate Account</button>
                    </a>
                </form>
            </div>
        </div>


        <br><br>

        <!--- more code here---->

    <script type="text/javascript">
        function setValues() {
            if ("<%=userInfo.getString("gender")%>" == "Male")
            $('select option:contains("Male")').prop('selected',true);

            else if ("<%=userInfo.getString("gender")%>" == "Female")
            $('select option:contains("Female")').prop('selected',true);
        }

        window.onload = setValues;

    </script>

    <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/js/bootstrap.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/js/bootstrap-modal.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/js/bootstrap-popover.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/js/bootstrap-modalmanager.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/js/editinfo.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/js/holder.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/js/logout.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/js/bootstrap-dropdown.js"></script>
</body>
</html>

Когда я запустил его, я получаю эту ошибку:

org.apache.jasper.JasperException: обработано исключение Страница JSP/editinfo.jsp в строке 61

Строка 61:

value = «<% = userInfo.getString(» электронная почта «)% > »

Я удаляю эту строку, и она отлично работает (но мне нужно это, чтобы получить значение). Когда я держу строку 61 и пытаюсь удалить это:

value = «<% = userInfo.getString(» имя пользователя «)% > »

который находится в строке 52 моей страницы, он все равно не работает.

Я также заменю строку 52 на строку 61, и она работает.

Я также получаю следующие ошибки:

javax.servlet.ServletException: java.sql.SQLException: столбец «email» не найден. java.sql.SQLException: не найден адрес электронной почты столбца.

Но я на 100% уверен, что в моей базе данных есть столбец электронной почты. Кроме того, когда я пытаюсь это сделать для других столбцов моей базы данных, он возвращает ту же ошибку. Он работает только в том случае, если это столбец «имя пользователя». Пожалуйста, помогите мне. Как это исправить?

After installing the update, confluence stopped starting. Writes error 500. confluence on our own server. windows server 2016 + MS SQL help me please

HTTP Status 500 – Internal Server Error


Type Exception Report

Message Произошла ошибка при обработке [errors.jsp] в строке [13]

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.apache.jasper.JasperException: Произошла ошибка при обработке [errors.jsp] в строке [13]

10:     <link rel="shortcut icon" href="johnson/fav-confluence.ico">
11:     <%
12:         JohnsonPageI18NProvider johnsonPageI18NProvider = (JohnsonPageI18NProvider) BootstrapUtils.getBootstrapContext().getBean("johnsonPageI18NProvider");
13:         String translations = johnsonPageI18NProvider.getTranslations().serialize();
14:     %>
15:     <script>
16:         window.i18n = <%=translations%>;


Stacktrace:
	........................conflernce.jpg

Hi Everyone,

I am a beginner in jsp and trying to validate a text field using the following code its shows the followin expection «org.apache.jasper.JasperException: An exception occurred processing JSP page /Test/chkValidation.jsp at line 10»

trialvalidation.jsp

<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*,java.util.regex.* ,java.io.*" errorPage="" 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<form name="tri" action="chkValidation.jsp" method="post">
<input type="text" name="txtId" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
chkValidation.jsp

<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*,java.util.regex.*,java.io.*" errorPage="" import= "Validations.regexFunctions" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<%
	    regexFunctions reg = new regexFunctions(); 
	
	
        String id = request.getParameter("txtId");
	    int i = reg.checkForString(id);
	
	     out.println("i : "+i);
	     out.println("id : "+id);

%>

</body>
</html>

It is showing the following error or expection to which i can’t seem to reslove

org.apache.jasper.JasperException: An exception occurred processing JSP page /Test/chkValidation.jsp at line 10

7:
8: <body>
9: <%
10: regexFunctions reg = new regexFunctions();
11:
12:
13: String id = request.getParameter(«txtId»);

Hope u will Help me out:
Hopeing for a positive reply:

Вопрос:

отчет об исключении типа

message Исключение произошло при обработке страницы JSP/login.jsp в строке 5

описание Сервер обнаружил внутреннюю ошибку, которая помешала ему выполнить этот запрос.

исключение

org.apache.jasper.JasperException: Исключение произошло при обработке страницы JSP/login.jsp в строке 5

5:     Class.forName("com.mysql.jdbc.Driver");

6: Соединение con = DriverManager.getConnection(“jdbc: mysql://localhost: 3306/test”, “root”, “harsha”);

основная причина

javax.servlet.ServletException: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Лучший ответ:

Эта ошибка возникает из-за того, что ваш драйвер JDBC не был в вашем классе.

Class.forName("com.mysql.jdbc.Driver");

В основном вы пытаетесь создать объект класса, который не загружается в JVM… Решение помещает JAR-драйвер JDBC в ваш путь к классу.

Ура!

Ответ №1

Попробуйте разместить mysql-connector-java-5.1.27-bin.jar в каталоге webapp /web-inf/lib

а затем перезапустите или передислоцируйте

Делаю учебное веб-приложение «Библиотека». Есть 2 jsp страницы: index — вход, main — главная (сюда должен выводится список авторов из БД) main.jsp

<%@ page import="app.AuthorList" %>
<%@ page import="app.Author" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Inside</title>
  <style type="text/css">
   #footer {
    position: fixed; /* Фиксированное положение */
    left: 0; bottom: 0; /* Левый нижний угол */
    padding: 10px; /* Поля вокруг текста */
    background: LightSeaGreen; /* Цвет фона */
    color: #fff; /* Цвет текста */
    width: 100%; /* Ширина слоя */
   }
  </style>
</head>
<body>
<div class="text-center">
<img src="images1.jpg" class="img-thumbnail"  alt="Responsive image">
</div>
<div class="jumbotron">
  <h1 class="text-info">Librus</h1>
  <p>You can find some books here.</p>
  <% AuthorList authorList = new AuthorList();
        for (Author author : authorList.getAuthorList()) {
        	%>
        	<li><a href="#"> <%=author.getFull_name() %></a></li>
      <% }%>  
</div>
  <div id="footer" class="text-center">
   &copy; Markus Efr
  </div>
</body>
</html>

PostgreSQL содержит бд проекта, в Glassfish настроен пул соединения и ресурс для его использования. В папку lib поместил драйвер для postresql 5b98ed8a6462a059536928.png5b98ed935d29e203060835.png Также 3 java класса Author — сущность объекта,

package app;

public class Author {

	public Author() {
		
	}
	
	private int auth_id; 
	private String full_name;
	
	public Author (int auth_id, String full_name) {
		this.auth_id=auth_id; 
		this.full_name=full_name;
	}

	public int getAuth_id() {
		return auth_id;
	}

	public void setAuth_id(int auth_id) {
		this.auth_id = auth_id;
	}

	public String getFull_name() {
		return full_name;
	}

	public void setFull_name(String full_name) {
		this.full_name = full_name;
	}
	
}

AuthorList — выполняет запрос и наполняет список сущностями из БД.

package app;
import app.Connector;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AuthorList {

	private ArrayList<Author> authorList = new ArrayList<Author>();
	
	private ArrayList<Author> getAuthors () {
		try {
			Connection con = Connector.getConnection();
		    Statement stmt = con.createStatement();
		    ResultSet rs = stmt.executeQuery("select * from author");
		    while (rs.next()) {
		    	Author author = new Author();
		    	author.setFull_name(rs.getString("full_name"));
		    	authorList.add(author);
		    }		    
		} catch (SQLException e) {
		Logger.getLogger(AuthorList.class.getName()).log(Level.SEVERE, "Error", e);
		}
		  return authorList;
	}	  

     public ArrayList<Author> getAuthorList() {
          if (!authorList.isEmpty()) {
        	  return authorList;
          } else {
        	  return getAuthors();
          }
     }  	 
     }

Connector содержит настойки для использования ресурса БД.

package app;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class Connector {

	private static Connection con;
	private static InitialContext ic;
	private static DataSource ds;
	
	public static Connection getConnection()  {
 
		try {		
    ic = new InitialContext();
    ds = (DataSource) ic.lookup("jdbc/library");
   if (con==null) {
	   con = ds.getConnection();
   }
		} catch (SQLException e) {
Logger.getLogger(AuthorList.class.getName()).log(Level.SEVERE, "Error", e);
		} catch (NamingException e) {
			Logger.getLogger(AuthorList.class.getName()).log(Level.SEVERE, "Error", e);
	}	
		return con;
  } 
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Librus</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
    <resource-ref>
    <description>JDBC Connection Pool</description>
    <res-ref-name>jdbc/library</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
  </resource-ref>
</web-app>

5b98eea8d31c1103838642.png
Буду благодарен за понимание что пошло не так. Где возник NullPoint и как его изгнать ?

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Out of memory ошибка mk 9 как исправить ошибку
  • Out of memory ошибка fallout new vegas