I have the following servlet:
#WebServlet(name = "Placeholder",urlPatterns = {"/foo"})
public class Placeholder extends HttpServlet {
public static int numbers=5;
HttpSession session;
public void doGet (HttpServletRequest _req, HttpServletResponse _res) throws ServletException, IOException {
/* Refresh session attributes */
session = _req.getSession();
session.setAttribute("wee","ok");
}
}
With the following JSP:
<%#page language="java" contentType="text/html"%>
<%#page import="java.util.*, java.io.*"%>
<%#page import="main.java.Placeholder.*" %>
<html>
<body>
<b><% out.println("wee, printing from java");%></b>
<% out.println("<br/>Your IP address is " + request.getRemoteAddr());
String value = (String) session.getAttribute("wee");
out.println(value);%>
</body>
</html>
I'm surely missing the point somewhere as attribute wee is resolved as null, first time I load the page. If I go to /foo I get empty an page, and after I get back and reload the root page of servlet, wee actually gets its value.
My goal here is to simply print variables from the servlet into the view, no routing needed. Not sure that urlPatterns are needed here, but it does not work for now without this little hack.
UPD. Ok, so I've figured out that whatever route I put in, I need to add some characters in browser, get back and reload the page.
So, the root is 0.0.0.0:8080/webapp
I need to access,say 0.0.0.0:8080/webapp/qwerty , get back to /webapp and refresh the page.
How do I get session instantiated by just going to /webapp?
Why don't I have 404 or 500 on accessing some random unexisting route /webapp/randomstuff?
First configure servlet as welcome file in web.xml. If web.xml not present than create it manually inside WEB-INF folder and put below content inside it.
<welcome-file-list>
<welcome-file>foo</welcome-file>
</welcome-file-list>
than in your servlet dispatch request to your jsp lets say your jsp name is index.jsp than your servlet code would be look like:
#WebServlet(name = "Placeholder",urlPatterns = {"/foo"})
public class Placeholder extends HttpServlet {
public static int numbers=5;
public void doGet (HttpServletRequest _req, HttpServletResponse _res) throws ServletException, IOException {
HttpSession session = _req.getSession();
session.setAttribute("wee","ok");
_res.sendRedirect("index.jsp");
}
}
Now run your servlet you will see output.
Hope this solve your problem!!!
Related
I am trying to develop a webapplication (with Jsp & Servlets) and deploy in tomcat. After successfully deployed, I can access only JSP pages but not Servlets. I have tried in both the ways : given a link with reference to the (Relative and absolute) pah of the Servlet and given the URL directly in the browser address bar. Please help me out.
index.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>home</title>
</head>
<body>
<h2>Welcome</h2>
Click here to ServletDemo_01.<br><br>
</body>
</html>
ServletDemo_01.java
package com.ignite.servlet;
import java.io.IOException;
import java.io.PrintWriter;
#javax.servlet.annotation.WebServlet(name = "ServletDemo_01")
public class ServletDemo_01 extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Hello");
out.close();
}
}
Note : I didn't update any thing in the default web.xml, since I am using WebServlet annotation.
I have updated annotation as below, then it's solved.
#javax.servlet.annotation.WebServlet(name = "ServletDemo_01", urlPatterns = "/ServletDemo_01")
I just started using JSP and Servlet, so I encountered a really basic problem.
I'm trying to make a request from JSP to servlet, where I set a parameter and then forward the answer from servlet back to the jsp.
Here is the code from my JSP:
<% String s = (String)request.getAttribute("name");
out.println(s);
%>
Here is my code from servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try (PrintWriter out = response.getWriter()) {
request.setAttribute("name", new String("aa"));
this.getServletContext().getRequestDispatcher("/index.jsp").forward(request,response);
}
}
So in the end, the servlet has the value, but my jsp doesn't.
Here you have already declared a String type but you cast it as String also, this is redundant.
<% String s = (String)request.getAttribute("name");
out.println(s);
%>
Also, there's a difference between <%= %> and <% %>. If you want to output the variable into your jsp use the one with the equals (<%= %>). The second line of your scriptlet code would also generate an error. The code you write in your servlet doesn't just continue on the JSP, it's not how it works.
if you want to output the name attribute just do this:
<%= request.getAttribute("name") %>
However since 2010 scriptlets are discouraged (outdated technology).. We use EL and JSTL instead. You should be able to just output the variable like this:
${name}
In your Servlet all you need to do is this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = "Jane"; //create a string
request.setAttribute("name", name); //set it to the request
RequestDispatcher rs = request.getRequestDispatcher("index.jsp"); //the page you want to send your value
rs.forward(request,response); //forward it
}
EDIT
You asked,
Is there a way to trigger the servlet let s say on a click of a button
or something like that?
Yes, there are multiple ways to do it and it really depends on how you want it setup. An easy way to trigger the servlet on a button click is like this. *(Assuming you have a servlet mapped onto /Testing):
<a href="/Testing">Trigger Servlet<a>
Another way could be with a form:
<form action="Testing" method="get">
<input type="hidden" name="someParameterName" value="you can send values like this">
<button type="submit">Do some magic</button>
</form>
There's also AJAX (which involves javascript). But this is fairly advanced and i don't recommend doing it until you are familiar with normal synchronous http behaviour.
Try without a writer, you don't want two writing contexts to a single response. You are also not using it:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("name", new String("aa"));
this.getServletContext().getRequestDispatcher("/index.jsp").forward(request,response);
}
I think you should call the request dispatcher method using request object. This is how you do it :
RequestDispatcher rs = request.getRequestDispatcher("index.jsp");
rs.forward(request,response);
We have a jsp (2.2)/jstl(2.1) form that submits to a java servlet (3.0) on tomcat 7 server. Randomly, intermittently we will get a submission to the servlet with all the http request parameter values as null. Our form has some fields that are pre-populated so we expect at least those to be retrievable but they are null at the serlvet as well. Almost all of the form submissions we receive contain form data and are successfully processed. It's the once in every so many submissions that has the completely empty http request parameter set that I cannot figure out nor reproduce. There are no file uploads involved, the data is submitted via post. We validate client side and server side. I have searched high and low for reasons why the form data can be empty but have not had any success. Any thoughts?
1) no file uploads
2) all fields have 'name='
3) method is post
4) data is validated prior to submission
5) implement a filter for db entity management
partial jsp form:
<%# page contentType="text/html; charset=UTF-8" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
response.setHeader("Cache-Control", "no-cache");//Forces caches to obtain a new copy of the page from the origin server
response.setHeader("Cache-Control", "no-store");//Directs caches not to store the page under any circumstance
response.setDateHeader("Expires", 0);//Causes the proxy cache to see the page as "stale"
response.setHeader("Pragma", "no-cache");//HTTP 1.0 backward enter code here
%>
<!DOCTYPE html>
<!--head/body stuff -->
<form id="app_form" name="app_form" action="process" method="post" novalidate="novalidate" accept-charset="ISO-8859-1">
<!-- general form fields using html/jstl -->
<button type="submit" id="submit_application" name="submit_application" class="submit application submitbtn" title="I'm finished and want to submit my completed application.">SUBMIT APPLICATION</button>
</form>
partial filter:
public class EntityManagerFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
log.debug("Initializing filter...");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
EntityManagerUtil.getEntityManager().getTransaction().begin();
chain.doFilter(request, response);
EntityManagerUtil.getEntityManager().getTransaction().commit();
} catch (Throwable ex) {
}
partial java servlet:
public class ProcessApplicationFormServlet extends BaseServlet {
private static Logger log = Logger.getLogger(ProcessApplicationFormServlet.class);
private static final long serialVersionUID = 1L;
Application_Domestic appdata = null;
Domestic_user currentUser = null;
String sessID = null;
String program = null;
String type = null;
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
//values from form
appdata.setTitle(maxLength(req.getParameter("title"),25));
appdata.setFirst(maxLength(req.getParameter("first"),30));
appdata.setMiddle(maxLength(req.getParameter("middle"),30));
appdata.setLast(maxLength(req.getParameter("last"),57));
appdata.setSuffix(maxLength(req.getParameter("suffix"),25));
appdata.setEmail_Address(maxLength(req.getParameter("trueemail"),50));
etc...
process data
}
}
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
These are just the portions that deal with submission/http request. If there are other important coding considerations that I need to show, please let me know. Do keep in mind that only 1 - 2 percent of the form submissions come in with empty httpServletRequest data. This code has been tested and working. I just cannot seem to be able to reproduce the scenario when a user submits the form (it can not be submitted until all data as been validated) and it reaches the servlet with an empty data set where every parameter is null.
I have recently been thrown into the wonderful world of programming websites with Java. I have a little experience with Java but would still consider myself a beginner.
I have created a Java class that has a simple SQL query in it. I am trying to display onto a JSP page but am unsure on how to achieve this.
Here is my Java class called Main.java:
public static void main(String[] args) throws Exception {
//Accessing driver from JAR
Class.forName("com.mysql.jdbc.Driver");
//Creating a variable for the connection called "con"
//jdbc:mysql://host_name:port/dbname
//Driver name = com.mysql.jdbc.Driver
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
PreparedStatement statement = con.prepareStatement("select name from user");
ResultSet result = statement.executeQuery();
while(result.next()) {
System.out.println(result.getString(1));
}
}
How would I get system.out.println on a JSP page?
If you need to save results and display to JSP .
save the results in request and in view layer iterate using JSTL to display the result.
which means , in servlet get the request and forward it new jsp
I recommend to use JSF instead JSP ,
JSP also allows you to write blocks of Java code inside the JSP. You do this by placing your Java code between <% and %> characters.
A scriptlet contains Java code that is executed every time the JSP is invoked.
Here is a link to simple jsp web app that should help you to get started.
http://j2ee.masslight.com/Chapter1.html#mygreeting
you could use below sample code as a reference.
JSP page
<form action="servlet1" method="get">
<% ModelClass class = new ModelClass();
class.connectDb();
class.performDBoperations();
%>
<table><tr><td>
<%
class.id;
%>
</form>
Model Class:
class ModelClass {
int id;
public static void connectDb() {
dbConnection code
}
public void performDBoperations() {
get info from table with SQL thru JDBC.
id=update it;
}
A basic concept in web programming is that you don't start actions from a method (main or any other). Someone request's a JSP or servlet and the corresponding class answers. You can do both things in a JSP and leave the work of connecting to a database to an auxiliar class as #chaitanya10 answer shows.
The Nebeans tutorial for JSP's is not a bad starting point. There are several JSP/Servlets tutorial in the web, but I'd recommend to stay away from the Java EE tutorials.
For the example you post, what you need to do is program a servlet, in that servlet you would have your business logic calls (in this case the data base query), after getting the data, you have to pass it to the JSP page. With servlets there is no need for main method, but they must be deployed in a servlet container (like Tomcat).
Here is the code:
public class UserListServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Accessing driver from JAR
Class.forName("com.mysql.jdbc.Driver");
//Creating a variable for the connection called "con"
//jdbc:mysql://host_name:port/dbname
//Driver name = com.mysql.jdbc.Driver
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
PreparedStatement statement = con.prepareStatement("select name from user");
ResultSet result = statement.executeQuery();
//creates a list with the user names
List<String> userList = new ArrayList<String>();
while(result.next()) {
userList.add(result.getString(1));
}
//passing the data to the JSP
request.setAttribute("users", userList);
getServletContext().getRequestDispatcher("/user_list.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
Now in the JSP you could have something like this:
<%# page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import="java.util.List" %>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User List</title>
</head>
<body>
<%
if (request.getAttribute("userList") != null) {
List<String> users = request.getAttribute("userList");
%>
<h1>Users: </h1>
<table>
<tr>
<td>Name<</td>
</tr>
<% for (String name : users) {%>
<tr>
<td><%= name%></td>
</tr>
<% }
}%>
</table>
</body>
</html>
You can improve this example by using JSTL instead of Scriptlets (<% ... %>).
Are you sure that is this good way to create java websites?
Ask google for Java EE, Servlets and get into it.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to pass an Object from the servlet to the calling JSP
How can I pass object from servlet to JSP?
I have used the following code in the servlet side
request.setAttribute("ID", "MyID");
request.setAttribute("Name", "MyName");
RequestDispatcher dispatcher = request.getRequestDispatcher("MangeNotifications.jsp");
if (dispatcher != null){
dispatcher.forward(request, response);
}
and this code in JSP side
<td><%out.println(request.getAttribute("ID"));%> </td>
<td><%out.println(request.getAttribute("Name"));%> </td>
I get null results in the JSP Page
I think servlet's service (doGet/doPost) method is not requested. In order to access request attributes in JSPs, you must request the servlet via url-pattern and that way you don't have to use session.
SampleServlet.java
#WebServlet(name = "SampleServlet", urlPatterns = {"/sample"})
public class SampleServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("ID", "MyID");
request.setAttribute("Name", "MyName");
RequestDispatcher dispatcher = request
.getRequestDispatcher("/MangeNotifications.jsp");
if (dispatcher != null){
dispatcher.forward(request, response);
}
}
}
MangeNotifications.jsp (I presume that this file is located at root of web-context)
<br/>ID : ${ID} Or scriptlets <%-- <%=request.getAttribute("ID")%> --%>
<br/>ID : ${Name}
Now open the browser and set request url somersetting like this,
http://localhost:8084/your_context/sample
Put it in the session (session.setAttribute("foo", bar);) or in the request; then it is accessible from the JSP through the name you gave it ("foo" in my example).
EDIT :
Use simply <%= ID %> and <%= Name %> instead of <%out.println.....%>. Note the = at the beginning of the java tag, indicating to output the result of the expression.