I can`t understand one thing when i send request to get object by name from db,
it always return me null. I surf all sites try to fix it with session and etc. Nothing to work.
Any ideas?
enter image description here
This is my Servlet class:
#WebServlet(value = "/display", name = "IndexServlet")
public class IndexServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if(!(request.getParameter("mysql")==null)) {
MySQLRepository sql = new MySQLRepository();
Headline object = sql.getByHeadline(request.getParameter("mysql"), DatabaseConnection.initDatabase());
request.setAttribute("id", object.getId());
request.setAttribute("headline", object.getHeadline());
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("out.jsp");
requestDispatcher.forward(request,response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is index.jsp:
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>MySQLSolrProject</title>
</head>
<!DOCTYPE html>
<body>
<form action="out.jsp" method="get">
<p>Headline:</p>
<label>
<input type="text" name="mysql">
</label>
<%--<br>
<p>Full text:</p>
<label>
<input type="text" name="solr">
</label>--%>
<br><br>
<input type="submit" value="Search" formmethod="get">
</form>
</body>
</html>
This is out.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Out</title>
</head>
<body>
<h2>Text is:</h2>
<table>
<tr><th>Id</th><th>Headline</th><th></th></tr>
<tr><td><%=session.getAttribute("id")%></td>
<td><%=session.getAttribute("headline")%></td>
</tr>
</table>
<p>Return to search</p>
</body>
</html>
the error was that Tomcat version 10.* didn't want to work with version 4 servlets
I downgraded Tomcat to version 9.* and it worked.
Related
This question already has an answer here:
Servlet send response to JSP
(1 answer)
Closed 3 years ago.
how do i set the jsp file as response in my servlet ?And what kind of expression do i need to use in the jsp page?
this is the form
<html>
<head>
<title>Select your Hobby</title>
</head>
<body>
<form method="POST" action="SelectHobby">
<p> Choose a Hobby:
</p>
<select name="hobby" size="1">
<option>horse skiing
<option>extreme knitting
<option>alpine scuba
<option>speed dating
</select>
<br><br>
<center>
<input type="SUBMIT">
</center>
</form>
</body>
</html>
the servlet
package com.example.web;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HobbyServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
String hobby = request.getParameter("hobby");
}
}
and this is the jsp in wich i want to see the hobby in the body
<html>
<head>
<title>These are your hobbies</title>
</head>
<body>
<%
</body>
</html>
I recomend you to read this post. JSTL will help you. I suppose you mapped your servlet. Here is a quick example:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<form method="POST" action="testservlet">
<p> Choose a Hobby:
</p>
<select name="hobby" size="1">
<option>horse skiing
<option>extreme knitting
<option>alpine scuba
<option>speed dating
</select>
<br><br>
<center>
<input type="SUBMIT">
</center>
</form>
</body>
</html>
The servlet:
#WebServlet(name = "test", urlPatterns = { "/testservlet" })
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String hobby = request.getParameter("hobby");
request.setAttribute("theHobby", hobby);
request.getRequestDispatcher("hobbypage.jsp").forward(request, response);
}
I defined an attribute called theHobby to hold the value from the selected hobby in the first page. I also created a page called hobbypage.jsp where I want to send the value to.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Hobby: ${theHobby}
</body>
</html>
With JSTL you can call the attribute through the name you defined like this ${nameOfAttribute}.
I can't get the checkbox value of "no_del_file" into the servlet.
here is my JSP:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>List of Command menu</title>
</head>
<body>
<div><b>${reply}</b></div>
<div id="wrapper">
<div id="menu">
<form action="runButtonCommand" method="post" name="myform">
<a href="runButtonCommand?param1=list apps" >List1</a><br/><br/>
<a href="runButtonCommand?param1=list data" >List2</a><br/><br/>
<br/><br/>
no del:
<%String test = (String)request.getParameter("no_del_file"); %>
<%String checked = "";%>
<%
if ("on".equals(test)) {
checked="checked=\"on\"";
} %>
<input type="checkbox" name="no_del_file" <%=checked%>>
<br />
</form>
</div>
<div id="output">
<p>Output:</p>
<textarea style="resize: none;" data-role="none" rows="40" cols="120" name="outputarea">
${data}
</textarea>
</div>
</div>
</body>
</html>
And here is the Servlet part where I try to get the checkbox value:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String[] tester= request.getParameterValues("no_del_file");
System.out.println("Start: "+tester);
performTask(request, response);
}
However it doesn't matter if I use getParameterValues, getParameter or getAttribute I always get null if checked or unchecked. How can I get that value?
Thanks for your help.
Viking
It calls Servlet by click a href.
<li >privilegeManagement</li>
this code is include in the navigation.jsp which is included in the main.jsp.
then it's my servlet.
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
ProviderDao pd = new ProviderDao();
List<ProviderArchives> list = pd.getArchives();
String str = "chenfeng";
req.setAttribute("list", list);
req.setAttribute("hu" , str);
getServletContext().getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
}
then it's my main.jsp.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#page import="java.util.*"%>
<%#page import="com.chenfeng.javabean.ProviderArchives"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>main</title>
</head>
<body>
<%# include file="navigation.jsp"%>
<div>
<%# include file="management.jsp"%>
</div>
<div>
<%
String k = (String)request.getAttribute("hu");
out.println(k);
%>
<c:forEach items="${list}" var="item">
<tr>
<td>${item.provideID() }</td>
<td>${item.GID }</td>
<td>${item.Gname }</td>
<td>${item.PID }</td>
<td>${item.TEL }</td>
<td>${item.ADDR }</td>
<td>
Modify
Delete
</td>
</tr>
</c:forEach>
</div>
</body>
</html>
then when I run this on server,it shows like this
thank in advance for any help!
Actually,there is no reason for this code.But the eclipse run into problem.The real problem log output after I delete class file in build directory and build it again.
It's quite clear. You set attribute of Request Object while you're forwarding Servlet Context Object.
Instead of:
getServletContext().getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
Write:
req.getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
Try to figure out when I load my jsp page the error message is shown even if I do not submit the button. Can anyone advice how to show error message after submit the button. I post my code here for control.
Thanks in advance
LoginController
#Controller
//#RequestMapping("/")
public class LoginController {
#Autowired
private LoginService loginServiceImpl;
#RequestMapping(value="/login", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView validUser(#ModelAttribute("person") PersonModel personModel) {
ModelAndView model= new ModelAndView("login");
try
{
boolean validUser = loginServiceImpl.isValidUser(personModel.getName(), personModel.getPassword());
//Zjistí zda-li je user přihlášen
if(validUser)
{
System.out.println("User Login Successful");
model.addObject("successMessage", personModel.getName());
}
else
{
System.out.println("Login wasn't Successful");
model.addObject("unsuccessmessage", "Invalid credentials!!");
}
}
catch(Exception e)
{
e.printStackTrace();
}
return model;
}
}
JSP Page
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form:form id="loginForm" method="post" action="login" modelAttribute="person">
<form:label path="name">Login name:</form:label>
<form:input id="name" name="name" path="name" /><br>
<form:label path="password">Password</form:label>
<form:password id="password" name="password" path="password" /><br>
<input type="submit" value="Submit" />
<h2>${unsuccessMessage}</h2>
<h2>${successMessage}</h2>
</form:form>
</body>
</html>
I have two jsps. One is login_first.jsp, another one is main.jsp. After submit in login_first.jsp, I call main.jsp. It works fine.
I have logout button in main.jsp which sends control back to login_first.jsp. it executes login_first.jsp but page is not loading.
Please help.
login_first.jsp
<%# page session="false" %>
<%
try {
HttpSession session = request.getSession(true);
if ("Submit".equals(request.getParameter("SubmitButton"))) {
session.setAttribute("userLoggedIn", "true");
response.sendRedirect("main.jsp");
return;
} else {
session.setAttribute("userLoggedIn", "false");
session.invalidate();
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<body>
<form name="loginForm" method="post">
<table>
<tr>
<td><input type="submit" name="SubmitButton" value="Submit" class=button/></td>
</tr>
</table>
</form>
</body>
<%
} catch (Exception e) {
e.printStackTrace();
response.sendRedirect("login_first.jsp");
return;
}
%>
</html>
main.jsp
<%# page session="false" %>
<%
try {
HttpSession session = request.getSession(false);
if (session != null && "true".equals(session.getAttribute("userLoggedIn"))
&& !"Logout".equalsIgnoreCase(request.getParameter("logout"))) {
// do work
} else {
if (session != null) {
session.setAttribute("userLoggedIn", "false");
}
response.sendRedirect("login_first.jsp");
return;
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<body>
<form name="creditCardForm" target="formresponse" autocomplete="off" method="post">
<table width="50%" border=0 cellpadding=3 cellspacing=1>
<tr>
<td>
<div align="right">
<input name="logout" type="submit" class=button value="Logout">
</div>
</td>
</tr>
</table>
<iframe name="formresponse" width="0" height="0" style="visibility:hidden"></iframe>
</form>
</body>
<%
} catch (Exception e) {
e.printStackTrace();
response.sendRedirect("login_first.jsp");
return;
}
%>
</html>
First off, both pages have 'session=false' set but you're trying to get/set attributes in Session. Are you sure it's working at all as intended?
Second, you can only call response.sendRedirect() before any data was sent back to the client (before buffer flushed). Are you sure it's happening in your case?
Although scriptlets are outdated, I believe you should check against the documentation on where your JSP files are located and if you need to use a leading / on your redirect URLs; e.g. /first_login.jsp instead of first_login.jsp.
I just found that the target="formresponse" in main.jsp gives problem. So I have moved this logout to a separate form and added action.
But the same sendRedirect is working from first_login.jsp. From
main.jsp to login_first.jsp is not working.
One reason could be that your main.jsp is in some subfolder.