Why "response.sendRedirect" doesn't work? - java

This is my login part which I need to compare user input with data in the database.
So If a lecturer tries to enter the system, he or she will get into lecturer interface(lecturer.html) and same goes to the student.
But right now, when I try to enter the system using either lecturer or student ID, the system will direct me to the log in interface.
I hope someone can help me to solve this :)
This is the query for Java DB (LogIn.java)
public class LogIn extends HttpServlet {
static final String dbURI = "jdbc:derby://localhost:1527/webdb";
String str = SELECT DEMO.REGISTRATION.*, \n" +
DEMO.STUDENT.STUD_PASSWORD,DEMO.LECTURER.LECT_PASSWORD
FROM DEMO.REGISTRATION
LEFT OUTER JOIN DEMO.STUDENT
ON REGISTRATION.STUDENT_ID = STUDENT.STUDENT_ID
LEFT OUTER JOIN DEMO.LECTURER
ON REGISTRATION.LECTURER_ID = LECTURER.LECTURER_ID;";
Connection theConnection = null;
And this is the rest of codes (LogIn.java)
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String matricI = request.getParameter("matricin");
String passwordI = request.getParameter("passwordin");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>\n" +
" <head>\n" +
" <title>SPEDT | UKM</title>\n" +
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n" +
" <link rel=\"stylesheet\" href=\"//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css\">\n" +
" <link rel=\"stylesheet\" href=\"//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css\">\n" +
" <script src=\"//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js\"></script>\n" +
" </head>\n" +
" \n" +
" <body>\n" +
" \n" +
" <div class=\"navbar navbar-inverse \" role=\"navigation\">\n" +
" <div class=\"container\">\n" +
" <div class=\"navbar-header\">\n" +
" <button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\".navbar-collapse\">\n" +
" <span class=\"sr-only\">Toggle navigation</span>\n" +
" <span class=\"icon-bar\"></span>\n" +
" <span class=\"icon-bar\"></span>\n" +
" <span class=\"icon-bar\"></span>\n" +
" </button>\n" +
" <a class=\"navbar-brand\" href=\"#\">Sistem Penilaian Esei Dalam Talian</a>\n" +
" </div>\n" +
" <div class=\"navbar-collapse collapse\">\n" +
" <form class=\"navbar-form navbar-right\" role=\"form\" method=\"get\" action=\"http://localhost:8080/Spedt/LogIn\">\n" +
" <a class=\"btn btn-danger\" role=\"button\" href=\"http://localhost:8080/Spedt/start.html\">Keluar</a>\n" +
" </form>\n" +
" </div><!--/.navbar-collapse -->\n" +
" </div>\n" +
" </div>\n" +
"</html>");
// Load database driver
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch (ClassNotFoundException cnfe){
System.out.println(cnfe);
}
// Create a Connection to contacts db Data source
try {
theConnection = DriverManager.getConnection(dbURI,"demo","demo");
} catch (SQLException sqle) {
System.out.println(sqle);
}
// prepare statement for inserting data into table
try {
PreparedStatement theStatement=theConnection.prepareStatement(str);
request.setAttribute("matricin",matricI);
request.setAttribute("passwordin",passwordI);
Statement st = theConnection.createStatement();
ResultSet rs = st.executeQuery(str);
String m = matricI;
String p = passwordI;
while (rs.next()) {
String matricS = rs.getString("STUDENT_ID");
String passwordS = rs.getString("STUD_PASSWORD");
String matricL = rs.getString("LECTURER_ID");
String passwordL = rs.getString("LECT_PASSWORD");
if(m.equals(matricS) && p.equals(passwordS)){
response.sendRedirect("http://localhost:8080/Spedt/StudentInput");
return;}
else if(m.equals(matricL) && p.equals(passwordL)){
response.sendRedirect("http://localhost:8080/Spedt/Lecturer.html");
return;}
else {
out.println("<p class=\"bg-danger container\">Sila masukkan No. Matrik dan Kata Laluan yang betul !</p>");
}
}
}
catch (SQLException sqle) {
System.out.println(sqle);
}
theConnection.close(); //Close database Connection
}catch(Exception e) {
out.println(e.getMessage());//Print trapped error.
} finally {
out.close();
}
}
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);
}
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
and this is the html
<form class="navbar-form navbar-right" role="form" method="get" action="http://localhost:8080/Spedt/LogIn">
<div class="form-group">
<input type="text" name="matricin" placeholder="No. Matrik" class="form-control">
</div>
<div class="form-group">
<input type="password" name="passwordin" placeholder="Kata Laluan" class="form-control">
</div>
<button type="submit" class="btn btn-success">Masuk</button>
</form>
This is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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_3_1.xsd">
<servlet>
<servlet-name>InputData</servlet-name>
<servlet-class>mypkg.InputData</servlet-class>
</servlet>
<servlet>
<servlet-name>GetData</servlet-name>
<servlet-class>mypkg.GetData</servlet-class>
</servlet>
<servlet>
<servlet-name>LogIn</servlet-name>
<servlet-class>mypkg.LogIn</servlet-class>
</servlet>
<servlet>
<servlet-name>Lecturer</servlet-name>
<servlet-class>mypkg.Lecturer</servlet-class>
</servlet>
<servlet>
<servlet-name>Student</servlet-name>
<servlet-class>mypkg.Student</servlet-class>
</servlet>
<servlet>
<servlet-name>LogOut</servlet-name>
<servlet-class>mypkg.LogOut</servlet-class>
</servlet>
<servlet>
<servlet-name>LecturerInput</servlet-name>
<servlet-class>mypkg.LecturerInput</servlet-class>
</servlet>
<servlet>
<servlet-name>GetDataLecturer</servlet-name>
<servlet-class>mypkg.GetDataLecturer</servlet-class>
</servlet>
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>mypkg.NewServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>InputLecturer</servlet-name>
<servlet-class>mypkg.InputLecturer</servlet-class>
</servlet>
<servlet>
<servlet-name>GetDataLect</servlet-name>
<servlet-class>mypkg.GetDataLect</servlet-class>
</servlet>
<servlet>
<servlet-name>StudentInput</servlet-name>
<servlet-class>mypkg.StudentInput</servlet-class>
</servlet>
<servlet>
<servlet-name>InputStudent</servlet-name>
<servlet-class>mypkg.InputStudent</servlet-class>
</servlet>
<servlet>
<servlet-name>GetDataStud</servlet-name>
<servlet-class>mypkg.GetDataStud</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InputData</servlet-name>
<url-pattern>/InputData</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GetData</servlet-name>
<url-pattern>/GetData</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LogIn</servlet-name>
<url-pattern>/LogIn</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Lecturer</servlet-name>
<url-pattern>/Lecturer</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Student</servlet-name>
<url-pattern>/Student</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LogOut</servlet-name>
<url-pattern>/LogOut</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LecturerInput</servlet-name>
<url-pattern>/LecturerInput</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GetDataLecturer</servlet-name>
<url-pattern>/GetDataLecturer</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>InputLecturer</servlet-name>
<url-pattern>/InputLecturer</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GetDataLect</servlet-name>
<url-pattern>/GetDataLect</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>StudentInput</servlet-name>
<url-pattern>/StudentInput</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>InputStudent</servlet-name>
<url-pattern>/InputStudent</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GetDataStud</servlet-name>
<url-pattern>/GetDataStud</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
I hope someone can help me to solve this problem.thanks :)

