I have been practicing java Servlets. Can I set urlPattern from database?
#WebServlet(name = "PatternServlet", urlPatterns = "/pattern")
The following servlet creates html pages getting information from postgres, so content is dynamic. However url address is remaining same each time.
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 java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
#WebServlet(name = "PatternServlet", urlPatterns = "/pattern")
public class PatternServlet extends HttpServlet {
String title;
String content;
List<String> headerItems;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
initializeFields();
//Dynamically creates pages with a given information
PageMaker pageMaker = new PageMaker(title, headerItems, out);
pageMaker.setContent(content);
pageMaker.makePage();
}
public void initializeFields(){
//initializes field from database
}
}
Can I do something to solve this issue? Thank you!
I hope I understand your question correctly. First the urlPatterns are static once the servlet is created. You can use some fancy stuff to give it a name when it starts, but this cannot be changed once set.
But you can use wildcards
#WebServlet(urlPatterns = "/dbcontent/*")
call your servlet with
http://yourserver/dbcontent/dbRef
and then
#Post
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pathInfo = request.getPathInfo();
String[] pathElements = pathInfo.split("/");
// get last item (or whatever one you need)
String dbRef = pathInfo[pathInfo.lenth -1];
// check input. User could have tampered url
// do your stuff with dbRef
}
I did not test the code and there are better ways to fetch the dbRef you need, but I hope this illustrates how you can use a servlet to fetch stuff from a database.
Related
I'm running Apache Tomcat 8 on Eclipse Mars on Windows 7, and here's my piece of code:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Main")
public class Main extends HttpServlet {
private static final long serialVersionUID = 1L;
public Main() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("");
pw.println("");
pw.println("");
pw.println("<h1>Example 0</h1>");
pw.println("");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
It starts tomcat, ok, and "Example 0" can be seen when I access localhost. BUT, if I change the string in the response to "Example 1", it takes around 10 min to change it. I'm a beginner in Servlet / Tomcat development, and I'm failing to grasp the reason why the delay occurs. Why that happens??
Not an answer, but I recommend you code web stuffs with Netbeans, there is no doubt Eclipse is the king, but Netbeans does web stuffs better.
I am trying to create a small registeration form using jsp and servlet.
The concept goes like this:
The data being enterd in the jsp form will be checked for duplication by a servlet program.
If duplication exists , then the control must return back to the registeration (jsp) page from where the servlet was called.
I am doing this in eclipse helios.
Servlet program is under the default package under java resources ,
and jsp file is under the web content folder.
My problem is that
I am able to redirect from jsp to servlet;
but when I try to return back to the jsp page from the servlet ,
tomcat server is showing error like:
HTTP Status 404 - /RservletEs/registeration.jsp
type Status report
message /RservletEs/reg.jsp
description The requested resource is not available.
I tried both request.dispatcher() and response.sendRedirect() both are showing same error.
The file path is:
RservletEs/src/ServletCheck
Rservlets/Web Content/registeration.jsp
I have attached the source code below
somebody pls help me out of this
import java.io.IOException;
import java.io.PrintWriter;
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 org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.collect.ImmutableMap;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import java.util.Map;
import com.google.gson.Gson;
/**
* Servlet implementation class ServletCheck
*/
#WebServlet("/ServletCheck")
public class ServletCheck extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
* /
public ServletCheck() {
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
String clusterName="asdf";
String hostName="localcost";
String index="testdb";
String type="emp_type";
String field="emailId";
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int portNumber=26101;
final TransportClient client = new TransportClient(ImmutableSettings.settingsBuilder().put("cluster.name", clusterName)
.put("client.transport.sniff", true).build());
Settings settings = client.settings();
out.println("**settings:"+ settings);
ImmutableMap<String, String> map = settings.getAsMap();
out.println("**map::"+ map);
((TransportClient) client).addTransportAddress(new InetSocketTransportAddress(hostName, portNumber));
out.println("ES client:" + client);
String firstName=request.getParameter("firstName");
String lastName=request.getParameter("lastName");
String emailId=request.getParameter("emailId");
String age=request.getParameter("age");
String dob=request.getParameter("dob");
String eId=request.getParameter("employeeId");
String value=emailId;
SearchResponse response2 = client.prepareSearch(index)
.setTypes(type)
.setSearchType(SearchType.QUERY_AND_FETCH)
.setQuery(QueryBuilders.termQuery(field, value))
.setFrom(0).setSize(60).setExplain(true).setRouting("1")
.execute()
.actionGet();
SearchHit[] results = response2.getHits().getHits();
int length=results.length;
int i=0;
if (length>0){
response.sendRedirect(request.getContextPath()+"/registeration.jsp");
//request.getRequestDispatcher("/registeration.jsp").forward(request, response);
}
else{
out.println("setting the values");
hr_employee tweet = new hr_employee();
out.println("setting the id");
tweet.setEmployeeId(eId);
tweet.setFirstName(firstName);
out.println("setting the last name");
tweet.setLastName(lastName);
tweet.setEmailId(emailId);
tweet.setDob(dob);
String str=tweet.getEmployeeId();
/* System.out.println("the id is...."+str);
System.out.println("the firstname .... "+tweet.getFirstName());
System.out.println("teh last name....."+tweet.getLastName());
*/
out.println("initiallizing req builder");
final IndexRequestBuilder builder = client.prepareIndex(index, type,str);
out.println("setting source");
builder.setSource(new Gson().toJson(tweet));
out.println("getting response");
final IndexResponse response3 = builder.setRouting("1").execute().actionGet();
out.println("geting connected...");
out.println("ElasticSearchEJBBean:indexDocument:" + index+ ":" + type+ ":" + str + ":index results:" + response3);
response.sendRedirect(request.getContextPath()+"/ServletInsert");
}
}
/**
* #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);
}
}
sounds like there must be some problem with the way u name it.
Try like this:
right click on ur jsp file and select copy qualified name .
then use that name to redirect or dispatch like this:
request.getRequestDispatcher("/registeration .jsp").forward(request,response);
Since jsp is under the web-content folder do this
response.sendRedirect("/registeration.jsp");
or try something like this
response.sendRedirect(request.getSession().getServletContext().getRealPath("/registeration.jsp"));
I am currently trying to complete a login system using jsp and servlets.I have my register and login validation working.
I wish to link to a welcome page following login to display the user profile information.
I had, just for testing purposes, a response.sendRedirect(welcome.jsp) which redirected following a successful login by the login servlet.
Now, to display the profile info on this welcome page I was going to use a servlet to gather the info from the database and render it to the the browser using a printwriter.
How do I call this servlet successfully from the loginservlet to run the doPost() method?
Or is there a better way of doing it?
Thank you for your time.
(For simplicity, I was just trying to get a basic webpage to appear first to make sure this was working I will have no problem with the database side of things once I get this going)
LOGIN SERVLET:
package logon;
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 javax.servlet.http.HttpSession;
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
System.out.println("In the Login Servlet");
User user = new User();
user.setEmail(request.getParameter("email"));
user.setPassword(request.getParameter("password"));
LoginDAO.login(user);
if(user.isValid())
{
HttpSession session = request.getSession(true);
session.setAttribute("currentSessionUser",user);
session.setAttribute("currentSessionUserEmail", user.getEmail());
response.sendRedirect("WelcomeServlet");
}else
response.sendRedirect("LoginFailure.html");
} catch (Throwable exc)
{
System.out.println(exc);
}
}
}
WELCOME SERVLET:
package logon;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public WelcomeServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.print("<html>"+"<head>"+"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">");
out.print("<title>Welcome</title>");
out.print("</head>"+"<body>");
out.print("Welcome to the welcome page!!!");
out.print("</body>"+"</html>");
}
}
You can't redirect using POST, only using GET. Since you're just displaying HTML in WelcomeServlet move the code from doPost to doGet, or make the one call the other, which simply makes them both do the same thing.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
Also, it would be better to use a JSP than to out.print a bunch of HTML inside a servlet. See the info page for servlets.
Plus, obviously your welcome page needs to read the attribute currentSessionUser from the session and make sure its not null to see if the user is really logged in or not. Otherwise if a user knows the address of the welcome page they can just bypass your login check as you have it now.
Your problem is that you have currently implemented your Servlet to respond to the wrong HTTP verb.
You'll notice that the servlet has as doPost and a doGet method. As you might expect these map onto HTTP GET and HTTP POST requests. Your current problem stems from the fact that you have implemented the doPost method in your WelcomeServlet therefore expecting a POST request, when it will actually be serving a GET request.
Speaking very crudely, you can think of GET requests as read operations and POST requests as write operations. So when you submit a form to save some data, this is typically handled a POST request. You are basically asking to write data to a database or session. When you load a web page, this is typically handled as a GET request. You are simply asking to read the data.
Again simplifying, but re-directs are typically GET requests. Therefore your Servlet will need to implement the doGet() method to respond to the browsers GET request after it is re-directed.
I like to run a servlet on a tomcat server but it gives the error as above.Also when i put ajax request on the servlet it did not working through index.jsp.Please help me friends.
also explain briefly because I am at the starting level of servlet.
import java.sql.Connection;
java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.Driver;
import java.util.Arrays;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySQLAccess extends HttpServlet
{
public void getRows(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException
{
String a="";
PrintWriter out = response.getWriter();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sankar?" + "user=root");
Statement statement = connection.createStatement();
ResultSet resultSet = statement
.executeQuery("SELECT * FROM sankar.datas");
a=resultSet.getString("name");
}
catch (Exception e)
{
e.printStackTrace();
}
out.println(a);
}
}
In order to accept the GET request, you need to override the doGet method in your MySQLAccess servlet class. Considering the code, you may just have to replace the name of your getRows method to doGet. From javadocs
HttpServlet class provides an abstract class to be subclassed to
create an HTTP servlet suitable for a Web site. A subclass of
HttpServlet must override at least one method, usually one of these:
doGet, if the servlet supports HTTP GET requests
doPost, for HTTP POST requests
doPut, for HTTP PUT requests
doDelete, for HTTP DELETE requests
You need the doGet-Method like so:
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// your code
}
This method is called from the server (tomcat container more specifically) when a GET request is sent to the servlet.
If you wish to use POST you need to implement the doPost(...)method, btw.
I need to make a "text" file available on my site so that a partner can read the data daily. I'd like this "text" file to be generated dynamically. We use JSPs and Java Servlets for of our pages
Is there a way to dynamically generate a text file dynamically to be downloaded when the user visits my JSP or a Java Servlet url?
I have tried using a JSP without any html in it. It does put some text on the page, but I can't seem to include line breaks in the output so I think it may be better to just serve it as a file to be downloaded.
To generate some text and download it, you can use something like this:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet( name = "TextOutputServlet", urlPatterns = { "/servlets/giveMeSomeText" } )
public class TextOutputServlet extends HttpServlet {
protected void processRequest( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
response.setContentType( "text/plain;charset=UTF-8" );
response.setHeader( "Content-Disposition", "attachment;filename=MyTextFile.txt" );
PrintWriter out = response.getWriter();
try {
out.println( "Some content..." );
out.println( "Some more..." );
} finally {
out.close();
}
}
#Override
protected void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
processRequest( request, response );
}
#Override
protected void doPost( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
processRequest( request, response );
}
}