I was trying this small HttpSession program as a demo for my project.
This program just checks whether the user is new, if it is then displays a form, if the user is not new, then it displays the name of the user, the color he selected and the total no. of visits.
When i run my program, it works only for the first time. That means when i run another instance of my program, it displays a blank web page.
What is wrong in the code that is causing this problem???
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;
import javax.servlet.http.HttpSession;
public class SessionServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Integer hitCount;
HttpSession s = request.getSession(true);
if(s.isNew()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet SessionServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<form method=get action=SessionServlet>");
out.println("<h3>Please sleect a Color</h3>");
out.println("<input type=radio name=color />Red");
out.println("<br /><input type=radio name=color />Green");
out.println("<br /><input type=text name=txtName />");
out.println("<br /><input type=submit name=Submit value=Submit />");
out.println("</form>");
out.println("</body>");
out.println("</html>");
} else if(!s.isNew()){
String name = (String) request.getParameter("txtName");
String color = (String) request.getParameter("color");
hitCount = new Integer(1);
s.setAttribute("Name", name);
s.setAttribute("color", color);
s.setAttribute("HitCount", hitCount);
if((name != null) && (color != null)) {
out.println("Name: " + s.getAttribute("Name"));
hitCount = (Integer)s.getAttribute("HitCount");
hitCount = hitCount++;
s.setAttribute("HitCount", hitCount);
//out.println("<body bgcolor=" + s.getAttribute("color") + ">");
out.println("you selected" + s.getAttribute("color"));
out.println("Total visits=====>" + s.getAttribute("HitCount"));
}
}
}
}
}
The second time you run this code, the session already exists, so the program goes through else branch- but the "old" request object (from the first run of the application) and its parameters (color and name) are already gone at that time. Request is destroyed by container right after the response from the first application run was sent back to the client.
In your code
String name = (String) request.getParameter("txtName");
String color = (String) request.getParameter("color");
you are trying to get non existing parameters. Parameters txtName and color do not exist in request anymore. Therefore they are null and the next condition
if((name != null) && (color != null))
is always false. And nothing is written into out Writer.
What you should do in order to make this work is to read the parameters from the session object (this is what the sessions are made for anyway) where you should put them in the first application run. This code won't work. And your hitCount will always be 1 (please see HttpSessionListener interface). This code is wrong on so many levels- you should re-write everything after the else if branch which should be only else anyway.
TLDR:
Your question was why it is not working: the answer is - you are reading non existing parameters. You have to put the parameters into session object in the first application run and read them from it.
edit after your question from December 31st:
Here is what I would do. Assume following directory structure of this simple project named SessionServlet. This structure will be used in whole answer. To simplify things I won't list every directory, you surely get the idea from this. This is not the real-life example of directory structure, it is simplified for the purposes of this tutorial example.
<path-to-project>/SessionServlet/src/com/example/session
<path-to-project>/SessionServlet/WebContent/META-INF
<path-to-project>/SessionServlet/WebContent/WEB-INF
Create an html file, for example start.html. It should contain the input fields which values you need to store in the session. The file goes here
<path-to-project>/SessionServlet/WebContent/start.html
Its contents
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Start page</title>
</head>
<body>
<form method="get" action="MySessionServlet">
<h3>Please select a Color</h3>
<input type="radio" name="color" value="red" />Red<br>
<input type="radio" name="color" value="green" />Green<br>
<input type="text" name="txtName" /><br>
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
In your servlet example you forgot the value attribute in radiobutton input, therefore whichever radiobutton you would check, the value would be on, not the color name.
Next you have to create the servlet class SessionServlet.java, which will be slightly different from your original idea. It goes here:
<path-to-project>/SessionServlet/src/com/example/session/SessionServlet.java
Its contents
package com.example.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionServlet extends HttpServlet {
private static final long serialVersionUID = -3808675281434686897L;
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String requestColor = null;
String requestTxtName = null;
PrintWriter out = response.getWriter();
MySessionListener listener = new MySessionListener();
HttpSession session = request.getSession();
if (session.isNew()) {
//these are request parameters sent from html form
requestColor = request.getParameter("color");
requestTxtName = request.getParameter("txtName");
//save the attributes in session in order to use them later
session.setAttribute("sessionColor", requestColor);
session.setAttribute("sessionTxtName", requestTxtName);
}
else {
//get the previously stored attributes from session
String color = (String) session.getAttribute("sessionColor");
String name = (String) session.getAttribute("sessionTxtName");
//session info
out.println("session already existed");
if (color != null && name != null) {
out.println("Name: " + name);
out.println("Color: " + color);
out.println("Session count: " + listener.getSessionCount());
}
}
}
}
I think the servlet's code is pretty much self-explanatory. However, if you have any particular questions, please ask.
In order to count the active sessions, you need to create a SessionListener class and count the sessions. For the purposes of this example I put the class into the same directory as servlet class. Please do not do this in real project. You'd create a big mess. This is only simplified Java Enterprise Hello world example. The file is here
<path-to-project>/SessionServlet/src/com/example/session/MySessionListener.java
Its contents are
package com.example.session;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements HttpSessionListener {
private static int sessionCount;
#Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("Creating session with id: " + se.getSession().getId());
sessionCount++;
}
#Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Destroying session id: " + se.getSession().getId());
sessionCount--;
}
public int getSessionCount() {
return sessionCount;
}
}
The listener class for counting active sessions must implement HttpSessionListener interface. We call the method getSessionCount() in SessionServlet class as you already noticed.
The last thing to do is to create a deployment descriptor xml in order to tell the container what to do with those classes we created.
the file must be named web.xml and it must be placed in WEB-INF directory.
<path-to-project>/SessionServlet/WebContent/WEB-INF/web.xml
Its contents are
<?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>SessionServlet</display-name>
<welcome-file-list>
<welcome-file>start.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>my Session Servlet</servlet-name>
<servlet-class>com.example.session.SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>my Session Servlet</servlet-name>
<url-pattern>/MySessionServlet</url-pattern>
</servlet-mapping>
<!-- set session timeout to 30 minutes -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- register listener class -->
<listener>
<listener-class>com.example.session.MySessionListener</listener-class>
</listener>
</web-app>
And that's all. Lastly my two cents- you should first acquaint with Standard Edition Java. This is an example from Enterprise world which is way over your head yet. There are plenty of tutorials on the web. Give it some time, you won't regret it.
Regarding the servlets- you should (must) first understand the basic concepts of request, response, session, client and container (who is who, the lifecycle, managing, etc.) before you start making real projects. The best book I've seen about this is Head First - Servlets and JSP, which should be a starting point in understanding this topic.
You set response.setContentType("text/html;charset=UTF-8") ....
But in your section if(!s.isNew()){.... the output is not HTML, but is plain text. ("Name:", etc...)
My bet is that the content is there, but your browser is not displaying it.
Related
So I'm new to servlets and jsp, and was following along to the Hello World post-process example from https://stackoverflow.com/tags/servlets/info. When I tried to run it using Tomcat v9.0 in Eclipse, I get
After doing some additional research, and poking around, I haven't found a working solution or an explanation of what is happening. I had basically copied the code from the example, so I'm pretty confused as to why it isn't working. I also don't really have the proficiency yet to figure out exactly what is wrong, so any help would be great. My only hunch so far is that I probably messed up the directories or something. Here is a picture:
The only discrepancy I could find was where my HelloServlet.class was located, which was in
apache-tomcat-9.0.19/webapps/hello/build/classes/com/example/controller/HelloServlet.class
instead of
/WEB-INF/classes/com/example/controller/HelloServlet.class
as stated in the example. I assumed this was because Eclipse, by default, had compiled the class file where it is now, but just to be sure, I copied the class folder into WEB-INF so it would match the example, but it still didn't work. So that is where I'm stuck. If anyone could point out my mistake or even help at all, that would be very much appreciated. I have included my hello.jsp, web.xml, and HelloServlet.java files below just in case there's any issues with them.
hello.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Servlet Hello World</title>
<style>.error { color: red; } .success { color: green; }</style>
</head>
<body>
<form action="hello" method="post">
<h1>Hello</h1>
<p>
<label for="name">What's your name?</label>
<input id="name" name="name" value="${fn:escapeXml(param.name)}">
<span class="error">${messages.name}</span>
</p>
<p>
<label for="age">What's your age?</label>
<input id="age" name="age" value="${fn:escapeXml(param.age)}">
<span class="error">${messages.age}</span>
</p>
<p>
<input type="submit">
<span class="success">${messages.success}</span>
</p>
</form>
</body>
</html>
web.xml
<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"
metadata-complete="true">
</web-app>
HelloServlet.java
package com.example.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#SuppressWarnings("serial")
#WebServlet("/hello")
public class HelloServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Preprocess request: we actually don't need to do any business stuff, so just display JSP.
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Postprocess request: gather and validate submitted data and display the result in the same JSP.
// Prepare messages.
Map<String, String> messages = new HashMap<String, String>();
request.setAttribute("messages", messages);
// Get and validate name.
String name = request.getParameter("name");
if (name == null || name.trim().isEmpty()) {
messages.put("name", "Please enter name");
} else if (!name.matches("\\p{Alnum}+")) {
messages.put("name", "Please enter alphanumeric characters only");
}
// Get and validate age.
String age = request.getParameter("age");
if (age == null || age.trim().isEmpty()) {
messages.put("age", "Please enter age");
} else if (!age.matches("\\d+")) {
messages.put("age", "Please enter digits only");
}
// No validation errors? Do the business job!
if (messages.isEmpty()) {
messages.put("success", String.format("Hello, your name is %s and your age is %s!", name, age));
}
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
You need to allow cross origin
private void setAccessControlHeaders(HttpServletResponse resp) {
resp.setHeader("Access-Control-Allow-Origin", "http://localhost:9000");
resp.setHeader("Access-Control-Allow-Methods", "GET");
}
I'm learning Java Web, but I have some problems and I need help.
I use a template.jsp in which I include header.jsp, footer.jsp, login.jsp (the left side of the template ) and ${param.content}.jsp. For each page named X.jsp I made another jsp with the following content, because I want each page to have the same layout:
<jsp:include page="template.jsp">
<jsp:param name="content" value="X"/>
<jsp:param name="title" value="Start navigate"/>`enter code here`
</jsp:include>
When I click on the Review link,for example, I want to be redirect to Review.jsp, but I have some problems.
In footer.jsp I have something like this:
(...)
< a href =" Review.jsp "> Review </a>
(...)
After login, I try to click Review, it sends me to the Review.jsp, but it shows me that I'm not logged in. I use Spring Framework, Tomcat 7, Eclipse, MySQL. When I log in, I create a cookie:
String timestamp = new Date().toString();
String sessionId = DigestUtils.md5Hex(timestamp);
db.addSession(sessionId, username, timestamp);
Cookie sid = new Cookie("sid", sessionId);
response.addCookie(sid);
For each method, I have something like this (I saw this in a tutorial):
#RequestMapping(value = "/writeReview", method = RequestMethod.GET)
public String nameMethod(#CookieValue("sid") String sid,...)
Using the sid, I can find out who's the user. I have a database with the user's account and some other tables. The problem is that when I click review or any other, it shows me that I'm not logged in. What can I do?
UPDATE:
I use JavaBean for user and login.jsp. The JSP that has the text box for the login, I have a GET method when I click on the button to log in.
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView createCookie(
#RequestParam("username") String username, #RequestParam("password") String password,
HttpServletRequest request, HttpServletResponse response) throws SQLException {
//code for creating the cookie here, after testing if the user is in my database
}
For each page, I send the sid and I have an attribute for the model, username:
public String methodName(#CookieValue(required = false) String sid, Model model) {
if (sid != null) {
User user = getUserBySid(sid);
model.addAttribute("user", user);
}
(..other data.)
return "nameJSP.jsp";
}
I check in each JSP if the username is not empty, so that's how I see if a user is logged in. The application goes well, it passes parameters if I don't click on the links from the header or footer. The problem is that I have to pass , let's say, a parameter from a JSP who's the actual content of the layout to the JSP referred by the footer and this JSP will be the next content of my layout. The layout only recognize content and title:
<title>${param.title}</title>
(I didn't paste all the code, I use a table <table>....)
<%# include file="header.jsp"%>
<%# include file="login.jsp"%>
<jsp:include page="${param.content}.jsp"/>
<%# include file="footer.jsp"%>
So how can I include a parameter in this JSP which will be received from another JSP? Also it will have to be accessed by layout.jsp and sent to the footer or the header?
<jsp:include page="layout.jsp">
<jsp:param name="content" value="X"/>
<jsp:param name="title" value="Start navigate"/>
</jsp:include>
To pass some parameter(s) to the included JSP:
<jsp:include page="somePage.jsp" >
<jsp:param name="param1" value="someValue" />
<jsp:param name="param2" value="anotherParam"/>
....
</jsp:include>
You are already doing it.
OK, the details of the question is not very clear, but I get the idea.
One of the solutions could be the following.
In your Login action, if the authentication was successful, create HttpSession and set an attribute for the authenticated User:
if (/* authentication was successfull */) {
request.getSession().setAttribute("loggedInUser", user);
...
}
And in the code where you are controlling if the user is logged in just check the presence of the appropriate HttpSession attribute:
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("loggedInUser") == null) {
// user is not logged in, do something about it
} else {
// user IS logged in, do something: set model or do whatever you need
}
Or in your JSP page you can check if the user is logged in using JSTL tags as showed by BalusC in the example here:
...
<c:if test="${not empty loggedInUser}">
<p>You're still logged in.</p>
</c:if>
<c:if test="${empty loggedInUser}">
<p>You're not logged in!</p>
</c:if>
...
Filters to the rescue
But usually, you check if the user is logged in to restrict access to some pages (so only authenticated user could access them). And you write some class that implements javax.servlet.Filter.
Here is an example of the LoginFilter from one of my projects:
package com.example.webapp.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* The purpose of this filter is to prevent users who are not logged in
* from accessing confidential website areas.
*/
public class LoginFilter implements Filter {
/**
* #see Filter#init(FilterConfig)
*/
#Override
public void init(FilterConfig filterConfig) throws ServletException {}
/**
* #see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("loggedInUser") == null) {
response.sendRedirect(request.getContextPath() + "/login.jsp");
} else {
chain.doFilter(request, response);
}
}
/**
* #see Filter#destroy()
*/
#Override
public void destroy() {}
}
In this project I used plain servlets and JSP without Spring, but you'll get the idea.
And of course, you must configure web.xml to use this filter:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
...
<filter>
<filter-name>Login Filter</filter-name>
<filter-class>com.example.webapp.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Login Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
</web-app>
Note:
If you are using a Web Container or Application Server that supports Servlet version 3.0 and higher then you can annotate your filter class with #WebFilter annotation in which case there is no need to configure the filter in the deployment descriptor (web.xml). See an example of using #WebFilter annotation and more Filter related information here.
Hope this will help you.
Or just use:
String username = request.getRemoteUser();
I want to create a servlet project.
My Java class is called AzpanaServlet.java, and it contains an inner class. (When I compile it, I have 2 class files).
My project is a simple application that receives a string input and does some stuff with it (not relevant).
When I press on the "submit" button I receive the following error:
HTTP Status 404 - /AzpanaServlet
Type Status report
Message /AzpanaServlet
Description The requested resource (/AzpanaServlet) is not available.
Apache Tomcat/6.0.18
Please help me if you can, I can't solve this much time.
this is my Java code:
public class AzpanaServlet extends HttpServlet {
//
//Some functions
//
//Inner class: public class oneChar{...}
//
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* Get the value of form parameter
*/
String name = request.getParameter("name");
/*
* Set the content type(MIME Type) of the response.
*/
response.setContentType("text/html");
String str = "";
PrintWriter out = response.getWriter();
ArrayList<Integer> list = new ArrayList<Integer>();
try {
list = mainmanu(name); //not relevant function.
} catch (Exception e) {
str = e.toString();
e.printStackTrace();
}
/*
* Write the HTML to the response
*/
out.println("<html>");
out.println("<head>");
out.println("<title> this is your answers</title>");
out.println("</head>");
out.println("<body>");
if(str != ""){
out.println(str);
}
else{
for(int i = 0;i<=40;i++){
out.println(list.get(i));
out.println("<br>");
}
}
out.println("<a href='form.html'>"+"Click here to go back to input page "+"</a>");
out.println("</body>");
out.println("</html>");
out.close();
}
public void destroy() {
}
}
My web.xml code:
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>AzpanaServlet</servlet-name>
<servlet-class>com.example.AzpanaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AzpanaServlet</servlet-name>
<url-pattern>/AzpanaServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/form.html</welcome-file>
</welcome-file-list>
</web-app>
My form.html code:
<html>
<head>
<title>Zeev's Project</title>
</head>
<body>
<h1>Just Enter String</h1>
<form method="POST" action="AzpanaServlet">
<label for="name">Enter String</label>
<input type="text" id="name" name="name"/><br><br>
<input type="submit" value="Submit Form"/>
<input type="reset" value="Reset Form"/>
</form>
</body>
</html>
The hierarchy of the Folder is following:
ROOT[
WEB-INF[
web.xml
classes[
com[
example[
AzpanaServlet.class
AzpanaServlet$oneChar.class
]
]
]
lib[
AzpanaServlet.java
]
]
META-INF[
MANIFEST.MF
]
form.html
]
Copied your exact code and just commented out the Servlet code to be
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* Get the value of form parameter
*/
String name = request.getParameter("name");
System.out.println("Parameter name : "+name);
Works like a charm.
In my server console
Parameter name : helloo
There is no problem with your configuration. You might want to clean your browser cache and try again.
The problem may be that you are using IDE to run the Tomcat Server and deployed to the root application context. Try to use some app context for your application in deployment. For example /myapp.
Have a look at your IDE console or your tomcat log, did your web application ever started successfully?
It might didn't start for some reason.
I'm experimenting with sending data from a jsp form and calling a servlet and showing that data in the servlet.
I would like to use setAttribute and getAttribute.
In this jsp file I'm using setAttribute:
<HTML>
<HEAD>
<TITLE>
Multi Processor
</TITLE>
</HEAD>
<BODY>
<h4>This is a form submitted via POST:</h4>
<FORM action = "/MyWebArchive/MulitProcessorServlet" method = "POST">
Enter your name: <INPUT type="TEXT" name="name"/>
<BR/>
<INPUT type="submit"/>
</FORM>
<BR/>
<h4>This is a form submitted via GET:</h4>
<FORM action = "/Week05WebArchive/MulitProcessorServlet">
Enter your name: <INPUT type="TEXT" name="name"/>
<BR/>
<INPUT type="submit"/>
</FORM>
</BODY>
<%
String strMasjidLocation = "Selimiyie Masjid Methuen";
session.setAttribute("MasjidLocation", strMasjidLocation);
%>
</HTML>
This is the servlet I would like to use getAttribute but I don't know how to use GetAttribute. Can you show me what additional code I need to add to the servlet so I can capture the value from the setAttribute?
package temp22;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MulitProcessorServlet
*/
public class MulitProcessorServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
doPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
String name = req.getParameter("name");
StringBuffer page = new StringBuffer();
String methodWhoMadeTheCall = req.getMethod();
String localeUsed = req.getLocale().toString();
String strMasjidLocation = null;
//strMasjidLocation = this is where I would like to capture the value from the jsp that called this servlet.
page.append("<HTML><HEAD><TITLE>Multi Form</TITLE></HEAD>");
page.append("<BODY>");
page.append("Hello " + name + "!");
page.append("<BR>");
page.append("The method who called me is: " + methodWhoMadeTheCall);
page.append("<BR>");
page.append("The language used is: " + localeUsed);
page.append("<BR>");
page.append("I am at this location: " + strMasjidLocation);
page.append("</BODY></HTML>");
res.setContentType("text/html");
PrintWriter writer = res.getWriter();
writer.println(page.toString());
writer.close();
}
}
This should work:
String value = (String) req.getSession(false).getAttribute("MasjidLocation")
Don't use scriptlets; that's 1999 style. Learn JSTL and write your JSPs using that.
Your servlets should never, ever have embedded HTML in them. Just validate and bind parameters, pass them off to services for processing, and put the response objects in request or session scope for the JSP to display.
I agree with duffymo that you should learn on newer technology (if this is applicable, maybe your client cannot allow that...). Anyway, to get the value of the attribute you owuld do:
strMasjidLocation = (String)req.getSession().getAttribute("MasjidLocation");
Also, I notice you have two different paths for your servlets in your HTML < form> tags:
MyWebArchive/MulitProcessorServlet
and
Week05WebArchive/MulitProcessorServlet
Is it expected?
You used Session not Request.
you may need to get Session from request.
String strMasjidLocation = request.getSession().getAttribute("MasjidLocation");
This question already has answers here:
HTTP Status 405 - HTTP method is not supported by this URL
(2 answers)
Closed 1 year ago.
I am having trouble getting the page to work. I have my form method to post and my servlet implements doPost(). However, it keeps showing me that I am not supporting the POST method.
I am just trying to do a simple website and insert values into my MySQL DB.
*type Status report
message HTTP method POST is not supported by this URL
description The specified HTTP method is not allowed for the requested resource (HTTP method POST is not supported by this URL).*
the static page:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN"
"http://www.wapforum.org/DTD/xhtml-mobile10.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>XHTML Mobile Profile Document</title>
<!--
Change href="style.css" below to the file name and
relative path or URL of your external style sheet.
-->
<link rel="stylesheet" href="index.css" type="text/css"/>
<!--
<style> document-wide styles would go here </style>
-->
</head>
<body>
<h1> Register Here </h1>
<form action="regSuccess.do" method = "POST">
UserName: <input type="text" name="txtregUsername" size="15" maxlength="15">
<br/>
Password: <input type="password" name="txtregPassword" size="15"
maxlength="15"><br/>
Name: <input type="text" name="txtregName" size="20" maxlength="30"><br/>
Email: <input type="text" name="txtregEmail" size="20" maxlength="30">
<br/><br/>
<input type="submit" name="btnRegister" value="Register Me"/>
</form>
</body>
</html>
the servlet:
package core;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class handlingReg extends HttpServlet {
//database parameters
private static final String db_server = "localhost/";
private static final String db_name ="bus_guide";
private Connection con = null;
//init of connection to dabatase
public void init(ServletConfig config) throws ServletException {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception e) {
System.out.println("Exception in init(): unable to load JDBC DriverA");
}
try {
con = DriverManager.getConnection("jdbc:mysql://"+ db_server + db_name , "root" , "");
System.out.println("conn: "+con);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
//end init()
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response handling
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//handling request
String enteredUsername = request.getParameter("txtregUsername");
String enteredPw = request.getParameter("txtregPassword");
String enteredName = request.getParameter("txtregName");
String enteredEmail = request.getParameter("txtregEmail");
//inserting values into database
try {
Statement stmnt = con.createStatement();
stmnt.executeUpdate("INSERT INTO regUsers VALUES('"+enteredUsername+"','"+enteredPw+"','"+enteredName+"','"+enteredEmail+"')");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
//output html out.println("");
out.println("<?xml version = \"1.0\" encoding =\"utf-8\"?>");
out.println("<!DOCTYPE html PUBLIC \"-//WAPFORUM/DTD XHTML Mobile 1.0//EN\"");
out.println(" \"http://www.wapforum.org/DTD/xhtml-mobile10.dtd\">");
out.println("<html xmlns=\"http://www.w3.org/1000/xhtml\">");
out.println("<head>");
out.println("<title></title>");
out.println("</head>");
out.println("<body>");
out.println("Register Success!");
out.println("<a href = \"index.xhtml\"> Click here to go back to main page.
</a>");
out.println("</body>");
out.println("</html>");
}
}
web.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<!--Self declared servlet mapping starts here-->
<servlet>
<servlet-name>handleRegister</servlet-name>
<servlet-class>core.handlingReg</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>handleRegister</servlet-name>
<url-pattern>/regSuccess.do</url-pattern>
</servlet-mapping>
<!--Self declared servlet mapping ends here-->
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
<mime-mapping>
<extension>xhtml</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>jad</extension>
<mime-type>text/vnd.sun.j2me.app-descriptor</mime-type>
</mime-mapping>
<mime-mapping>
<extension>jar</extension>
<mime-type>application/java-archive</mime-type>
</mime-mapping>
</web-app>
edit:removed doGet(request,response);
It's because you're calling doGet() without actually implementing doGet(). It's the default implementation of doGet() that throws the error saying the method is not supported.
if you are using tomcat you may try this
<servlet-mapping>
<http-method>POST</http-method>
</servlet-mapping>
in addition to <servlet-name> and <url-mapping>
It says "POST not supported", so the request is not calling your servlet. If I were you, I will issue a GET (e.g. access using a browser) to the exact URL you are issuing your POST request, and see what you get. I bet you'll see something unexpected.
This happened to me when:
Even with my servlet having only the method "doPost"
And the form method="POST"
I tried to access the action using the URL directly, without using the form submitt. Since the default method for the URL is the doGet method, when you don't use the form submit, you'll see # your console the http 405 error.
Solution: Use only the form button you mapped to your servlet action.
If you're still facing the issue even after replacing doGet() with doPost() and changing the form method="post". Try clearing the cache of the browser or hit the URL in another browser or incognito/private mode. It may works!
For best practices, please follow this link.
https://www.oracle.com/technetwork/articles/javase/servlets-jsp-140445.html