In your code you don't need to specify full URL in action you can just Specify abc.jsp or ServletName which is there in web.xml.
<form class="navbar-form navbar-right" role="form" method="get" action="LogIn">
Secondly you need to specify onClick in Submit button of your form.
<button type="submit" class="btn btn-success" onclick="action">Masuk</button>
EDIT
I'm getting this, every time I try to log in.
localhost:8080/Spedt/LogIn?matricin=A138&passwordin=92
So it's working and you need to do some stuff in your LogIn Servlet as your doGet method is Empty and better to Use POST for LogIn!!!

ohhh..
In this case control is not reaching to servlet so how would you expect to run redirect!!
In action part of your html you have written action="http://localhost:8080/Spedt/LogIn"
you should use action for your servlet which you have define in web.xml file
see your xml file is
<servlet>
<servlet-name>LogIn</servlet-name>
<servlet-class>mypkg.LogIn</servlet-class>
</servlet>
if your write action=LogIn then you will go to mypkg.LogIn servlet

Related

Can't Post a message using Facebook's API, using MVC and Java

I was trying to use the facebook API to post a message to share a page I am making as a project to learn to use APIs.
And I'm running into the following problem.
I tried to post and I was redirected to facebook where I accepted a bunch of permisions and then I was redirected to the url "MyUrl/oauth2callback/Facebook?code=A very large code" and got a 404 Not Found error.
I'm not sure what the problem is and I have been trying to find it for the past 3 days, here is the resource I am using:
import org.restlet.resource.ClientResource;
public class FacebookPostResource {
private String uri = "https://graph.facebook.com/me/feed";
private String access_token = null;
public FacebookPostResource(String access_token) {
this.access_token = access_token;
}
public boolean publishPost(String message){
String normalizedMessage=message.replace(' ', '+');
ClientResource cr=new ClientResource(uri+"?access_token="+access_token);
cr.post("message="+normalizedMessage);
return true;
}
}
Here is the Controller:
public class FacebookPostController extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -6818025976353856770L;
private static final Logger log =
Logger.getLogger(FacebookPostController.class.getName());
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
IOException,ServletException {
String accessToken=(String)req.getSession().getAttribute("Facebook-
token");
if(accessToken!=null && !"".equals(accessToken)){
FacebookPostResource fbResource=new
FacebookPostResource(accessToken);
fbResource.publishPost(req.getParameter("message"));
req.getRequestDispatcher("/").forward(req,resp);
}else{
log.info("Trying to acces to Facebook without an acces token,
redirecting to OAuth servlet");
req.getRequestDispatcher("/AuthController/Facebook").forward(req,resp);
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws
IOException,ServletException {
doGet(req,resp);
}
}
Here is My scope configuration:
{
"Facebook":{
"tokenUrl":"https://graph.facebook.com/v2.8/oauth/access_token",
"clientId":"MyID",
"clientSecret":"MySecret" ,
"authorizationFormUrl":"https://www.facebook.com/v2.8/dialog/oauth",
"scopes":["user_posts", "user_friends"]
}
}
Here is the JSP where I write the post:
<c:if test='${empty sessionScope["Facebook-token"]}'>
<c:redirect url = "/AuthController/Facebook"/>
</c:if>
<h1>Publicar Post en Facebook</h1>
<div class="container">
<p class="message"></p>
<form action="/facebookPostCreation" method="post">
Mensaje: <textarea name="message"></textarea>
<br>
<div class="bottom_links">
<button type="submit" class="button">Publicar en
Facebook</button>
<button type="button"
onClick="javascript:window.location.href='index.html'"
class="button">Cancel</button>
</div>
</form>
</div>
And finally here is my web.xml
...
<servlet>
<servlet-name>FacebookPostCreation</servlet-name>
<servlet-class>aiss.controller.FacebookPostController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FacebookPostCreation</servlet-name>
<url-pattern>/facebookPostCreation</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>FacebookAuthController</display-name>
<servlet-name>FacebookAuthController</servlet-name>
<servlet-class>aiss.controller.oauth.GenericAuthController</servlet-class>
<init-param>
<param-name>provider</param-name>
<param-value>Facebook</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FacebookAuthController</servlet-name>
<url-pattern>/AuthController/Facebook</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>FacebookOAuth2Callback</display-name>
<servlet-name>FacebookOAuth2Callback</servlet-name>
<servlet-class>aiss.controller.oauth.OAuth2Callback</servlet-class>
<init-param>
<param-name>provider</param-name>
<param-value>Facebook</param-value>
</init-param>
<init-param>
<param-name>onSuccess</param-name>
<param-value>redirect:/facebookFriendsListing</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FacebookOAuth2Callback</servlet-name>
<url-pattern>/OAuth2Callback/Facebook</url-pattern>
</servlet-mapping>
Try using my code
https://github.com/OswaldoRosalesA/FacebookAPIJava.git
Use Debuger.java to Test.
I use the Graph API
https://developers.facebook.com/docs/graph-api

Getting more information about an object when clicking on a text in html using MVC

So I'm a making a small web app to get information about games, I have made a searchBar that request the search to an API and then I get the first 10 games with the most similar title to the search. But I only show the title.
This is an example of a search
The games have a lot of attributes, one of them is the ID, and it allows me to get all the info of a game using a controller.
Right now the app works like this:
1: You search the title of a game
2. A controller gives me a List of IDs and with the ids I get the rest of the info about the games, but I only show the titles.
Now, what I want to do:
3.When you click on a title you use a controller, and from the ID it request (again, I'm not sure if I can use the previous games objects) all the info from that game and Shows it.
The controllers works fine, but I'm having problems with the HTML.
This is the controller for the search:
...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String query = request.getParameter("searchQuery");
RequestDispatcher rd = null;
log.log(Level.FINE, "Searching for games that contain " + query);
GameResource game = new GameResource();
GameSearch[] gameResults = null;
gameResults = game.getGameSearch(query);
//System.out.println(Arrays.toString(gameResults));
List<Game> listaBusqueda = new ArrayList<Game>();
if (gameResults.length!=0){
rd = request.getRequestDispatcher("/success.jsp");
for (GameSearch g : gameResults) {
listaBusqueda.add(game.getGame(g.getId().toString()));
}
request.setAttribute("games", listaBusqueda);
} else {
log.log(Level.SEVERE, "Game object: " + gameResults);
rd = request.getRequestDispatcher("/error.jsp");
}
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
...
This is the controllers that gives me a game using an ID
...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String gameId = request.getParameter("id");
GameResource resource = new GameResource();
RequestDispatcher rd = null;
log.log(Level.FINE, "Retrieving game");
Game game = resource.getGame(gameId);
if(game!=null) {
rd = request.getRequestDispatcher("/success.jsp");
request.setAttribute("Game", game);
request.setAttribute("Item", "gameID");
} else {
log.log(Level.SEVERE, "Cannot retrieve game: ");
rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
}
/**
* #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);
}
}
Both of them works, in the last one the objects are created correctly and the ID is obtained.
Now, this is the html for success.jsp, and this is where the problem is:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Search results</title>
</head>
<body>
<fieldset id="IGDB">
<legend>
IGDB search for
<c:out value="${param.searchQuery}" />
</legend>
<c:forEach items="${requestScope.games}" var="game">
<article name="gameArticle" id="gameArticle"></article>
<a href="GameIdController?id=${game.id}"><c:out value="${game.name}"
/></a>
<br />
</c:forEach>
</fieldset>
<c:if test="${requestScope.Item=='gameID' }">
<c:forEach items="${requestScope.Game}" var="game">
<article name="gameArticle" id="gameArticle"></article>
<c:out value="${game.name}" />
<br />
</c:forEach>
$game = ${requestScope.Game}
<c:out value="${game.name}"/>
</c:if>
<article name = "gameByIDArticle" id = "gameByIDArticle">
</article>
</body>
</html>
When I click in a title, I get redirected to a blank webpage (http://localhost:8090/GameIdController?id=IdOfTheGame),as you can see the id is included in the URL, but it's completely blank and it should include the title again as is stated in my code.
I will also include my web.xml
<?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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<description></description>
<display-name>GameSearchController</display-name>
<servlet-name>GameSearchController</servlet-name>
<servlet-class>aiss.controller.GameSearchController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GameSearchController</servlet-name>
<url-pattern>/GameSearchController</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>GamePopularityController</display-name>
<servlet-name>GamePopularityController</servlet-name>
<servlet-class>aiss.controller.GamePopularityController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GamePopularityController</servlet-name>
<url-pattern>/GamePopularityController</url-pattern>
</servlet-mapping>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/api</param-value>
</context-param>
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-
class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-
class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>aiss.api.GameApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>GameIdController</display-name>
<servlet-name>GameIdController</servlet-name>
<servlet-class>aiss.controller.GameIdController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GameIdController</servlet-name>
<url-pattern>/GameIdController</url-pattern>
</servlet-mapping>
</web-app>
Okay i think i understand why you are seeing a blank page. Everything is working as expected, the problem seems to be with this:
if(game!=null) {
rd = request.getRequestDispatcher("/success.jsp");
request.setAttribute("Game", game);
request.setAttribute("Item", "gameID");
} else {
log.log(Level.SEVERE, "Cannot retrieve game: ");
rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
The reason why you are seeing a blank page is because your game variable is not null. And you don't have a forward statement in the first part of that if else block.
if(game!=null) {
rd = request.getRequestDispatcher("/success.jsp");
request.setAttribute("Game", game);
request.setAttribute("Item", "gameID");
rd.forward(request, response); // missing this!
} else {
log.log(Level.SEVERE, "Cannot retrieve game: ");
rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
EDIT: In response to your other problem from the comment, i think the forEach is having problems because of this:
<c:forEach items="${requestScope.Game}" var="game">
change it to this:
<c:forEach items="${Game}" var="game">

Error with Java Servlet & DB connection [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
Having issues getting the program to display anything when running in eclipse.
Goal is:
In this application you will also create a virtual directory so that you do not have to use the word servlet as part of your form post URL. You will then be able to run your Web application servlet by using a URL similar to the following: http://localhost:7070/Week5/FormPost2. To create your virtual directory you may start by modifying the web.xml attached to this assignment. Next, create a Servlet that displays a form when the doGet method is invoked. The form will contain a post action that directs the form post back to the same servlet, which in the doPost method will save the form data to a database. Use your Oracle account to make the DB connection. After the form data has been saved to the database, respond back with a query from the database displaying all the current records contained in the database, in an appealing format. The form must contain a minimum of three input fields.
Below error was received:
HTTP Status 404 - /Week5/servlet/Week5.Week5
type Status report
message /Week5/servlet/Week5.Week5
description The requested resource is not available.
Apache Tomcat/7.0.72
I'm sure it is a simple error, but please pinpoint it so I can get it to display properly. Thank you.
package Week5;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Week5 extends HttpServlet{
private static final long serialVersionUID = 1L;
Connection con = null;
Statement stmt = null;
public Week5(){
init();
}
public void init(){
try{
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "student2", "pass");
stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE MYTABLE (FNAME VARCHAR2(20), LNAME VARCHAR2(40), PHONE VARCHAR2(20))");
stmt.close();
}
catch (Exception e){
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println("First Name:");
out.println("");
out.println("");
out.println("Last Name:");
out.println("");
out.println("");
out.println("Phone:");
out.println("");
out.println("SUBMIT");
out.println("");
out.println("");
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
try{
if (con != null)
init();
String fname = request.getParameter("FNAME");
String lname = request.getParameter("LNAME");
String phone = request.getParameter("PHONE");
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO MYTABLE VALUES('" + fname + "', '" + lname + "', '" + phone + "')");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
ResultSet rset = stmt.executeQuery("SELECT * FROM MYTABLE");
while (rset.next()){
out.print("");
out.print("First Name: " + rset.getString(1));
out.print("");
out.println();
out.print("");
out.print("Last Name: " + rset.getString(2));
out.print("");
out.println();
out.print("");
out.print("Phone: " + rset.getString(3));
out.print("");
out.println();
out.println();
}
out.println("");
out.close();
stmt.close();
}
catch (Exception e){
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println(e.getMessage());
out.println("");
out.close();
}
}
}
XML
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
<servlet>
<servlet-name>
Week5 <!-- Alias I gave the servlet // -->
</servlet-name>
<servlet-class>
HelloWorld <!-- Class name // -->
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
Week5 <!-- Alias I gave the servlet // -->
</servlet-name>
<url-pattern>
/VirtualName <!-- What I want the user to type in // -->
<!-- Example: http://localhost:7070/Week5/FormPost2 // -->
</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>
FormPost2
</servlet-name>
<servlet-class>
HelloWorld2
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
FormPost2
</servlet-name>
<url-pattern>
/VirtualName2
</url-pattern>
</servlet-mapping>
</web-app>
your servlet class should be fully qualified class name such as
<servlet-class>
week5.week5
</servlet-class>
<servlet-class> tag should contain the servlet(class)
<servlet-name> will be the name of the servlet that is mapped with the <servlet-mapping>
example
<servlet>
<servlet-name>
anyServletName
</servlet-name>
<servlet-class>
com.example.customServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
anyServletName
</servlet-name>
<url-pattern>
/VirtualName2
</url-pattern>
</servlet-mapping>

Why does my servlet request.getParameter return null?

I'm having a problem with the request. It always returns "null", but I don't know why. I want it to return a name.
This is my servlet:
public class MinServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Syvtabellen - fra en servlet</title></head>");
out.println("<body>");
out.println("<p>Her er syv-tabellen:<br>");
for (int i=1; i<=10; i++)
{
out.println("Syv gange "+ i +" er: "+ 7*i +".<br>");
}
out.println("</body>");
out.println("</html>");
String parameterværdi = request.getParameter("navn");
out.print( "Værdien af parameteren 'navn' er: <br>" + parameterværdi );
}
}
This is the index.xml:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>TODO write content</div>
</body>
This is the web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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_3_1.xsd">
<servlet>
<servlet-name>MinServlet</servlet-name>
<servlet-class>konti.MinServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MinServlet</servlet-name>
<url-pattern>/MinServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
Do I've to add it in the index.xml somehow? I know that the parameter returns null if the parameter doesn't exist, but I don't know how to fix it :)
I believe you are following a tutorial. As Elliott said in his comment you need to have a parameter called "navn" in you view to catch it from your servelet otherwise you will get a null. Or else there should be a query string called "navn". Here I can't see any parameter called "navn" in your client side.
For example: http://www.java4s.com/java-servlet-tutorials/example-of-request-getparameter-retrieve-parameters-from-html-form/
According to your code:
index.html
<font face="verdana" size="2px">
<form action="getVal" method="post">
First way to pass request Param <input type="text" name="navn"><br>
<input type="submit" value="Submit">
</form>
</font>
TestApp.java
public class TestApp extends HttpServlet
{
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
PrintWriter pw=res.getWriter();
res.setContentType("text/html");
String n1=req.getParameter("navn");
pw.println("Requested Value" +n1);
pw.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>sumOfTwoNumbers</servlet-name>
<servlet-class>java4s.OngetParameter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestApp</servlet-name>
<url-pattern>/getVal</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Or else you can pass query string as following
Second way to pass Request param:
index.html
Click here

Part null pointer exception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to upload a file but I get a NullPointerException along the way.
The error I am getting is
SEVERE: java.lang.NullPointerException at servlet.UploadServlet.doPost(UploadServlet.java:36)
on this line:
InputStream is = part.getInputStream();
Here is the code for servlet and jsp page.
UploadServlet
#MultipartConfig(fileSizeThreshold = 1024 * 1024 * 10, maxFileSize = 1024 * 1024 * 50, maxRequestSize = 1024 * 1024 * 50)
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Part part = request.getPart("file");
InputStream is = part.getInputStream();
String filename = getFileName(part);
String relativeWebPath = "/WEB-INF/uploads";
String absoluteFilePath = getServletContext().getRealPath(relativeWebPath);
File uploadedFile = new File(absoluteFilePath, filename);
FileOutputStream os = new FileOutputStream(uploadedFile);
int i = is.read();
while (i != -1) {
os.write(i);
i = is.read();
}
os.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
out.close();
}
}
private String getFileName(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1);
}
}
return null;
}
}
upload.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>MobMel::Upload</title>
</head>
<body>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<table class="upload">
<tr>
<td>File</td>
<td><input type="file" name="file"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Upload"></td>
</tr>
</table>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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_3_1.xsd">
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>servlet.RegisterServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>servlet.LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ProfileServlet</servlet-name>
<servlet-class>servlet.ProfileServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ProfileServlet</servlet-name>
<url-pattern>/ProfileServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
I hope you guys can help me fix this.
Thanks
I think this may help:
https://coderanch.com/t/618813/Null-Pointer-Exception-request-getPart
In brief, you need to add Multipartsconfig annotation. At least in my case the troble has gone.

Categories

Resources