|
geniusis 1 / 1 / 0 Регистрация: 12.06.2019 Сообщений: 7 |
||||||||
|
1 |
||||||||
|
11.11.2020, 02:48. Показов 1030. Ответов 2 Метки jsp, sql, tomcat (Все метки)
Добрый день, ошибка в передачи атрибутов в jsp странницу((
И сама ошибка Кликните здесь для просмотра всего текста 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] An error occurred at line: [18] in the jsp file: [/view.jsp] Stacktrace: Долблюсь уже 2 дня, не понимаю в чем ошибка(
__________________
0 |
|
3636 / 2968 / 918 Регистрация: 05.07.2013 Сообщений: 14,220 |
|
|
11.11.2020, 08:57 |
2 |
|
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»); Stacktrace: java.lang.NullPointerException Добавлено через 26 минут
Нужно было эту строчку воткнуть ((
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:
........................
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">
© Markus Efr
</div>
</body>
</html>
PostgreSQL содержит бд проекта, в Glassfish настроен пул соединения и ресурс для его использования. В папку lib поместил драйвер для postresql 
Также 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>

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